Round Numbers Breakouts Smart Formula Signals and AlertsThis indicator uses Round Numbers breakouts and then uses smart formula with the near Round Numbers to determine best TP (take profit)/SL (stop loss) areas. Furthermore, it calculates win percentage, shows in-profit/in-loss peaks and the price amount result over a customizable date range, which when combined well with the smart formula provides decent profitable outcome. I have decided to write my own backtesting engine as the integrated TradingView strategy one has limitations and has shown inconsistencies when compared to manual backtesting…
There are many settings you can manually change to trade any instrument, any style, any approach and there are presets included for Bitcoin(BTCUSD), FOREX(EURUSD), SPY(S&P500), so you can start trading immediately! Alerts correspond to indicator settings and are turned on with a few clicks. There are 3 tables (each can be shown/hidden) showing everything you need to see/know to calibrate the indicator as you wish.
Labels, lines, tables explanations (everything can be hidden/shown):
- LONG Labels: medium-green: position open, dark-green: SL, bright-green: TP, blue: TP2
- SHORT Labels: medium-red: position open, dark-red: SL, bright-red: TP, purple: TP2
- Gray circles: position entry area | Yellow crosses: SL area
- Green line: Long TP1, Blue line: Long TP2 | Red Line: Short TP1, Purple line: Short TP2
- Grey lines: Round Numbers (customized via “Round Number up/down measure unit” input)
- Yellow labels at end of each week: end of week OVERALL total results
- Red colored background: power segment
- 3 tables: 1) INFO | STATS, 2) SPY Options Calculator, 3) Indicator Settings
If you decide to fully customize the indicator yourself, on the very top - under “PRESETS” select “MANUAL”! NOTE: If you select any of the pre-set presets, only GLOBAL settings can be changed, the rest of the settings will be “frozen” until you switch it to “MANUAL”!
- Global Settings are self-explanatory and mainly observational, show/hide, etc.
- Manual TP2 (Multi-Take-Profit) Settings:
>>>>> Include TP2 System? Turn on/off multi-profit system, with this unchecked, every trade will either end with SL or with TP1.
>>>>> TP2 System: NEAREST/FORMULA, NEAREST – after TP1 is taken > next TP2 will be a round number price target nearest to where TP1 was taken (sometimes it can be very near, sometimes further away…), FORMULA – 2nd round number price target will be optimally selected based on the distance behind and ahead of TP1 area. For TP2 – FORMULA would be the most logical choice as with multi-take-profit setting turned on – you’d want to ride it out as far as possible.
>>>>> TP1/TP2 division type: 1) Each price target (TP1, TP2) will be ½ of the position 2) TP1 will be 2/3 of the position and TP2 will be the remaining 1/3.
>>>>> TP2 hit type: “close” > candle has to close on top/crossing the price target line, “touch” > once candle touches the price target – you will be immediately alerted to take the partial profit (if you will use such setting – you will need to take the partial profits as soon as you receive the alert.
>>>>> TP1 > Back to Entry hit type: similar to TP2, “close” > candle close, “touch” > candle touch. Please note: this is a very tricky setting as if you use “close” option – your profitable trade may become a loss if a huge candle will close against your position eliminating your TP1 profit, however often the price will touch and cross the entry area to only bounce and continue with your position direction for even bigger profits… so experiment with the date range results to see what works best for your instrument/setting/strategy.
>>>>> TP2 count towards trades count: this can be a bit confusing, but it is simply how should TP2 be treated towards trades count. The indicator will show you Win Percentage and Win % is obtained from winning trades count divided by total trades count. While TP2 is not “a new trade”, it expands the profit of the trade. This is an experimental setting to count TP2 as the whole winning trade, ½ of a trade, or not count it at all.
- Manual Signals/TP1 Settings:
>>>>> TP1/TP2 offset: this one is really cool, with this feature you can hunt these conditions when the price comes very near the profit target area, but never touches it. With this setting turned on and with a good offset amount – you will be able to catch these for TP1 and TP2!
>>>>> TP1/TP2 offset amount: just what the title says, please be careful with this as this number varies significantly depending on the instrument you will be trading. Examples: 1) For SPY 0.1 would be $0.10 offset - if TP1 is $400 and price hits $399.90 > TP1 considered taken/signal shown/alert) | 2) For EURUSD, it is very different and if wrong will show TP1 immediately at position open, typical good offset for EURUSD is: 0.0005 | 3) For BTCUSD, 10 - $10 offset, if TP is $15,000 > $14,990, etc.
>>>>> Round Number up/down measure unit (in dollars $): this one is very important if you will be using “MANUAL” selection to build your own setup as it is very different for every instrument. For SPY, round numbers are single dollars or even half-dollar 50 cent numbers: 1 or 0.5 (350, 351, 352, etc. or 350.50, 351, 351.50, 352, etc.), while for Bitcoin (BTCUSD) a single unit ($1) is too small to be a round number as Bitoin moves much faster and wider every second and it would have to be at least 50 ($50) to make sense. Similar for FOREX (EUR/USD) a single 1 unit ($1) will be too big as EURUSD will never move a whole $1 in 15 minutes or even a day.. and would have to be something like 1.05500. You can easily determine if this number makes sense for your instrument by observing the grey Round Number lines which will correspond based on this setting. You can also visually observer if the price of the instrument appreciates these round numbers.
>>>>> Close Position Before Market Closes: just what the title says. Indicator will close the position 15 minutes before market closes (US session), update backtesting stats, alert you.
>>>>> Close Position Before Power Hour: 3PM – 4PM ET is the last hour of US trading session, where sudden move in any direction can happen with huge volatility, while sometimes nothing will happen at all… Many try to avoid it, so if you wish to avoid it as well - turn this on and it will alert you to close your positions 15 minutes before Power Hour starts, backtesting/stats will be adjusted accordingly.
>>>>> Skip OVERSIZED candles in signals: turn on this setting to skip signals, which happen to fall on big candles. This is basically a protection from huge volatility moves, which usually happen during financial news/events and if you are not a fan of these – you can set this option for indicator to not open anything based on the candle size.
>>>>> Color OVERSIZED candles: this will help you calibrate the size of the OVERSIZED candles if you decide to use this setting and overall visually see them.
>>>>> OVERSIZED candle size: OVERSIZED candle size must be input as it varies significantly. Please note: for each instrument – the size number is completely different, as for SPY: 2 would mean any candle bigger than $2 distance will be considered OVERSIZED, for Bitcoin it would have to be several hundred dollars, like 400-500. For FOREX, this would have to be a decimal, for EURUSD something like 0.0005. It’s best to experiment visually with this setting depending on the instrument you will be trading while setting up the size. To see a typical huge unusual candle – look up financial calendar for something like FOMC meeting, then measure the candle input it into this setting.
>>>>> OVERSIZED candle size calculation type: this is just more flexibility for your preference. If you wish to calculate the size of the candle based on the open/close – select “BODY”, if you wish to use high/low – select “STICKS (from tip to tip)”. Hard to say which one is better, so it is up to you to decide.
>>>>> Include EMA in signal formula: LONG signals will only be shown only if above EMA, SHORT if below EMA. EMA length is of course customizable in below.
>>>>> Skip opposite candle types in signals: signals where the candle color confirms the direction of the trade, but the candle type is opposite (like a green colored bearish hammer for example) will be avoided (such candles can be very uncertain/deceptive).
>>>>> Skip doji: signals where the signal candle is doji (uncertain) will be avoided.
>>>>> TP1 hit type/system: same thing as TP2 hit type/system.
>>>>> SL hit type/system: same as TP1 and TP2 types/systems.
>>>>> Intraday Session Signals Active Time in ET: time range during the day when indicator will show signals (open trades, alert you, etc.). This is specifically for intraday trading. You can turn it off completely by selecting a BLANK option.
>>>>> Intraday TP/SL Active Time in ET: same as above, but for taking profits/stop losses.
*** To add the alerts
-Right-click anywhere on the TradingView chart
-Click on Add alert
-Condition: Select this indicator by it’s name
-Alert name: Whatever you want
-Hit “Create”
-Note: If you change ANY Settings within the indicator – you must DELETE the current alert and create a new one per steps above, otherwise it will continue triggering alerts per old Settings!
If you wish to try this out for a week or so – please write me directly and I will give you access.
Cerca negli script per "spy"
Market First Signals - Relative Strength/WeaknessThis market-first trading strategy gives BUY, SHORT, and CLOSE signals based on volume, trend, and relative strength or weakness to the market (SPY by default, can be customized). This indicator is useful for signaling day-trade entries and exits for tickers that are strong (or weak) against the market.
Stocks that are showing relative strength (or weakness) to the market, are trending, and have decent movement generate a buy (or short) signal. When the trend runs out, a CLOSE signal is fired.
Potential profit (based on ATR) and actual profit is calculated, predicting the type of move expected
Unique 'stay in trade' logic helps prevent unnecessary CLOSE signals if a trend is likely to continue
A colored plot indicates the strength of the current trend and turns orange/red when the strength is weakened.
Crypto traders can uncheck 'Trade during market hours' for 24-hour trading, and should change the comparison ticker from SPY to BTCUSD or something similar for their market.
Enjoy!
KEY CONCEPTS
The three- and five-minute timeframes are used to establish and verify trend (ADX/DI with custom logic)
Entries and exits are based on Parabolic SAR and confirmed on multiple timeframes, trend, and relative volume
Relative strength /weakness to the market compares ticker to SPY
Chop is avoided at all costs. I've experimented with choppiness indicator below 38, but found that the ADX DI+/- readings work even better.
Trend is established using ADX DI+/- readings over 20, confirmed by EMA 5/13 crossover and EMA5 slope
Signals will fire only if the average volume for the current 5-min bar is above normal
Only tickers with a five-bar / 13 period ATR of 1% the ticker's price generate signal.
Only longs above daily-anchored VWAP, shorts below daily-anchored VWAP
Signals fire on bar close to prevent repainting / look-ahead bias
Indicator labels and alerts generated
SIGNALS
BUY: up-trending tickers showing relative strength are bought on the three-minute PSAR
SELL: when the close price falls below the 1, 3, and 5-minute PSAR, or the ADX DI- falls below 20
SHORT: down-trending tickers with relative weakness are shorted on the three-minute PSAR
COVER: when the close price moves above the 1, 3, and 5-minute PSAR, or the ADX DI- falls below 20
ALERTS
Alerts are generated on BUY, SELL, SHORT, and COVER signals, as well as optional LOST RELATIVE STRENGTH and LOST RELATIVE WEAKNESS
INPUTS
Use relative strength/weakness comparison with the market : trigger trades based on the ticker's strength or weakness to the selected comparison ticker (usually SPY for equities or BTCUSD for crypto)
Comparison Ticker for relative strength/weakness : Ticker to compare against for relative strength/weakness
Trade during market hours only : Take buy/sells during specified hours. Disable this for crypto trading.
Market hours (market time) : Customize market hours - defaults to 9:30 to 16:00 EST
"Only trade very strong trends" : take trades only if an established trend is very strong (ADX over 40) (DEFAULT = OFF)
"Limit trade direction to VWAP" : Long trades only above VWAP, shorts below (DEFAULT = ON)
"Limit trade direction to Market direction" : Long trades only if SPY (or selected comparison ticker) is up, shorts if the market is down. (DEFAULT= OFF)
"Limit trades based on a ticker's green/red status for the day" : Long trades if the ticker is green for the day, shorts if red. (DEFAULT = OFF)
RSI and market strength with alerts By combining the true strength of the Nasdaq (NDX) and S&P500 ( SPY ) we can then compare that against the volatility /fear index ( VIX ). The true strength of the Volatility Index ( VIX ) is shown by the red area and the Nasdaq (NDX) and S&P500 ( SPY ) by the silver /teal areas.
The yellow EMA area shows the average difference between the VIX and the NDX/ SPY indexes. When the yellow area crosses above the zero line and is climbing it means that the NDX/ SPY are strengthening. When the yellow area is decreasing or crosses under the zero line it means the fear/volatility index ( VIX ) is becoming stronger and NDX/ SPY are weakening. The RSI is overlaid as a white line to show the correlation of the instrument strength compared to the market.
When looking at charts of companies/components listed on the Nasdaq and/or S&P 500 you will notice a frequent correlation between the movement of the yellow area depicting index health and the RSI of the chart you are viewing. It’s a very quick and effective method of seeing the strength and fear within the market indexes and how they are effecting your chart.
The background color changes when the market strength combined with the active symbol RSI and higher timeframe MACD signals are aligned. Green is a buy zone, Red is a sell zone.
There are also red and green indicator x’s at the top/bottom of the indicator. They show a drastic change in Relative strength within a short period. This often indicates a buy or sell opportunity.
It is tested and works well on all timeframes with Stocks listed on NASDAQ & S&P500 .
Buy, Sell, Exit Buy and Exit Sell alerts are included.
There are also red and green indicator x’s at the top/bottom of the indicator. They show a drastic change in Relative strength within a short period. This often indicates a buy or sell opportunity.
Market Index Strength by Keiron RichieBy combining the true strength of the Nasdaq (NDX) and S&P500 (SPY) we can then compare that against the volatility /fear index (VIX). The true strength of the Volatility Index (VIX) is shown by the red area and the Nasdaq (NDX) and S&P500 (SPY) by the silver/teal areas.
The yellow EMA line shows the average difference between the VIX and the NDX/SPY indexes. When the yellow line crosses above the zero line and is climbing it means that the NDX/SPY are strengthening. When the yellow line is decreasing or crosses under the zero line it means the fear (VIX) is becoming stronger and NDX/SPY are weakening.
When looking at charts of companies/components listed on the Nasdaq and/or S&P 500 you will notice a frequent correlation between the movement of the yellow line depicting index health and the strength of the chart you are viewing. It’s a very quick and effective method of seeing the strength and fear within the market indexes and how they are effecting your chart.
The background color changes based on the market strength combined with the active symbol true strength. Green is a buy zone, Red is a sell zone.
It is tested and works well on all timeframes with Stocks listed on NASDAQ & S&P500. It does not include buy/sell alerts.
Kelly Position Size CalculatorThis position sizing calculator implements the Kelly Criterion, developed by John L. Kelly Jr. at Bell Laboratories in 1956, to determine mathematically optimal position sizes for maximizing long-term wealth growth. Unlike arbitrary position sizing methods, this tool provides a scientifically solution based on your strategy's actual performance statistics and incorporates modern refinements from over six decades of academic research.
The Kelly Criterion addresses a fundamental question in capital allocation: "What fraction of capital should be allocated to each opportunity to maximize growth while avoiding ruin?" This question has profound implications for financial markets, where traders and investors constantly face decisions about optimal capital allocation (Van Tharp, 2007).
Theoretical Foundation
The Kelly Criterion for binary outcomes is expressed as f* = (bp - q) / b, where f* represents the optimal fraction of capital to allocate, b denotes the risk-reward ratio, p indicates the probability of success, and q represents the probability of loss (Kelly, 1956). This formula maximizes the expected logarithm of wealth, ensuring maximum long-term growth rate while avoiding the risk of ruin.
The mathematical elegance of Kelly's approach lies in its derivation from information theory. Kelly's original work was motivated by Claude Shannon's information theory (Shannon, 1948), recognizing that maximizing the logarithm of wealth is equivalent to maximizing the rate of information transmission. This connection between information theory and wealth accumulation provides a deep theoretical foundation for optimal position sizing.
The logarithmic utility function underlying the Kelly Criterion naturally embodies several desirable properties for capital management. It exhibits decreasing marginal utility, penalizes large losses more severely than it rewards equivalent gains, and focuses on geometric rather than arithmetic mean returns, which is appropriate for compounding scenarios (Thorp, 2006).
Scientific Implementation
This calculator extends beyond basic Kelly implementation by incorporating state of the art refinements from academic research:
Parameter Uncertainty Adjustment: Following Michaud (1989), the implementation applies Bayesian shrinkage to account for parameter estimation error inherent in small sample sizes. The adjustment formula f_adjusted = f_kelly × confidence_factor + f_conservative × (1 - confidence_factor) addresses the overconfidence bias documented by Baker and McHale (2012), where the confidence factor increases with sample size and the conservative estimate equals 0.25 (quarter Kelly).
Sample Size Confidence: The reliability of Kelly calculations depends critically on sample size. Research by Browne and Whitt (1996) provides theoretical guidance on minimum sample requirements, suggesting that at least 30 independent observations are necessary for meaningful parameter estimates, with 100 or more trades providing reliable estimates for most trading strategies.
Universal Asset Compatibility: The calculator employs intelligent asset detection using TradingView's built-in symbol information, automatically adapting calculations for different asset classes without manual configuration.
ASSET SPECIFIC IMPLEMENTATION
Equity Markets: For stocks and ETFs, position sizing follows the calculation Shares = floor(Kelly Fraction × Account Size / Share Price). This straightforward approach reflects whole share constraints while accommodating fractional share trading capabilities.
Foreign Exchange Markets: Forex markets require lot-based calculations following Lot Size = Kelly Fraction × Account Size / (100,000 × Base Currency Value). The calculator automatically handles major currency pairs with appropriate pip value calculations, following industry standards described by Archer (2010).
Futures Markets: Futures position sizing accounts for leverage and margin requirements through Contracts = floor(Kelly Fraction × Account Size / Margin Requirement). The calculator estimates margin requirements as a percentage of contract notional value, with specific adjustments for micro-futures contracts that have smaller sizes and reduced margin requirements (Kaufman, 2013).
Index and Commodity Markets: These markets combine characteristics of both equity and futures markets. The calculator automatically detects whether instruments are cash-settled or futures-based, applying appropriate sizing methodologies with correct point value calculations.
Risk Management Integration
The calculator integrates sophisticated risk assessment through two primary modes:
Stop Loss Integration: When fixed stop-loss levels are defined, risk calculation follows Risk per Trade = Position Size × Stop Loss Distance. This ensures that the Kelly fraction accounts for actual risk exposure rather than theoretical maximum loss, with stop-loss distance measured in appropriate units for each asset class.
Strategy Drawdown Assessment: For discretionary exit strategies, risk estimation uses maximum historical drawdown through Risk per Trade = Position Value × (Maximum Drawdown / 100). This approach assumes that individual trade losses will not exceed the strategy's historical maximum drawdown, providing a reasonable estimate for strategies with well-defined risk characteristics.
Fractional Kelly Approaches
Pure Kelly sizing can produce substantial volatility, leading many practitioners to adopt fractional Kelly approaches. MacLean, Sanegre, Zhao, and Ziemba (2004) analyze the trade-offs between growth rate and volatility, demonstrating that half-Kelly typically reduces volatility by approximately 75% while sacrificing only 25% of the growth rate.
The calculator provides three primary Kelly modes to accommodate different risk preferences and experience levels. Full Kelly maximizes growth rate while accepting higher volatility, making it suitable for experienced practitioners with strong risk tolerance and robust capital bases. Half Kelly offers a balanced approach popular among professional traders, providing optimal risk-return balance by reducing volatility significantly while maintaining substantial growth potential. Quarter Kelly implements a conservative approach with low volatility, recommended for risk-averse traders or those new to Kelly methodology who prefer gradual introduction to optimal position sizing principles.
Empirical Validation and Performance
Extensive academic research supports the theoretical advantages of Kelly sizing. Hakansson and Ziemba (1995) provide a comprehensive review of Kelly applications in finance, documenting superior long-term performance across various market conditions and asset classes. Estrada (2008) analyzes Kelly performance in international equity markets, finding that Kelly-based strategies consistently outperform fixed position sizing approaches over extended periods across 19 developed markets over a 30-year period.
Several prominent investment firms have successfully implemented Kelly-based position sizing. Pabrai (2007) documents the application of Kelly principles at Berkshire Hathaway, noting Warren Buffett's concentrated portfolio approach aligns closely with Kelly optimal sizing for high-conviction investments. Quantitative hedge funds, including Renaissance Technologies and AQR, have incorporated Kelly-based risk management into their systematic trading strategies.
Practical Implementation Guidelines
Successful Kelly implementation requires systematic application with attention to several critical factors:
Parameter Estimation: Accurate parameter estimation represents the greatest challenge in practical Kelly implementation. Brown (1976) notes that small errors in probability estimates can lead to significant deviations from optimal performance. The calculator addresses this through Bayesian adjustments and confidence measures.
Sample Size Requirements: Users should begin with conservative fractional Kelly approaches until achieving sufficient historical data. Strategies with fewer than 30 trades may produce unreliable Kelly estimates, regardless of adjustments. Full confidence typically requires 100 or more independent trade observations.
Market Regime Considerations: Parameters that accurately describe historical performance may not reflect future market conditions. Ziemba (2003) recommends regular parameter updates and conservative adjustments when market conditions change significantly.
Professional Features and Customization
The calculator provides comprehensive customization options for professional applications:
Multiple Color Schemes: Eight professional color themes (Gold, EdgeTools, Behavioral, Quant, Ocean, Fire, Matrix, Arctic) with dark and light theme compatibility ensure optimal visibility across different trading environments.
Flexible Display Options: Adjustable table size and position accommodate various chart layouts and user preferences, while maintaining analytical depth and clarity.
Comprehensive Results: The results table presents essential information including asset specifications, strategy statistics, Kelly calculations, sample confidence measures, position values, risk assessments, and final position sizes in appropriate units for each asset class.
Limitations and Considerations
Like any analytical tool, the Kelly Criterion has important limitations that users must understand:
Stationarity Assumption: The Kelly Criterion assumes that historical strategy statistics represent future performance characteristics. Non-stationary market conditions may invalidate this assumption, as noted by Lo and MacKinlay (1999).
Independence Requirement: Each trade should be independent to avoid correlation effects. Many trading strategies exhibit serial correlation in returns, which can affect optimal position sizing and may require adjustments for portfolio applications.
Parameter Sensitivity: Kelly calculations are sensitive to parameter accuracy. Regular calibration and conservative approaches are essential when parameter uncertainty is high.
Transaction Costs: The implementation incorporates user-defined transaction costs but assumes these remain constant across different position sizes and market conditions, following Ziemba (2003).
Advanced Applications and Extensions
Multi-Asset Portfolio Considerations: While this calculator optimizes individual position sizes, portfolio-level applications require additional considerations for correlation effects and aggregate risk management. Simplified portfolio approaches include treating positions independently with correlation adjustments.
Behavioral Factors: Behavioral finance research reveals systematic biases that can interfere with Kelly implementation. Kahneman and Tversky (1979) document loss aversion, overconfidence, and other cognitive biases that lead traders to deviate from optimal strategies. Successful implementation requires disciplined adherence to calculated recommendations.
Time-Varying Parameters: Advanced implementations may incorporate time-varying parameter models that adjust Kelly recommendations based on changing market conditions, though these require sophisticated econometric techniques and substantial computational resources.
Comprehensive Usage Instructions and Practical Examples
Implementation begins with loading the calculator on your desired trading instrument's chart. The system automatically detects asset type across stocks, forex, futures, and cryptocurrency markets while extracting current price information. Navigation to the indicator settings allows input of your specific strategy parameters.
Strategy statistics configuration requires careful attention to several key metrics. The win rate should be calculated from your backtest results using the formula of winning trades divided by total trades multiplied by 100. Average win represents the sum of all profitable trades divided by the number of winning trades, while average loss calculates the sum of all losing trades divided by the number of losing trades, entered as a positive number. The total historical trades parameter requires the complete number of trades in your backtest, with a minimum of 30 trades recommended for basic functionality and 100 or more trades optimal for statistical reliability. Account size should reflect your available trading capital, specifically the risk capital allocated for trading rather than total net worth.
Risk management configuration adapts to your specific trading approach. The stop loss setting should be enabled if you employ fixed stop-loss exits, with the stop loss distance specified in appropriate units depending on the asset class. For stocks, this distance is measured in dollars, for forex in pips, and for futures in ticks. When stop losses are not used, the maximum strategy drawdown percentage from your backtest provides the risk assessment baseline. Kelly mode selection offers three primary approaches: Full Kelly for aggressive growth with higher volatility suitable for experienced practitioners, Half Kelly for balanced risk-return optimization popular among professional traders, and Quarter Kelly for conservative approaches with reduced volatility.
Display customization ensures optimal integration with your trading environment. Eight professional color themes provide optimization for different chart backgrounds and personal preferences. Table position selection allows optimal placement within your chart layout, while table size adjustment ensures readability across different screen resolutions and viewing preferences.
Detailed Practical Examples
Example 1: SPY Swing Trading Strategy
Consider a professionally developed swing trading strategy for SPY (S&P 500 ETF) with backtesting results spanning 166 total trades. The strategy achieved 110 winning trades, representing a 66.3% win rate, with an average winning trade of $2,200 and average losing trade of $862. The maximum drawdown reached 31.4% during the testing period, and the available trading capital amounts to $25,000. This strategy employs discretionary exits without fixed stop losses.
Implementation requires loading the calculator on the SPY daily chart and configuring the parameters accordingly. The win rate input receives 66.3, while average win and loss inputs receive 2200 and 862 respectively. Total historical trades input requires 166, with account size set to 25000. The stop loss function remains disabled due to the discretionary exit approach, with maximum strategy drawdown set to 31.4%. Half Kelly mode provides the optimal balance between growth and risk management for this application.
The calculator generates several key outputs for this scenario. The risk-reward ratio calculates automatically to 2.55, while the Kelly fraction reaches approximately 53% before scientific adjustments. Sample confidence achieves 100% given the 166 trades providing high statistical confidence. The recommended position settles at approximately 27% after Half Kelly and Bayesian adjustment factors. Position value reaches approximately $6,750, translating to 16 shares at a $420 SPY price. Risk per trade amounts to approximately $2,110, representing 31.4% of position value, with expected value per trade reaching approximately $1,466. This recommendation represents the mathematically optimal balance between growth potential and risk management for this specific strategy profile.
Example 2: EURUSD Day Trading with Stop Losses
A high-frequency EURUSD day trading strategy demonstrates different parameter requirements compared to swing trading approaches. This strategy encompasses 89 total trades with a 58% win rate, generating an average winning trade of $180 and average losing trade of $95. The maximum drawdown reached 12% during testing, with available capital of $10,000. The strategy employs fixed stop losses at 25 pips and take profit targets at 45 pips, providing clear risk-reward parameters.
Implementation begins with loading the calculator on the EURUSD 1-hour chart for appropriate timeframe alignment. Parameter configuration includes win rate at 58, average win at 180, and average loss at 95. Total historical trades input receives 89, with account size set to 10000. The stop loss function is enabled with distance set to 25 pips, reflecting the fixed exit strategy. Quarter Kelly mode provides conservative positioning due to the smaller sample size compared to the previous example.
Results demonstrate the impact of smaller sample sizes on Kelly calculations. The risk-reward ratio calculates to 1.89, while the Kelly fraction reaches approximately 32% before adjustments. Sample confidence achieves 89%, providing moderate statistical confidence given the 89 trades. The recommended position settles at approximately 7% after Quarter Kelly application and Bayesian shrinkage adjustment for the smaller sample. Position value amounts to approximately $700, translating to 0.07 standard lots. Risk per trade reaches approximately $175, calculated as 25 pips multiplied by lot size and pip value, with expected value per trade at approximately $49. This conservative position sizing reflects the smaller sample size, with position sizes expected to increase as trade count surpasses 100 and statistical confidence improves.
Example 3: ES1! Futures Systematic Strategy
Systematic futures trading presents unique considerations for Kelly criterion application, as demonstrated by an E-mini S&P 500 futures strategy encompassing 234 total trades. This systematic approach achieved a 45% win rate with an average winning trade of $1,850 and average losing trade of $720. The maximum drawdown reached 18% during the testing period, with available capital of $50,000. The strategy employs 15-tick stop losses with contract specifications of $50 per tick, providing precise risk control mechanisms.
Implementation involves loading the calculator on the ES1! 15-minute chart to align with the systematic trading timeframe. Parameter configuration includes win rate at 45, average win at 1850, and average loss at 720. Total historical trades receives 234, providing robust statistical foundation, with account size set to 50000. The stop loss function is enabled with distance set to 15 ticks, reflecting the systematic exit methodology. Half Kelly mode balances growth potential with appropriate risk management for futures trading.
Results illustrate how favorable risk-reward ratios can support meaningful position sizing despite lower win rates. The risk-reward ratio calculates to 2.57, while the Kelly fraction reaches approximately 16%, lower than previous examples due to the sub-50% win rate. Sample confidence achieves 100% given the 234 trades providing high statistical confidence. The recommended position settles at approximately 8% after Half Kelly adjustment. Estimated margin per contract amounts to approximately $2,500, resulting in a single contract allocation. Position value reaches approximately $2,500, with risk per trade at $750, calculated as 15 ticks multiplied by $50 per tick. Expected value per trade amounts to approximately $508. Despite the lower win rate, the favorable risk-reward ratio supports meaningful position sizing, with single contract allocation reflecting appropriate leverage management for futures trading.
Example 4: MES1! Micro-Futures for Smaller Accounts
Micro-futures contracts provide enhanced accessibility for smaller trading accounts while maintaining identical strategy characteristics. Using the same systematic strategy statistics from the previous example but with available capital of $15,000 and micro-futures specifications of $5 per tick with reduced margin requirements, the implementation demonstrates improved position sizing granularity.
Kelly calculations remain identical to the full-sized contract example, maintaining the same risk-reward dynamics and statistical foundations. However, estimated margin per contract reduces to approximately $250 for micro-contracts, enabling allocation of 4-5 micro-contracts. Position value reaches approximately $1,200, while risk per trade calculates to $75, derived from 15 ticks multiplied by $5 per tick. This granularity advantage provides better position size precision for smaller accounts, enabling more accurate Kelly implementation without requiring large capital commitments.
Example 5: Bitcoin Swing Trading
Cryptocurrency markets present unique challenges requiring modified Kelly application approaches. A Bitcoin swing trading strategy on BTCUSD encompasses 67 total trades with a 71% win rate, generating average winning trades of $3,200 and average losing trades of $1,400. Maximum drawdown reached 28% during testing, with available capital of $30,000. The strategy employs technical analysis for exits without fixed stop losses, relying on price action and momentum indicators.
Implementation requires conservative approaches due to cryptocurrency volatility characteristics. Quarter Kelly mode is recommended despite the high win rate to account for crypto market unpredictability. Expected position sizing remains reduced due to the limited sample size of 67 trades, requiring additional caution until statistical confidence improves. Regular parameter updates are strongly recommended due to cryptocurrency market evolution and changing volatility patterns that can significantly impact strategy performance characteristics.
Advanced Usage Scenarios
Portfolio position sizing requires sophisticated consideration when running multiple strategies simultaneously. Each strategy should have its Kelly fraction calculated independently to maintain mathematical integrity. However, correlation adjustments become necessary when strategies exhibit related performance patterns. Moderately correlated strategies should receive individual position size reductions of 10-20% to account for overlapping risk exposure. Aggregate portfolio risk monitoring ensures total exposure remains within acceptable limits across all active strategies. Professional practitioners often consider using lower fractional Kelly approaches, such as Quarter Kelly, when running multiple strategies simultaneously to provide additional safety margins.
Parameter sensitivity analysis forms a critical component of professional Kelly implementation. Regular validation procedures should include monthly parameter updates using rolling 100-trade windows to capture evolving market conditions while maintaining statistical relevance. Sensitivity testing involves varying win rates by ±5% and average win/loss ratios by ±10% to assess recommendation stability under different parameter assumptions. Out-of-sample validation reserves 20% of historical data for parameter verification, ensuring that optimization doesn't create curve-fitted results. Regime change detection monitors actual performance against expected metrics, triggering parameter reassessment when significant deviations occur.
Risk management integration requires professional overlay considerations beyond pure Kelly calculations. Daily loss limits should cease trading when daily losses exceed twice the calculated risk per trade, preventing emotional decision-making during adverse periods. Maximum position limits should never exceed 25% of account value in any single position regardless of Kelly recommendations, maintaining diversification principles. Correlation monitoring reduces position sizes when holding multiple correlated positions that move together during market stress. Volatility adjustments consider reducing position sizes during periods of elevated VIX above 25 for equity strategies, adapting to changing market conditions.
Troubleshooting and Optimization
Professional implementation often encounters specific challenges requiring systematic troubleshooting approaches. Zero position size displays typically result from insufficient capital for minimum position sizes, negative expected values, or extremely conservative Kelly calculations. Solutions include increasing account size, verifying strategy statistics for accuracy, considering Quarter Kelly mode for conservative approaches, or reassessing overall strategy viability when fundamental issues exist.
Extremely high Kelly fractions exceeding 50% usually indicate underlying problems with parameter estimation. Common causes include unrealistic win rates, inflated risk-reward ratios, or curve-fitted backtest results that don't reflect genuine trading conditions. Solutions require verifying backtest methodology, including all transaction costs in calculations, testing strategies on out-of-sample data, and using conservative fractional Kelly approaches until parameter reliability improves.
Low sample confidence below 50% reflects insufficient historical trades for reliable parameter estimation. This situation demands gathering additional trading data, using Quarter Kelly approaches until reaching 100 or more trades, applying extra conservatism in position sizing, and considering paper trading to build statistical foundations without capital risk.
Inconsistent results across similar strategies often stem from parameter estimation differences, market regime changes, or strategy degradation over time. Professional solutions include standardizing backtest methodology across all strategies, updating parameters regularly to reflect current conditions, and monitoring live performance against expectations to identify deteriorating strategies.
Position sizes that appear inappropriately large or small require careful validation against traditional risk management principles. Professional standards recommend never risking more than 2-3% per trade regardless of Kelly calculations. Calibration should begin with Quarter Kelly approaches, gradually increasing as comfort and confidence develop. Most institutional traders utilize 25-50% of full Kelly recommendations to balance growth with prudent risk management.
Market condition adjustments require dynamic approaches to Kelly implementation. Trending markets may support full Kelly recommendations when directional momentum provides favorable conditions. Ranging or volatile markets typically warrant reducing to Half or Quarter Kelly to account for increased uncertainty. High correlation periods demand reducing individual position sizes when multiple positions move together, concentrating risk exposure. News and event periods often justify temporary position size reductions during high-impact releases that can create unpredictable market movements.
Performance monitoring requires systematic protocols to ensure Kelly implementation remains effective over time. Weekly reviews should compare actual versus expected win rates and average win/loss ratios to identify parameter drift or strategy degradation. Position size efficiency and execution quality monitoring ensures that calculated recommendations translate effectively into actual trading results. Tracking correlation between calculated and realized risk helps identify discrepancies between theoretical and practical risk exposure.
Monthly calibration provides more comprehensive parameter assessment using the most recent 100 trades to maintain statistical relevance while capturing current market conditions. Kelly mode appropriateness requires reassessment based on recent market volatility and performance characteristics, potentially shifting between Full, Half, and Quarter Kelly approaches as conditions change. Transaction cost evaluation ensures that commission structures, spreads, and slippage estimates remain accurate and current.
Quarterly strategic reviews encompass comprehensive strategy performance analysis comparing long-term results against expectations and identifying trends in effectiveness. Market regime assessment evaluates parameter stability across different market conditions, determining whether strategy characteristics remain consistent or require fundamental adjustments. Strategic modifications to position sizing methodology may become necessary as markets evolve or trading approaches mature, ensuring that Kelly implementation continues supporting optimal capital allocation objectives.
Professional Applications
This calculator serves diverse professional applications across the financial industry. Quantitative hedge funds utilize the implementation for systematic position sizing within algorithmic trading frameworks, where mathematical precision and consistent application prove essential for institutional capital management. Professional discretionary traders benefit from optimized position management that removes emotional bias while maintaining flexibility for market-specific adjustments. Portfolio managers employ the calculator for developing risk-adjusted allocation strategies that enhance returns while maintaining prudent risk controls across diverse asset classes and investment strategies.
Individual traders seeking mathematical optimization of capital allocation find the calculator provides institutional-grade methodology previously available only to professional money managers. The Kelly Criterion establishes theoretical foundation for optimal capital allocation across both single strategies and multiple trading systems, offering significant advantages over arbitrary position sizing methods that rely on intuition or fixed percentage approaches. Professional implementation ensures consistent application of mathematically sound principles while adapting to changing market conditions and strategy performance characteristics.
Conclusion
The Kelly Criterion represents one of the few mathematically optimal solutions to fundamental investment problems. When properly understood and carefully implemented, it provides significant competitive advantage in financial markets. This calculator implements modern refinements to Kelly's original formula while maintaining accessibility for practical trading applications.
Success with Kelly requires ongoing learning, systematic application, and continuous refinement based on market feedback and evolving research. Users who master Kelly principles and implement them systematically can expect superior risk-adjusted returns and more consistent capital growth over extended periods.
The extensive academic literature provides rich resources for deeper study, while practical experience builds the intuition necessary for effective implementation. Regular parameter updates, conservative approaches with limited data, and disciplined adherence to calculated recommendations are essential for optimal results.
References
Archer, M. D. (2010). Getting Started in Currency Trading: Winning in Today's Forex Market (3rd ed.). John Wiley & Sons.
Baker, R. D., & McHale, I. G. (2012). An empirical Bayes approach to optimising betting strategies. Journal of the Royal Statistical Society: Series D (The Statistician), 61(1), 75-92.
Breiman, L. (1961). Optimal gambling systems for favorable games. In J. Neyman (Ed.), Proceedings of the Fourth Berkeley Symposium on Mathematical Statistics and Probability (pp. 65-78). University of California Press.
Brown, D. B. (1976). Optimal portfolio growth: Logarithmic utility and the Kelly criterion. In W. T. Ziemba & R. G. Vickson (Eds.), Stochastic Optimization Models in Finance (pp. 1-23). Academic Press.
Browne, S., & Whitt, W. (1996). Portfolio choice and the Bayesian Kelly criterion. Advances in Applied Probability, 28(4), 1145-1176.
Estrada, J. (2008). Geometric mean maximization: An overlooked portfolio approach? The Journal of Investing, 17(4), 134-147.
Hakansson, N. H., & Ziemba, W. T. (1995). Capital growth theory. In R. A. Jarrow, V. Maksimovic, & W. T. Ziemba (Eds.), Handbooks in Operations Research and Management Science (Vol. 9, pp. 65-86). Elsevier.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. Econometrica, 47(2), 263-291.
Kaufman, P. J. (2013). Trading Systems and Methods (5th ed.). John Wiley & Sons.
Kelly Jr, J. L. (1956). A new interpretation of information rate. Bell System Technical Journal, 35(4), 917-926.
Lo, A. W., & MacKinlay, A. C. (1999). A Non-Random Walk Down Wall Street. Princeton University Press.
MacLean, L. C., Sanegre, E. O., Zhao, Y., & Ziemba, W. T. (2004). Capital growth with security. Journal of Economic Dynamics and Control, 28(4), 937-954.
MacLean, L. C., Thorp, E. O., & Ziemba, W. T. (2011). The Kelly Capital Growth Investment Criterion: Theory and Practice. World Scientific.
Michaud, R. O. (1989). The Markowitz optimization enigma: Is 'optimized' optimal? Financial Analysts Journal, 45(1), 31-42.
Pabrai, M. (2007). The Dhandho Investor: The Low-Risk Value Method to High Returns. John Wiley & Sons.
Shannon, C. E. (1948). A mathematical theory of communication. Bell System Technical Journal, 27(3), 379-423.
Tharp, V. K. (2007). Trade Your Way to Financial Freedom (2nd ed.). McGraw-Hill.
Thorp, E. O. (2006). The Kelly criterion in blackjack sports betting, and the stock market. In L. C. MacLean, E. O. Thorp, & W. T. Ziemba (Eds.), The Kelly Capital Growth Investment Criterion: Theory and Practice (pp. 789-832). World Scientific.
Van Tharp, K. (2007). Trade Your Way to Financial Freedom (2nd ed.). McGraw-Hill Education.
Vince, R. (1992). The Mathematics of Money Management: Risk Analysis Techniques for Traders. John Wiley & Sons.
Vince, R., & Zhu, H. (2015). Optimal betting under parameter uncertainty. Journal of Statistical Planning and Inference, 161, 19-31.
Ziemba, W. T. (2003). The Stochastic Programming Approach to Asset, Liability, and Wealth Management. The Research Foundation of AIMR.
Further Reading
For comprehensive understanding of Kelly Criterion applications and advanced implementations:
MacLean, L. C., Thorp, E. O., & Ziemba, W. T. (2011). The Kelly Capital Growth Investment Criterion: Theory and Practice. World Scientific.
Vince, R. (1992). The Mathematics of Money Management: Risk Analysis Techniques for Traders. John Wiley & Sons.
Thorp, E. O. (2017). A Man for All Markets: From Las Vegas to Wall Street. Random House.
Cover, T. M., & Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). John Wiley & Sons.
Ziemba, W. T., & Vickson, R. G. (Eds.). (2006). Stochastic Optimization Models in Finance. World Scientific.
Mean Reversion Trading With IV Metrics (By MC) - Mobile FriendlyThis script is a comprehensive toolkit for traders who want to combine price mean reversion analysis with advanced volatility metrics, including Implied Volatility Rank (IVR), Implied/“Fair” Volatility projections, and real-time market volatility indicators. It is optimized for both desktop and mobile use, providing a detailed statistics table directly on the chart, and is suitable for stocks, ETFs, indices, and even paired asset analysis.
Key Features & How They Work Together
1. Mean Reversion Probability & Z-Score
Mean Reversion Analysis: Calculates z-scores and statistical probabilities that the asset’s price will revert to its mean, using customizable lookback windows (e.g., 10-60 bars). This helps traders spot potentially overbought or oversold conditions.
Strong & Moderate Signals: Highlights strong and moderate reversion opportunities based on user-defined probability thresholds, providing clear visual cues for timing entries and exits.
2. Paired Asset Correlation
Pairs Trading Support: Allows comparison of two symbols (e.g., SPY vs TLT). It computes the ratio, rolling mean, standard deviation, and correlation, helping traders identify divergence/convergence opportunities in pairs trading.
3. Volatility Metrics & Projections
Historical & Implied Volatility: Estimates implied volatility (IV) using historical price data, calculates IVR (the asset’s IV relative to its own history), and provides user-customized percentile bands (e.g., 20th/80th percentiles).
Fair IV Calculation: Offers three methods to compute “fair” volatility:
Market-Aware (relative to VIX/SPX HV)
SMA of historical volatility
SMA of VIX Traders can choose the method that best fits current market conditions.
Future Projections: Projects IV, “Fair” IV, and IVR for a user-defined future period, giving insight into potential volatility trends.
4. Implied Move Range
Implied Move Calculation: Shows the expected price range (upper/lower bounds) for the forecast period based on the current IV, making risk management and target setting more objective.
Dynamic Labels: Automatically updates labels with the latest projected moves and bounds, keeping traders informed in real time.
5. Market Volatility Dashboard
Broad Market Indicators: Displays real-time values and daily changes for VIX, VIX1D, VVIX, MOVE (bond volatility), GVZ (gold volatility), and OVX (oil volatility). Color-coded thresholds help traders gauge market stress across asset classes.
Correlation to SPY: Shows how closely the asset moves with SPY, aiding in diversification and hedging decisions.
6. Performance Metrics
Daily Move Analysis: Tracks today’s price move (absolute and percentage), average rises/falls, and the percentage of green/red days over a custom period.
Trade Quality Assessment: Ranks trade opportunities (High/Moderate/Low/Very Low) based on mean reversion probability.
7. Highly Customizable Table
Mobile Friendly: The stats table can be placed anywhere on the chart, toggled between compact/full/extra modes, and resized for readability on any device.
Visual Cues: Color coding and dynamic labels make interpretation easy and fast.
8. Alert Conditions
Built-in alerts for strong/moderate mean reversion, IV crossing above/below “Fair” IV, allowing proactive trade management.
9. VIX-Based Expected Move Bands
Optionally plots ±1, 2, 3 standard deviation bands using VIX-based expected move, helping to visualize potential price extremes.
How These Features Help Traders
Unified Trading Dashboard: All key mean reversion and volatility insights are available at a glance, reducing the need to switch between multiple indicators or screens.
Informed Entries & Exits: By combining mean reversion probabilities, IV projections, and market volatility, traders can time trades more confidently and avoid false signals.
Risk Management: The implied move bounds and volatility levels support realistic stop-loss and target setting, adapting dynamically to market conditions.
Cross-Asset Awareness: Market-wide volatility metrics and asset correlation to SPY provide context, helping traders avoid surprises from macro shocks.
Pairs Trading: Direct support for ratio and correlation analysis streamlines pairs strategies.
Customization & Clarity: The flexible UI and color-coded stats make the tool accessible for both beginners and advanced users.
Mean Reversion, Correlation value & interpretation:
For Meant Reversion % Probability:
Lookback Period to use:
| Trading Horizon | Lookback Period (Length) | Rationale |
| 5–10 days | 10–20 bars | More sensitive, good for quick reversals |
| 10–20 days | 20–30 bars | Standard for short swing |
| 20–40 days | 40–60 bars | More stable mean for longer swing |
Interpretation Guide:
Only consider trades if Correlation ≥ 0.6 or Reversion % ≥ 75%.
Avoid trades with Reversion % < 20%.
Correlation and Reversion % together form a powerful trade quality filter.
| Reversion % | Correlation | Signal Strength | Action |
| ≥ 75% | ≥ 0.4 | High Probability | Consider full position |
| ≥ 50% | ≥ 0.6 | Moderate Probability | Trade with standard size |
| ≥ 75% | < 0.4 | Uncorrelated Edge | Trade small or hedge carefully |
| < 50% | Any | Weak | Avoid |
| Any | < 0.3 | Low Coherence | Avoid unless extreme Reversion |
| Correlation Value | Interpretation |
| +1.0 | Perfect positive correlation (price of both move in the same direction)|
| +0.7 to +0.9 | Strong positive correlation |
| +0.4 to +0.6 | Moderate positive correlation |
| 0 | No correlation (independent) |
| -0.4 to -0.6 | Moderate negative correlation |
| -0.7 to -0.9 | Strong negative correlation |
| -1.0 | Perfect negative correlation (price both move in the opposite direction)|
Summary:
This script empowers traders to navigate markets with a robust, data-driven approach, seamlessly blending mean reversion analytics with deep volatility insight—all in a mobile-friendly, customizable dashboard.
Disclaimer
This tool is for informational and educational purposes only. It does not provide financial advice or trading signals. Always do your own research and consult a professional before making investment decisions.
Rotation Phase TriggerHow to Use the Full Rotation Phase Trigger Tool (non-floating version)
This version is ideal for macro-level market context, helping you decide when to rotate between growth, income, and defensive positions using visual cues directly on the chart.
🧱 Components Recap (Non-Floating Version)
ROC Histograms:
SPY:TLT ROC (green bars): Measures equity strength vs. bonds
QQQ:XLU ROC (blue bars): Measures growth vs. defensive rotation
EMA Trend Filter:
Uses a fast/slow EMA crossover on both ratios to confirm the trend
When both are rising → confirms GROWTH phase
Phase Background Colors:
🟩 Green = GROWTH
🟧 Orange = INCOME
🟥 Red = DEFENSIVE
No color = NEUTRAL
Instruction Labels:
Show what sectors to add and what to sell (with ETF tickers)
Alert Conditions:
Can be linked to email, SMS, or app notifications
Triggered when phase changes
✅ Weekly Workflow
Every Monday (or Weekend Prep)
1. Open SPY on a Weekly Chart
This tool is designed around the U.S. equity vs bond regime
Always keep SPY as the main chart for best alignment
2. Check the Background Color
Instantly tells you what regime you're in:
Green → rotate into growth ETFs
Orange → stick to or buy income-generating ETFs
Red → get defensive, raise cash, or buy bond/hedge ETFs
3. Read the Labels
Top label = phase status (e.g., GROWTH)
Bottom label = action instructions:
What ETFs to accumulate (MTUM, VUN, HYLD, etc.)
What sectors or funds to rotate out of
4. Look at Momentum Histograms
Confirms whether the regime shift is gaining strength
Larger bars = stronger conviction
Diverging directions? Wait for confirmation
🔁 Tactical Rotation Plan
Phase Add Trim/Sell
GROWTH MTUM, VUN, XMTM, HXS, VTI HYLD, HHIS, HPYT
INCOME HYLD, HHIS, QQQY, DFN, DGS MTUM, VUN
DEFENSIVE HPYT, HPYT.U, ZGLD, GDE All equities
NEUTRAL Nothing new, rebalance if needed Excess risk positions
🔔 Alert Setup (Optional)
You can create alerts in TradingView using:
Right-click chart → "Add Alert"
Use condition: "Rotation Phase Trigger" → "GROWTH" / "INCOME" / "DEFENSIVE"
Choose notification method (popup, app, email, etc.)
💡 Pro Tips
Use this version on SPY weekly only — for best signal clarity
Internals Elite NYSE [Beta]Overview:
This indicator is designed to provide traders with a quick overview of key market internals and metrics in a single, easy-to-read table displayed directly on the chart. It incorporates a variety of metrics that help gauge market sentiment, momentum, and overall market conditions.
The table dynamically updates in real-time and uses color-coding to highlight significant changes or thresholds, allowing traders to quickly interpret the data and make informed trading decisions.
Features:
Market Internals:
TICK: Measures the difference between the number of stocks ticking up versus those ticking down on the NYSE. Green or red background indicates if it crosses a user-defined threshold.
Advance/Decline (ADD): Shows the net number of advancing versus declining stocks on the NYSE. Color-coded to show positive, negative, or neutral conditions.
Volatility Metrics:
VIX Change (%): Displays the percentage change in the Volatility Index (VIX), a key gauge of market fear or complacency. Color-coded for direction.
VIX Price: Displays the current VIX price with thresholds to indicate low, medium, or high volatility.
Other Market Metrics:
DXY Change (%): Percentage change in the US Dollar Index (DXY), indicating dollar strength or weakness.
VWAP Deviation (%): Percentage of stocks above VWAP (Volume Weighted Average Price), helping traders assess intraday buying and selling pressure.
Asset-Specific Metrics:
BTCUSD Change (%): Percentage change in Bitcoin (BTC) price, useful for monitoring cryptocurrency sentiment.
SPY Change (%): Percentage change in the S&P 500 ETF (SPY), a proxy for the overall stock market.
Current Ticker Change (%): Percentage change in the currently selected ticker on the chart.
US10Y Change (%): Percentage change in the yield of the 10-Year US Treasury Note (TVC:US10Y), an important macroeconomic indicator.
Customizable Appearance:
Adjustable text size to suit your chart layout.
User-defined thresholds for key metrics (e.g., TICK, ADD, VWAP, VIX).
Dynamic Table Placement:
You can position the table anywhere on the chart: top-right, top-left, bottom-right, bottom-left, middle-right, or middle-left.
How to Use:
Add the Indicator to Your Chart:
Apply the indicator to your chart from the Pine Script editor in TradingView.
Customize the Inputs:
Adjust the thresholds for TICK, ADD, VWAP, and VIX according to your trading style.
Enable or disable the metrics you want to see in the table by toggling the display options for each metric (e.g., Show TICK, Show BTC, Show SPY).
Set the table placement to your preferred position on the chart.
Interpret the Table:
Look for color-coded cells to quickly identify significant changes or breaches of thresholds.
Positive values are typically shown in green, negative values in red, and neutral/insignificant changes in gray.
Use metrics like TICK and ADD to gauge market breadth and momentum.
Refer to VWAP deviation to assess intraday buying or selling pressure.
Monitor the VIX and US10Y changes to stay aware of macroeconomic and volatility shifts.
Incorporate Into Your Strategy:
Use the indicator alongside technical analysis to confirm setups or identify areas of caution.
Keep an eye on correlated metrics (e.g., VIX and SPY) for broader market context.
Use BTCUSD or DXY as additional indicators of risk-on/risk-off sentiment.
Ideal Users:
Day Traders: Quickly gauge intraday market conditions and momentum.
Swing Traders: Identify broader sentiment shifts using metrics like ADD, DXY, and US10Y.
Macro Investors: Stay updated on key macroeconomic indicators like the 10-Year Treasury yield (US10Y) and the US Dollar Index (DXY).
This indicator serves as a comprehensive tool for understanding market conditions at a glance, enabling traders to act decisively based on the latest data.
Advanced Economic Indicator by USCG_VetAdvanced Economic Indicator by USCG_Vet
tldr:
This comprehensive TradingView indicator combines multiple economic and financial metrics into a single, customizable composite index. By integrating key indicators such as the yield spread, commodity ratios, stock indices, and the Federal Reserve's QE/QT activities, it provides a holistic view of the economic landscape. Users can adjust the components and their weights to tailor the indicator to their analysis, aiding in forecasting economic conditions and market trends.
Detailed Description
Overview
The Advanced Economic Indicator is designed to provide traders and investors with a powerful tool to assess the overall economic environment. By aggregating a diverse set of economic indicators and financial market data into a single composite index, it helps identify potential turning points in the economy and financial markets.
Key Features:
Comprehensive Coverage: Includes 14 critical economic and financial indicators.
Customizable Components: Users can select which indicators to include.
Adjustable Weights: Assign weights to each component based on perceived significance.
Visual Signals: Clear plotting with threshold lines and background highlights.
Alerts: Set up alerts for when the composite index crosses user-defined thresholds.
Included Indicators
Yield Spread (10-Year Treasury Yield minus 3-Month Treasury Yield)
Copper/Gold Ratio
High Yield Spread (HYG/IEF Ratio)
Stock Market Performance (S&P 500 Index - SPX)
Bitcoin Performance (BLX)
Crude Oil Prices (CL1!)
Volatility Index (VIX)
U.S. Dollar Index (DXY)
Inflation Expectations (TIP ETF)
Consumer Confidence (XLY ETF)
Housing Market Index (XHB)
Manufacturing PMI (XLI ETF)
Unemployment Rate (Inverse SPY as Proxy)
Federal Reserve QE/QT Activities (Fed Balance Sheet - WALCL)
How to Use the Indicator
Configuring the Indicator:
Open Settings: Click on the gear icon (⚙️) next to the indicator's name.
Inputs Tab: You'll find a list of all components with checkboxes and weight inputs.
Including/Excluding Components
Checkboxes: Check or uncheck the box next to each component to include or exclude it from the composite index.
Default State: By default, all components are included.
Adjusting Component Weights:
Weight Inputs: Next to each component's checkbox is a weight input field.
Default Weights: Pre-assigned based on economic significance but fully adjustable.
Custom Weights: Enter your desired weight for each component to reflect your analysis.
Threshold Settings:
Bearish Threshold: Default is -1.0. Adjust to set the level below which the indicator signals potential economic downturns.
Bullish Threshold: Default is 1.0. Adjust to set the level above which the indicator signals potential economic upswings.
Setting the Timeframe:
Weekly Timeframe Recommended: Due to the inclusion of the Fed's balance sheet data (updated weekly), it's best to use this indicator on a weekly chart.
Changing Timeframe: Select 1W (weekly) from the timeframe options at the top of the chart.
Interpreting the Indicator:
Composite Index Line
Plot: The blue line represents the composite economic indicator.
Movement: Observe how the line moves relative to the threshold lines.
Threshold Lines
Zero Line (Gray Dotted): Indicates the neutral point.
Bearish Threshold (Red Dashed): Crossing below suggests potential economic weakness.
Bullish Threshold (Green Dashed): Crossing above suggests potential economic strength.
Background Highlights
Red Background: When the composite index is below the bearish threshold.
Green Background: When the composite index is above the bullish threshold.
No Color: When the composite index is between the thresholds.
Understanding the Components
1. Yield Spread
Description: The difference between the 10-year and 3-month U.S. Treasury yields.
Economic Significance: An inverted yield curve (negative spread) has historically preceded recessions.
2. Copper/Gold Ratio
Description: The price ratio of copper to gold.
Economic Significance: Copper is tied to industrial demand; gold is a safe-haven asset. The ratio indicates risk sentiment.
3. High Yield Spread (HYG/IEF Ratio)
Description: Ratio of high-yield corporate bonds (HYG) to intermediate-term Treasury bonds (IEF).
Economic Significance: Reflects investor appetite for risk; widening spreads can signal credit stress.
4. Stock Market Performance (SPX)
Description: S&P 500 Index levels.
Economic Significance: Broad measure of U.S. equity market performance.
5. Bitcoin Performance (BLX)
Description: Bitcoin Liquid Index price.
Economic Significance: Represents risk appetite in speculative assets.
6. Crude Oil Prices (CL1!)
Description: Front-month crude oil futures price.
Economic Significance: Influences inflation and consumer spending.
7. Volatility Index (VIX)
Description: Market's expectation of volatility (fear gauge).
Economic Significance: High VIX indicates market uncertainty; inverted in the indicator to align directionally.
8. U.S. Dollar Index (DXY)
Description: Value of the U.S. dollar relative to a basket of foreign currencies.
Economic Significance: Affects international trade and commodity prices; inverted in the indicator.
9. Inflation Expectations (TIP ETF)
Description: iShares TIPS Bond ETF prices.
Economic Significance: Reflects market expectations of inflation.
10. Consumer Confidence (XLY ETF)
Description: Consumer Discretionary Select Sector SPDR Fund prices.
Economic Significance: Proxy for consumer confidence and spending.
11. Housing Market Index (XHB)
Description: SPDR S&P Homebuilders ETF prices.
Economic Significance: Indicator of the housing market's health.
12. Manufacturing PMI (XLI ETF)
Description: Industrial Select Sector SPDR Fund prices.
Economic Significance: Proxy for manufacturing activity.
13. Unemployment Rate (Inverse SPY as Proxy)
Description: Inverse of the SPY ETF price.
Economic Significance: Represents unemployment trends; higher inverse SPY suggests higher unemployment.
14. Federal Reserve QE/QT Activities (Fed Balance Sheet - WALCL)
Description: Total assets held by the Federal Reserve.
Economic Significance: Indicates liquidity injections (QE) or withdrawals (QT); impacts interest rates and asset prices.
Customization and Advanced Usage
Adjusting Weights:
Purpose: Emphasize components you believe are more predictive or relevant.
Method: Increase or decrease the weight value next to each component.
Example: If you think the yield spread is particularly important, you might assign it a higher weight.
Disclaimer
This indicator is for educational and informational purposes only. It is not financial advice. Trading and investing involve risks, including possible loss of principal. Always conduct your own analysis and consult with a professional financial advisor before making investment decisions.
BetaBeta , also known as the Beta coefficient, is a measure that compares the volatility of an individual underlying or portfolio to the volatility of the entire market, typically represented by a market index like the S&P 500 or an investible product such as the SPY ETF (SPDR S&P 500 ETF Trust). A Beta value provides insight into how an asset's returns are expected to respond to market swings.
Interpretation of Beta Values
Beta = 1: The asset's volatility is in line with the market. If the market rises or falls, the asset is expected to move correspondingly.
Beta > 1: The asset is more volatile than the market. If the market rises or falls, the asset's price is expected to rise or fall more significantly.
Beta < 1 but > 0: The asset is less volatile than the market. It still moves in the same direction as the market but with less magnitude.
Beta = 0: The asset's returns are not correlated with the market's returns.
Beta < 0: The asset moves in the opposite direction to the market.
Example
A beta of 1.20 relative to the S&P 500 Index or SPY implies that if the S&P's return increases by 1%, the portfolio is expected to increase by 12.0%.
A beta of -0.10 relative to the S&P 500 Index or SPY implies that if the S&P's return increases by 1%, the portfolio is expected to decrease by 0.1%. In practical terms, this implies that the portfolio is expected to be predominantly 'market neutral' .
Calculation & Default Values
The Beta of an asset is calculated by dividing the covariance of the asset's returns with the market's returns by the variance of the market's returns over a certain period (standard period: 1 years, 250 trading days). Hint: It's noteworthy to mention that Beta can also be derived through linear regression analysis, although this technique is not employed in this Beta Indicator.
Formula: Beta = Covariance(Asset Returns, Market Returns) / Variance(Market Returns)
Reference Market: Essentially any reference market index or product can be used. The default reference is the SPY (SPDR S&P 500 ETF Trust), primarily due to its investable nature and broad representation of the market. However, it's crucial to note that Beta can also be calculated by comparing specific underlyings, such as two different stocks or commodities, instead of comparing an asset to the broader market. This flexibility allows for a more tailored analysis of volatility and correlation, depending on the user's specific trading or investment focus.
Look-back Period: The standard look-back period is typically 1-5 years (250-1250 trading days), but this can be adjusted based on the user's preference and the specifics of the trading strategy. For robust estimations, use at least 250 trading days.
Option Delta: An optional feature in the Beta Indicator is the ability to select a specific Delta value if options are written on the underlying asset with Deltas less than 1, providing an estimation of the beta-weighted delta of the position. It involves multiplying the beta of the underlying asset by the delta of the option. This addition allows for a more precise assessment of the underlying asset's correspondence with the overall market in case you are an options trader. The default Delta value is set to 1, representing scenarios where no options on the underlying asset are being analyzed. This default setting aligns with analyzing the direct relationship between the asset itself and the market, without the layer of complexity introduced by options.
Calculation: Simple or Log Returns: In the calculation of Beta, users have the option to choose between using simple returns or log returns for both the asset and the market. The default setting is 'Simple Returns'.
Advantages of Using Beta
Risk Management: Beta provides a clear metric for understanding and managing the risk of a portfolio in relation to market movements.
Portfolio Diversification: By knowing the beta of various assets, investors can create a balanced portfolio that aligns with their risk tolerance and investment goals.
Performance Benchmarking: Beta allows investors to compare an asset's risk-adjusted performance against the market or other benchmarks.
Beta-Weighted Deltas for Options Traders
For options traders, understanding the beta-weighted delta is crucial. It involves multiplying the beta of the underlying asset by the delta of the option. This provides a more nuanced view of the option's risk relative to the overall market. However, it's important to note that the delta of an option is dynamic, changing with the asset's price, time to expiration, and other factors.
RedK Relative Strength Ribbon: RS Ribbon and RS ChartsRedK Relative Strength Ribbon (RedK RS_Ribbon) is TA tool that plots the Relative Strength of the current chart symbol against another symbol, or an index of choice. It enables us to see when a stock is gaining strength (or weakness) relative to (an index that represents) the market, and when it hits new highs or lows of that relative strength, which may lead to better trading decisions.
I searched TV for existing RS indicators but didn't find what I really wanted, so I put this together and added some additional features for my own use. It started as a simple RS line with new x-weeks Hi/Lo markers, then evolved into what you see here in v1.0 with the ability to plot a full RS chart in regular or HA candle types. Hope this will be useful to some other growth traders here on TV.
What is Relative Strength (RS)
------------------------------------
(RS is a comprehensive concept in TA, below is a quick summary - please research further if it's not already a familiar topic)
Relative Strength (RS) is a technical concept / indicator used mainly by growth / swing / momentum traders to compare the performance of one security or asset against another. RS measures the price performance of a specific security relative to a benchmark, such as an index or another asset. It's not to be confused with the famous Relative Strength Index (RSI) technical indicator
For example, In the context of comparing a stock's relative strength to the SPY (S&P 500) index, the relative strength calculation involves dividing the stock's price or price-related value (e.g., close price) by the corresponding value of the SPY index. The resulting ratio (and its trend over time) indicates the relative performance of the stock compared to the index.
Traders and investors use relative strength analysis to identify securities that have been showing relative strength or weakness compared to a benchmark, which can help in making investment decisions or identifying the "market leaders" and potential trading opportunities.
There are so many books and documentation about the RS concept and its importance to identify market leaders, especially when recovering from a bear market - if you're interested in the concept, please search more about it and review some of that literature. There's also a more detailed definition of Relative Strength in this article on Invstopedia
RedK RS_Ribbon features and options
---------------------------------------------------
The indicator settings provide many options and features - see the settings box below
- Change / choose base symbol
The default is to use SPY as the base symbol - so we're comparing the chart's symbol to a proxy of the S&P 500 - Some traders may prefer to use the QQQ - or other index or ETF that acts as a proxy for the industry / sector / market they are trading
- RS Calculation / RS line
we use the simple form of the RS calculation,
RS = closing price of current chart symbol / closing price of the base symbol (default is SPY) * 100
some RS documentation will use the Rate of Change (RoC) - but that's not what we're using here.
- The RS_Ribbon
* Once the RS line is plotted, it made sense to add couple of moving averages to it, to make it easier to observe the trend of the RS and the changes in that trend as you can see in the sample chart on top.
* The RS_Ribbon is made up of a fast and slow moving averages and will change color (green / red) based on detected trend RS direction - the 2 MA types and lengths can be changed until you get the setup that provides the best view for you of the RS trend over time. My preferred settings are used as defaults here.
- Identifying New (x)Week Hi/Lo RS Values
* Most traders would be interested when the calculated RS hits a new 52-week high or low value.
* There are cases where we may want to see when a new RS Hi/Lo has been hit for a different period - for example, a quarter (13 weeks)
* the number of weeks can be changed as well as adjusting the numbers of trading days per week (if needed for certain symbols/exchanges)
- Working with Different Timeframes
* Now these "markers" will only be available in the daily and weekly timeframes and there is a good reason for that, it's not the fact that i'm lazy :) and that enabling this in timeframes lower than 1D would have been some heavy lifting, but the reality is that with RS, we're really interested if a "day's close" hits a new RS high or low value against the moving window of x weeks (and the weeks close also) - if you think of this more, at lower TF, RS can hit a lower value that never end up registering on the daily closing and that causes a lot of visual confusion. So i took the "cleaner way out" of that issue.
* note that you can choose a different timeframe for the RS_Ribbon than the chart - if you do, please make sure the chart is at a lower timeframe than the indicator's - (and in that case remember to hide the candles because they won't make much sense)
i wanted to leverage TV's built-in multi-Timeframe (MTF) support with the caveat that using the indicator at lower TF with a chart at a higher TF (example chart at 1Wk and indicator at 1D) will show inaccurate results. If this sounds confusing, keep the indicator TF same as the chart.
the example here shows a 2-Hr chart against 1D RS_Ribbon
- Using RS Charts and RS Candles
* Beside the ability to plot the RS "closing" value with the RS line, the indicator provides the ability to show a "full" RS Chart with candles that represent the relative values of open, high, low. and close against the base symbol.
* the RS Charts can be used for regular chart analysis, for example, we can identify common chart patterns like Cup & Handle, VCP, Head & Shoulder..etc using these charts .. which can provide some edge over the price charts
* for the Heikin Ashi fans, I added the ability to choose classic or HA candles for the chart. note you have to enable the option to show the RS candles first before you choose the option to switch to HA.
The chart below shows a side-by-side comparison on the 2 RS chart types
Closing remarks
-----------------------
* RS is a good way to identify market/sector leaders (who will usually recover from a bear market before others) - and enable us to see the strength that comes from the broader makrket versus the one that comes from the stock's own performance and identify good trading opportunities
* I'll continue to update this work and alerts will come in next version - but wanted to check initial reaction and value
* as usual, if you decide to use this in your chart analysis, it's necessary to combine with other momentum, trend, ...etc indicators and do not make trading decision only based on the signales from a single indicator
Modern Portfolio Management IndicatorAfter weeks of grueling over this indicator, I am excited to be releasing it!
Intro:
This is not a sexy, technical or math based indicator that will give you buy and sell signals or anything fancy, but it is an indicator that I created in hopes to bridge a gap I have noticed. That gap is the lack of indicators and technical resources for those who also like to plan their investments. This indicator is tailored to those who are either established investors and to those who are looking to get into investing but don't really know where to start.
The premise of this indicator is based on Modern Portfolio Theory (MPT). Before we get into the indicator itself, I think its important to provide a quick synopsis of MPT.
About MPT:
Modern Portfolio Theory (MPT) is an investment framework that was developed by Harry Markowitz in the 1950s. It is based on the idea that an investor can optimize their investment portfolio by considering the trade-off between risk and return. MPT emphasizes diversification and holds that the risk of an individual asset should be assessed in the context of its contribution to the overall portfolio's risk. The theory suggests that by diversifying investments across different asset classes with varying levels of risk, an investor can achieve a more efficient portfolio that maximizes returns for a given level of risk or minimizes risk for a desired level of return. MPT also introduced the concept of the efficient frontier, which represents the set of portfolios that offer the highest expected return for a given level of risk. MPT has been widely adopted and used by investors, financial advisors, and portfolio managers to construct and manage portfolios.
So how does this indicator help with MPT?
The thinking and theory that went behind this indicator was this: I wanted an indicator, or really just a "way" to test and back-test ticker performance over time and under various circumstances and help manage risk.
Over the last 3 years we have seen a massive bull market, followed by a pretty huge bear market, followed by a very unexpected bull market. We have been and continue to be plagued with economic and political uncertainty that seems to constantly be looming over everyone with each waking day. Some people have liquidated their retirement investments, while others are fomoing in to catch this current bull run. But which tickers are sound and how tickers and funds have compared amongst each other remains somewhat difficult to ascertain, absent manually reviewing and calculating each ticker individually.
That is where this indicator comes in. This indicator permits the user to define up to 5 equities that they are potentially interested in investing in, or are already invested in. The user can then select a specific period in time, say from the beginning of 2022 till now. The user can then define how much they want to invest in each company by number of shares, so if they want to buy 1 share a week, or 2 shares a month, they can input these variables into the indicator to draw conclusions. As many brokers are also now permitting fractional share trading, this ability is also integrated into the indicator. So for shares, you can put in, say, 0.25 shares of SPY and the indicator will accept this and account for this fractional share.
The indicator will then show you a portfolio summary of what your earnings and returns would be for the defined period. It will provide a percent return as well as the projected P&L based on your desired investment amount and frequency.
But it goes beyond just that, you can also have the indicator display a simple forecasting projection of the portfolio. It will show the projected P&L and % Return over various periods in time on each of the ticker (see image below):
The indicator will also break down your portfolio allocation, it will show where the majority of your holdings are and where the majority of your P&L in coming from (best performers will show a green fill and worst will show a red fill, see image below):
This colour coding also extends to the portfolio breakdown itself.
Dollar cost averaging (DCA) is incorporated into the indicator itself, by assuming ongoing contributions. If you want to stop contributions at a certain point, you just select your end time for contributions at the point in which you would stop contributing.
The indicator also provides some basic fundamental information about the company tickers (if applicable). Simply select the "Fundamental" chart and it will display a breakdown of the fundamentals, including dividends paid, market cap and earnings yield:
The indicator also provides a correlation assessment of each holding against each other holding. This emphasizes the profound role of diversification on portfolios. The less correlation you have in your portfolio among your holdings, the better diversified you are. As well, if you have holdings that are perfectly inverse other holdings, you have a pseudo hedge against the downturn of one of your holdings. This is even more helpful if the inverse is a company with solid fundamentals.
In the below example you will see NASDAQ:IRDM in the portfolio. You will be able to see that NASDAQ:IRDM has a slight inverse relationship to SPY:
Yet IRDM has solid fundamentals and is performing well fundamentally. Thus, this makes IRDIM a solid addition to your portfolio as it can potentially hedge against a downturn for SPY and is less risky than simply holding an inverse leveraged share on SPY which is most likely just going to cost you money than make you money.
Concluding remarks:
There are many fun and interesting things you can do with this indicator and I encourage you to try it out and have fun with it! The overall objective with the indicator is to help you plan for your portfolio and not necessarily to manage your portfolio. If you have a few stocks you are looking at and contemplating investing in, this will help you run some theoretical scenarios with this stock based on historical performance and also help give you a feel of how it will perform in the future based on past behaviour.
It is important to remember that past behaviour does not indicate future behaviour, but the indicator provides you with tools to get a feel for how a stock has performed under various circumstances and get a general feel of the fundamentals of the company you could potentially be investing in.
Please note, this indicator is not meant to replace full, fundamental analyses of individual companies. It is simply meant to give you a "gist" of how companies are fundamentally and how they have performed historically.
I hope you enjoy it!
Safe trades everyone!
Trend Correlation HeatmapHello everyone!
I am excited to release my trend correlation heatmap, or trend heatmap for short.
Per usual, I think its important to explain the theory before we get into the use of the indicator, so let's get into the theory!
The theory:
So what is a correlation?
Correlation is the relationship one variable has to another. Correlations are the basis of everything I do as a quantitative trader. From the correlation between the same variables (i.e. autocorrelation), the correlation between other variables (i.e. VIX and SPY, SPY High and SPY Low, DXY and ES1! close, etc.) and, as well, the correlation between price and time (time series correlation).
This may sound very familiar to you, especially if you are a user, observer or follower of my ideas and/or indicators. Ninety-five percent of my indicators are a function of one of those three things. Whether it be a time series based indicator (i.e.my time series indicator), whether it be autocorrelation (my autoregressive cloud indicator or my autocorrelation oscillator) or whether it be regressive in nature (i.e. my SPY Volume weighted close, or even my expected move which uses averages in lieu of regressive approaches but is foundational in regression principles. Or even my VIX oscillator which relies on the premise of correlations between tickers.) So correlation is extremely important to me and while its true I am more of a regression trader than anything, I would argue that I am more of a correlation trader, because correlations are the backbone of how I develop math models of stocks.
What I am trying to stress here is the importance of correlations. They really truly are foundational to any type of quantitative analysis for stocks. And as such, understanding the current relationship a stock has to time is pivotal for any meaningful analysis to be conducted.
So what is correlation to time and what does it tell us?
Correlation to time, otherwise known and commonly referred to as "Time Series", is the relationship a ticker's price has to the passing of time. It is displayed in the traditional Pearson Correlation Coefficient or R value and can be any value from -1 (strong negative relationship, i.e. a strong downtrend) to + 1 (i.e. a strong positive relationship, i.e. a strong uptrend). The higher or lower the value the stronger the up or downtrend is.
As such, correlation to time tells us two very important things. These are:
a) The direction of the stock; and
b) The strength of the trend.
Let's take a look at an example:
Above we have a chart of QQQ. We can see a trendline that seems to fit well. The questions we ask as traders are:
1. What is the likelihood QQQ breaks down from this trendline?
2. What is the likelihood QQQ continues up?
3. What is the likelihood QQQ does a false breakdown?
There are numerous mathematical approaches we can take to answer these questions. For example, 1 and 2 can be answered by use of a Cumulative Distribution Density analysis (CDDA) or even a linear or loglinear regression analysis and 3 can be answered, more or less, with a linear regression analysis and standard error ascertainment, or even just a general comparison using a data science approach (such as cosine similarity or Manhattan distance).
But, the reality is, all 3 of these questions can be visualized, at least in some way, by simply looking at the correlation to time. Let's look at this chart again, this time with the correlation heatmap applied:
If we look at the indicator we can see some pivotal things. These are:
1. We have 4, very strong uptrends that span both higher AND lower timeframes. We have a strong uptrend of 0.96 on the 5 minute, 50 candle period. We have a strong uptrend at the 300 candle lookback period on the 1 minute, we have a strong uptrend on the 100 day lookback on the daily timeframe period and we have a strong uptrend on the 5 minute on the 500 candle lookback period.
2. By comparison, we have 3 downtrends, all of which have correlations less than the 4 uptrends. All of the downtrends have a correlation above -0.8 (which we would want lower than -0.8 to be very strong), and all of the uptrends are greater than + 0.80.
3. We can also see that the uptrends are not confined to the smaller timeframes. We have multiple uptrends on multiple timeframes and both short term (50 to 100 candles) and long term (up to 500 candles).
4. The overall trend is strengthening to the upside manifested by a positive Max Change and a Positive Min change (to be discussed later more in-depth).
With this, we can see that QQQ is actually very strong and likely will continue at least some upside. If we let this play out:
We continued up, had one test and then bounced.
Now, I want to specify, this indicator is not a panacea for all trading. And in relation to the 3 questions posed, they are best answered, at least quantitatively, not only by correlation but also by the aforementioned methods (CDDA, etc.) but correlation will help you get a feel for the strength or weakness present with a stock.
What are some tangible applications of the indicator?
For me, this indicator is used in many ways. Let me outline some ways I generally apply this indicator in my day and swing trading:
1. Gauging the strength of the stock: The indictor tells you the most prevalent behavior of the stock. Are there more downtrends than uptrends present? Are the downtrends present on the larger timeframes vs uptrends on the shorter indicating a possible bullish reversal? or vice versa? Are the trends strengthening or weakening? All of these things can be visualized with the indicator.
2. Setting parameters for other indicators: If you trade EMAs or SMAs, you may have a "one size fits all" approach. However, its actually better to adjust your EMA or SMA length to the actual trend itself. Take a look at this:
This is QQQ on the 1 hour with the 200 EMA with 200 standard deviation bands added. If we look at the heatmap, we can see, yes indeed 200 has a fairly strong uptrend correlation of 0.70. But the strongest hourly uptrend is actually at 400 candles, with a correlation of 0.91. So what happens if we change the EMA length and standard deviation to 400? This:
The exact areas are circled and colour coded. You can see, the 400 offers more of a better reference point of supports and resistances as well as a better overall trend fit. And this is why I never advocate for getting married to a specific EMA. If you are an EMA 200 lover or 21 or 51, know that these are not always the best depending on the trend and situation.
Components of the indicator:
Ah okay, now for the boring stuff. Let's go over the functionality of the indicator. I tried to keep it simple, so it is pretty straight forward. If we open the menu here are our options:
We have the ability to toggle whichever timeframes we want. We also have the ability to toggle on or off the legend that displays the colour codes and the Max and Min highest change.
Max and Min highest change: The max and min highest change simply display the change in correlation over the previous 14 candles. An increasing Max change means that the Max trend is strengthening. If we see an increasing Max change and an increasing Min change (the Min correlation is moving up), this means the stock is bullish. Why? Because the min (i.e. ideally a big negative number) is going up closer to the positives. Therefore, the downtrend is weakening.
If we see both the Max and Min declining (red), that means the uptrend is weakening and downtrend is strengthening. Here are some examples:
Final Thoughts:
And that is the indicator and the theory behind the indicator.
In a nutshell, to summarize, the indicator simply tracks the correlation of a ticker to time on multiple timeframes. This will allow you to make judgements about strength, sentiment and also help you adjust which tools and timeframes you are using to perform your analyses.
As well, to make the indicator more user friendly, I tried to make the colours distinctively different. I was going to do different shades but it was a little difficult to visualize. As such, I have included a toggle-able legend with a breakdown of the colour codes!
That's it my friends, I hope you find it useful!
Safe trades and leave your questions, comments and feedback below!
Vola2vola Volatility indicatorHello everyone!
For those who remember vola2vola volatility script, we are excited to bring it back within the Myfractalrange Tradingview account!
As you know, Volatility is very important to assets and many people use it to trade. This tool automate the calculation of the volatility of every asset as well as provide an estimated value of its "Trend" and "Trade".
The idea in this script is to allow users to have an idea of the current volatility regime of the asset he is monitoring: Is its volatility Bullish or Bearish Trend, Bearish or Bullish Trade? Is its volatility compressed to a previous minimum value? Is it about to experience a spike in volatility? Let's dig together into how this tool works and how you could integrate it into your trading shall we?
What are the data provided by the script, let see one by one:
- Volatility: The value of what vola2vola calls the "synthetic" volatility of the asset is calculated using a custom formula based on the VIXFIX formula. Default colour is blue
- Trade : Trade is generated using an arbitrary and fixed look back period, it acts as a short-term trend. It will give the user the possibility to know if the volatility of the asset is still trending short-term or not. Default colour is black
- Trend: Trend is also generated using an arbitrary and fixed look back period (20 times the one used for Trade), it acts as a longer-term trend. It works the same way as Trade and will give the user the possibility to know if the volatility of the asset is trending a longer-term basis or not. Default colours are: red when the Trend of the volatility of the asset is Bearish and green when the Trend of the volatility of the asset is Bullish
- 52-weeks high & low: Based on the highest and lowest value of Volatility in the past 52 weeks, a 52-weeks high and a 52-weeks low will be marked. These values usually acts as Resistance and Support for volatility. Default colour is black and they are in dotted lines
Here are some of the questions you need to know the answer to before using this script:
- How do you define a "Bullish/Bearish volatility Trade"? Volatility is Bullish Trade is when Volatility is above Trade and it is Bearish Trade when volatility is below Trade
- How do you define a "Bullish/Bearish volatility Trend"? Volatility is Bullish Trend is when Volatility is above Trend and it is Bearish Trend when volatility is below Trend
- On which time frame should i use this script? You want to use the Daily time frame. Although, for short term moves in the volatility space, users could monitor the Hourly timeframe
Understanding the volatility of an asset, along with the bullish or bearish nature of its Trade and Trend, is crucial for investors. Assets with decreasing volatility tend to appreciate in value, while those with increasing volatility tend to depreciate. Therefore, we recommend investors be aware of the volatility situation of the asset they are holding in their portfolio.
Here are the different scenarios that you will encounter on a Daily timeframe and how to interpret them:
- Volatility is below Trade & Trend and Volatility is Bearish Trade and Trend: It is the most Bullish set up for the price of an asset
- Volatility is above Trade & Trend and Volatility is Bullish Trade and Trend: It is the most Bearish set up for the price of an asset
- Any other set up suggests uncertainty, caution is therefore recommended
These are some cases that you could experience while using this script:
1) Bearish Volatility set up on a daily timeframe:
In this example using SPY, when its Volatility is Bearish Trend on a daily timeframe, the price of SPY tends to appreciate
2) Bullish Volatility set up on a daily timeframe:
In this example using SPY, when its Volatility is Bullish Trend on a daily timeframe, the price of SPY tends to depreciate
We hope that you will find these explanations useful, please contact us by private message for access.
Enjoy!
DISCLAIMER: No sharing, copying, reselling, modifying, or any other forms of use are authorised. This script is strictly for individual use and educational purposes only. This is not financial or investment advice. Investments are always made at your own risk and are based on your personal judgement. Myfractalrange is not responsible for any losses you may incur. Please invest wisely.
Accelerating Dual Momentum ScoreThis is a score metric used by the Accelerating Dual Momentum strategy.
According to the website you referenced when you created, the strategy is as follows:
Strategy Rules
This strategy allocates 100% of of the portfolio to one asset each month.
1. On the last trading day of each month, calculate the “momentum score” for the S&P 500 ( SPY ) and the international small cap equities (SCZ). The momentum score is the average of the 1, 3, and 6-month total return for each asset.
2. If the momentum score of SCZ > SPY and is greater than 0, invest in SCZ.
3. If the momentum score of SPY > SCZ and is greater than 0, invest in SPY .
4. If neither momentum score is greater than 0, calculate the 1-month total return for long-term US Treasuries ( TLT ) and US TIPS (TIP). Invest in whichever has the higher return.
Source: portfoliodb.co
Volatility/Volume ImpactWe often hear statements such as follow the big volume to project possible price movements. Or low volatility is good for trend. How much of it is statistically right for different markets. I wrote this small script to study the impact of Volatility and Volume on price movements.
Concept is as below:
Compare volume with a reference median value. You can also use moving average or other types for this comparison.
If volume is higher than median, increment positive value impact with change in close price. If volume is less than median, then increment negative value impact with change in close price.
With this we derive pvd and nvd which are measure of price change when volume is higher and lower respectively. pvd measures the price change when volume is higher than median whereas nvd measures price change when volume is lower than median.
Calculate correlation of pvd and nvd with close price to see what is impacting the price by higher extent.
Colors are applied to plots which have higher correlation to price movement. For example, if pvd has higher correlation to price movement, then pvd is coloured green whereas nvd is coloured silver. Similarly if nvd has higher correlation to price then nvd is coloured in red whereas pvd is coloured in silver.
Similar calculation also applied for volatility.
With this, you can observe how price change is correlated to high/low volume and volatility.
Let us see some examples on different markets.
Example 1: AMEX:SPY
From the chart snapshot below, it looks evident that SPY always thrive when there is low volatility and LOW VOLUME!!
Example 2: NASDAQ:TSLA
The picture will be different if you look at individual stocks. For Tesla, the price movement is more correlated to high volume (unlike SPY where low volume days define the trend)
Example 3: KUCOIN:BTCUSDT
Unlike stocks and indices, high volatility defined the trend for BTC for long time. It thrived when volatility is more. We can see that high volume is still major influencer in BTC price movements.
Settings are very simple and self explanatory.
Hint: You can also move the indicator to chart overlay for better visualisation of comparison with close price.
Linear Regression Relative Strength[image/x/iZvwDWEY/
Relative Strength indicator comparing the current symbol to SPY (or any other benchmark). It may help to pick the right assets to complement the portfolio build around core ETFs such as SPY.
The general idea is to show if the current symbol outperforms or underperforms the benchmark (SPY by default) when bought some certain time ago. Relative performance is displayed as percent and is calculated for three different time ranges - short (1 mo by default), mid (1 quarter), and long (half a year). To smooth the volatility, the script uses linear regression to estimate the trend and takes the start and the end points of the linear regression line to compute the relative strength.
It is important to remember that the script shows the gain relative to SPY (or other selected benchmark), not the asset's gain. Therefore, it may indicate that the asset is profitable, but it still may lose value if SPY is in downtrend.
Therefore, it is crucial to check other indicators before making a decision. In the example above, standard linear regression for one quarter is used to indicate the direction of the trend.
Drawdown RangeHello death eaters, presenting a unique script which can be used for fundamental analysis or mean reversion based trades.
Process of deriving this table is as below:
Find out ATH for given day
Calculate the drawdown from ATH for the day and drawdown percentage
Based on the drawdown percentage, increment the count of basket which is based on input iNumber of ranges . For example, if number of ranges is 5, then there will be 5 baskets. First basket will fit drawdown percentage 0-20% and each subsequent ones will accommodate next 20% range.
Repeat the process from start to last bar. Once done, table will plot how much percentage of days belong to which basket.
For example, from the below chart of NASDAQ:AAPL
We can deduce following,
Historically stock has traded within 1% drawdown from ATH for 6.59% of time. This is the max amount of time stock has stayed in specific range of drawdown from ATH.
Stock has traded at the drawdown range of 82-83% from ATH for 0.17% of time. This is the least amount of time the stock has stayed in specific range of drawdown from ATH.
At present, stock is trading 2-3% below ATH and this has happened for about 2.46% of total days in trade
Maximum drawdown the stock has suffered is 83%
Lets take another example of NASDAQ:TSLA
Stock is trading at 21-22% below ATH. But, historically the max drawdown range where stock has traded is within 0-1%. Now, if we make this range to show 20 divisions instead of 100, it will look something like this:
Table suggests that stock is trading about 20-25% below ATH - which is right. But, table also suggests that stock has spent most number of days within this drawdown range when we divide it by 20 baskets instad of 100. I would probably wait for price to break out of this range before going long or short. At present, it seems a stage ranging stage. I might think about selling PUTs or covered CALLs outside this range.
Similarly, if you look at AMEX:SPY , 36% of the time, price has stayed within 5% from ATH - makes it a compelling bull case!!
NYSE:BABA is trading at 50-55% below ATH - which is the most it has retraced so far. In general, it is used to be within 15-20% from ATH
NOW, Bit of explanation on input options.
Number of Ranges : Says how many baskets the drawdown map needs to be divided into.
Reference : You can take ATH as reference or chose a time window between which the highest need to be considered for drawdown. This can be useful for megacaps which has gone beyond initial phase of uncertainity. There is no point looking at 80% drawdown AAPL had during 1990s. More approriate to look at it post 2000s where it started making higher impact and growth.
Cumulative Percentage : When this is unchecked, percentage division shows 0-nth percentage instad of percentage ranges. For example this is how it looks on SPY:
We can see that SPY has remained within 6% from ATH for more than 50% of the time.
Hope this is helpful. Happy trading :)
PS: this can be used in conjunction with Drawdown-Price-vs-Fundamentals to pick value stocks at discounted price while also keeping an eye on range tendencies of it.
Thanks to @mattX5 for the ideas and discussion today :)
Altered True Strength Indicator (TSI) Reupload-
Altered TSI provides a slightly more volatile signal that demonstrates extremities in price action with greater success than standard TSI. In addition, I added bull/bear cross indicators (green/red) to make it easier to notice the crosses to save time when the market is moving fast (I couldn't find a regular TSI script with this addition). Finally, the signal also has overextension parameters (red and green lines)
I think this is best used on Intraday time frames as the signals respond to volatility very well and using Heikin Ashi candles, trend is more visual. In this particular example, I am showing SPY on the 3m time chart (my favorite short time frame) and the signal alone provided many opportunities for trades when using simple divergences and countering overextension direction when short term (blue) signal crosses either
In the first example (purple lines), SPY ramps but it was a dull signal given the signal strength flatlining- we would be looking for a short entry. When the signal fires, it provides a clean $1.50 move down in spy.
In the second example (orange), the blue signal provides a nice V shape (rebound signal) in which we are looking for a long entry. 390.50 is a strong SPY support in confluence with 2nd std dev VWAP extension, but disregarding that bull signal fires resulting in a 2 dollar move upwards. Exit is provided when blue line crosses green overextension.
In the third example (white), we are searching for a short entry at 392.5 resistance in confluence with divergently higher highs. Bear cross signal when fired and a significant cross is visible provides a $2.50 move to the downside with a potential exit provided when blue line crosses red overextension line in confluence with previous LOD area.
In the fourth example (green), we watch as the blue line provides a V pattern, we are searching for a long entry. If you didn't take a riskier long at 2nd std dev VWAP overextension with V recovery on blue line at red overextension for a ride to vwap, then you are looking for a secondary entry long as you wouldn't take the trade at resistance (vwap). Bullishly divergent lows provide this entry and the signal does not bear cross at all (but looking for significant crosses is more important even if the signal were to make a minor bear cross). Bullishly divergent double bottom provides a long entry to end of day with a nice clean signal for a $5.00 move until eod or when signal crosses overextension range.
Ideally, close to the money options or SPY/SPXS/SPXL are best used in the intraday time frame.
Again, this is not a standalone indicator but it's best used in conjunction with other indicators/trading strategies
Any questions feel free to comment
Candlestick RSThis is a candlestick charted Relative Strength indicator. It compares the chosen stock's progress compared to that of the SPY ETF ... ( SPY is used so it should hopefully update intraday). I use this indicator to see which stocks are outperforming the market.
Input Variable Descriptions:
Ratio: this variable is a float (0 to 1) that is basically how close the Candlestick RS is to the actual price action of the chart. (1.0 being right on top of it, 0.0 being as far away as possible from it)
Ballpark SPY price: this variable has to be constant, and due to the way pinescript works, you have to manually put in a ballpark of what SPY is at.
Neither of these variables influences the actual data of the indicator, but rather how it is shown on screen. It's difficult to describe, so I recommend you messing around with the variables and see what changes.
Hope this helps, I find this useful, so I figured I'd publish this... This is my first pine script so forgive me for any errors, just want to help :)
RS Power Scanner by MashrabThis script implements a custom IBD-style Relative Strength (RS) rating and RS line breakout scanner for any symbol versus SPY. It is designed to help traders quickly identify stocks with market-leading performance.
How It Works:
RS Rating (0–100 scale)
Calculates 252-bar Rate of Change (ROC) for the stock and SPY.
Compares stock ROC to SPY’s ROC.
Uses ta.percentrank() to convert the result into a percentile ranking (0–100).
A high RS rating means the stock has outperformed SPY over the past 252 bars.
RS Line New Highs
Plots the RS line = (Stock Close ÷ SPY Close).
Checks for a 50-bar highest value — a classic sign of market leadership.
Signal Logic
Plots a green ▲ label below bars when:
RS Rating ≥ 85 (strong relative performance)
RS line makes a 50-bar high (confirming strength)
Table Display
Shows live RS Rating and RS new high status for quick decision-making.
Use Case:
This tool is designed for traders using momentum, CAN SLIM, or relative strength strategies to spot potential leaders early. It is not a standalone buy/sell system; rather, it helps filter stocks for further analysis.
How to Use:
Apply to your watchlist charts.
Look for ▲ signals during market uptrends.
Combine with fundamental or volume analysis for best results.
Defense Mode Dashboard ProWhat it is
A one‑look market regime dashboard for ES, NQ, YM, RTY, and SPY that tells you when to play defense, when you might have an offense cue, and when to chill. It blends VIX, VIX term structure, ATR 5 over 60, and session gap signals with clean alerts and a compact table you can park anywhere.
Why traders like it
Because it filters out the noise. Regime first, tactics second. You avoid trading size into landmines and lean in when volatility cooperates.
What it measures
Volatility stress with VIX level and VIX vs 20‑SMA
Term structure using VX1 vs VX2 with two modes
Diff mode: VX1 minus VX2
Ratio mode: VX1 divided by VX2
Realized volatility using ATR5 over ATR60 with optional smoothing
Session risk from RTH opening gaps and overnight range, normalized by ATR
How to use in 30 seconds
Pick a preset in the inputs. ES, NQ, YM, RTY, SPY are ready.
Leave thresholds at defaults to start.
Add one TradingView alert using “Any alert() function call”.
Trade smaller or stand aside when the header reads DEFENSE ON. Consider leaning in only when you see OFFENSE CUE and your playbook agrees.
Defaults we recommend
VIX triggers: 22 and 1.25× the 20‑SMA
Term mode: Diff with tolerance 0.00. Use Ratio at 1.00+ for choppier markets
ATR 5/60 defense: 1.25. Offense cue: 0.85 or lower
ATR smoothing: 1. Try 2 to 3 if you want fewer flips
Gap mode: RTH. Turn Both on if you want ON range to count too
RTH wild gap: 0.60× ATR5. ON wild range: 0.80× ATR5
Alert cadence: Once per RTH session
Snooze: Quick snooze first 30 minutes on. Fire on snooze exit off, unless you really want the catch‑up ping
New since the last description
Multi‑asset presets set symbols and RTH windows for ES, NQ, YM, RTY, SPY
Term ratio mode with near‑flat warning when ratio is between 1.00 and your trigger
ATR smoothing for the 5 over 60 ratio
RTH keying for cadence, so “Once per RTH session” behaves like a trader expects
Snooze upgrades with quick snooze tied to the first N minutes of RTH and an optional fire‑on‑snooze‑exit
Compact title merge and user color controls for labels, values, borders, and background
Exposed series for integrations: DefenseOn(1=yes) and OffenseCue(1=yes)
Debug toggle to visualize gap points, ON range, and term readings
Stronger NA handling with a clear “No core data” row when feeds are missing
Notes
Dynamic alerts require “Any alert() function call”.
Works on any chart timeframe. Daily reads and 1‑minute anchors handle the regime logic.
Volumetric Expansion/Contraction### Indicator Title: Volumetric Expansion/Contraction
### Summary
The Volumetric Expansion/Contraction (PCC) indicator is a comprehensive momentum oscillator designed to identify high-conviction price moves. Unlike traditional oscillators that only look at price, the PCC integrates four critical dimensions of market activity: **Price Change**, **Relative Volume (RVOL)**, **Cumulative Volume Delta (CVD)**, and **Average True Range (ATR)**.
Its primary purpose is to help traders distinguish between meaningful, volume-backed market expansions and noisy, unsustainable price action. It gives more weight to moves that occur in a controlled, low-volatility environment, highlighting potential starts of new trends or significant shifts in market sentiment.
### Key Concepts & Purpose
The indicator's unique formula synthesizes the following concepts:
1. **Price Change:** Measures the magnitude and direction of the primary move.
2. **Relative Volume (RVOL):** Confirms that the move is backed by significant volume compared to its recent average, indicating institutional participation.
3. **Cumulative Volume Delta (CVD):** Measures the underlying buying and selling pressure, confirming that the price move is aligned with the net flow of market orders.
4. **Inverse Volatility (ATR):** This is the indicator's unique twist. It normalizes the signal by the inverse of the Average True Range. This means the indicator's value is **amplified** when volatility (ATR) is low (signifying a controlled, confident expansion) and **dampened** when volatility is high (filtering out chaotic, less predictable moves).
The goal is to provide a single, easy-to-read oscillator that signals when price, volume, and order flow are all in alignment, especially during a breakout from a period of contraction.
### Features
* **Main Oscillator Line:** A single line plotted in a separate pane that represents the calculated strength of the volumetric expansion or contraction.
* **Zero Line:** A dotted reference line to easily distinguish between bullish (above zero) and bearish (below zero) regimes.
* **Visual Threshold Zones:** The background automatically changes color to highlight periods of significant strength:
* **Bright Green:** Indicates a "Strong Up Move" when the oscillator crosses above the user-defined upper threshold.
* **Bright Fuchsia:** Indicates a "Strong Down Move" when the oscillator crosses below the user-defined lower threshold.
### Configurable Settings & Filters
The indicator is fully customizable to allow for extensive testing and adaptation to different assets and timeframes.
#### Main Calculation Inputs
* **Price Change Lookback:** Sets the period for calculating the primary price change.
* **CVD Normalization Length:** The lookback period for normalizing the Cumulative Volume Delta.
* **RVOL Avg Volume Length:** The lookback for the simple moving average of volume, used to calculate RVOL.
* **RVOL Normalization Length:** The lookback period for normalizing the RVOL score.
* **ATR Length & Normalization Length:** Sets the periods for calculating the ATR and its longer-term average for normalization.
#### Weights
* Fine-tune the impact of each core component on the final calculation, allowing you to emphasize what matters most to your strategy (e.g., give more weight to CVD or RVOL).
#### External Market Filter (Powerful Feature)
* **Enable SPY/QQQ Filter for Up Moves?:** A checkbox to activate a powerful regime filter.
* **Symbol:** A dropdown to choose whether to filter signals based on the trend of **SPY** or **QQQ**.
* **SMA Period:** Sets the lookback period for the Simple Moving Average (default is 50).
* **How it works:** When enabled, this filter will **only allow "Strong Up Move" signals to appear if the chosen symbol (SPY or QQQ) is currently trading above its specified SMA**. This is an excellent tool for aligning your signals with the broader market trend and avoiding bullish entries in a bearish market.
#### Visuals
* **Upper/Lower Threshold:** Allows you to define what level the oscillator must cross to trigger the colored background zones, letting you customize the indicator's sensitivity.
***
**Disclaimer:** This tool is designed for market analysis and confluence. It is not a standalone trading system. Always use this indicator in conjunction with your own trading strategy, risk management, and other forms of analysis.