Up and Downwhat is "Up and Down"?
It is an indicator designed to show you in detail on the chart and warn you when there is an increase or decrease in the market at a level that you consider important.
what it does?
When the price difference between a top and bottom is greater than the level you selected (the default input is 10 percent), it indicates this along with the percentage value on the chart. Then, it indicates the start and end points with lines so that you can see the change from where to where. It shows the price's current percentage distance from the last bottom or top in the upper right corner.
it also colors the candles so you can better understand how fast the price is moving. The greener the candles, the stronger the rise, and conversely, the greater the decline, the redder the candles. Of course, if you set an alarm, it will tell you in which trading pair, in which time period, at what percentage and in which direction there is a movement.
how it does it?
It uses a moving average with a short length to find bottoms and tops. It then measures the distance from the last peak to the bottom and expresses it as a percentage. It uses momentum using the moving average as a source to paint the candles. To compress this momentum between the values 255 and 0, I used a formula that I also used in my limited fisher transform work (because the inputs in the color.rgb function take values between 0 and 255). It was a bit challenging to use the lines correctly, but with the "ta.valuewhen" function and a little experimenting, they were I made sure they were drawn correctly.
how to use it?
It is quite simple to use. First, select the minimum interval you want to receive alarms. If you make this value too high, you will not receive any alarms; if you make it too low, you will receive too many alarms. Choose the range that will benefit you most for the trading pair you are using. Then all you have to do is set an alarm. When you set an alarm, leave the note section blank and the indicator will send you the necessary information.
Statistics
Relação 12M - Desempenho YoYAnalisa a variação percentual do preço de um ativo em um período de 12 meses. Ele compara o preço atual do ativo com o preço de fechamento registrado exatamente 12 meses atrás, indicando se o ativo apresentou valorização ou desvalorização ao longo do período.
Mastering ATR for Smart Stop Loss and Take Profit PlacementUsing the ATR indicator to set Stop Loss and Take Profit levels provides a dynamic and flexible way to manage risk based on the volatility of the market. This method ensures that your SL and TP are always in tune with current market conditions, preventing unnecessary stop-outs while maximizing the potential for profit. The table in the script makes it easy to view your calculated levels directly on the chart, improving your trading efficiency.
If you're looking for a more automated way to manage your trades, integrating ATR-based SL and TP can be a powerful tool in your strategy.
Happy Trading!
Crypto Market Cap Momentum Analyzer (AiBitcoinTrend)The Crypto Market Cap Momentum Analyzer (AiBitcoinTrend) is a robust tool designed to uncover trading opportunities by blending market cap analysis and momentum dynamics. Inspired by research-backed quantitative strategies, this indicator helps traders identify trend-following and mean-reversion setups in the cryptocurrency market by evaluating recent performance and market cap size.
This indicator classifies cryptocurrencies into market cap quintiles and ranks them based on their 2-week momentum. It then suggests potential trades—whether to go long, anticipate reversals, or simply hold—based on the crypto's market cap group and momentum trends.
👽 How the Indicator Works
👾 Market Cap Classification
The indicator categorizes cryptocurrencies into one of five market cap groups based on user-defined inputs:
Large Cap: Highest market cap tier
Upper Mid Cap: Second highest group
Mid Cap: Middle-tier market caps
Lower Mid Cap: Slightly below the mid-tier
Small Cap: Lowest market cap tier
This classification dynamically adjusts based on the provided market cap data, ensuring that you’re always working with a representative market structure.
👾 Momentum Calculation
By default, the indicator uses a 2-week momentum measure (e.g., a 14-day lookback when set to daily). It compares a cryptocurrency’s current price to its price 14 bars ago, thereby quantifying its short-term performance. Users can adjust the momentum period and rebalance period to capture shorter or longer-term trends depending on their trading style.
👾 Dynamic Ranking and Trade Suggestions
After assigning cryptos to size quintiles, the indicator sorts them by their momentum within each quintile. This two-step process results in:
Long Trade: For smaller market cap groups (Small, Lower Mid, Mid Cap) that have low (bottom-quintile) momentum, anticipating a trend continuation or breakout.
Reversal Trade: For the largest market cap group (Large Cap) that shows low momentum, expecting a mean-reversion back to equilibrium.
Hold: In scenarios where the coin’s momentum doesn’t present a strong contrarian or trend-following signal.
👽 Applications
👾 Trend-Following in Smaller Caps: Identify small or mid-cap cryptos with low momentum that might be poised for a breakout or sustained trend.
👾 Mean-Reversion in Large Caps: Pinpoint large-cap cryptocurrencies experiencing a temporary lull in performance, potentially ripe for a rebound.
👽 Why It Works in Crypto
The cryptocurrency market is heavily driven by retail investor sentiment and volatility. Research shows that:
Small-Cap Cryptos: Tend to experience higher volatility and speculative trends, making them ideal for momentum trades.
Large-Cap Cryptos: Exhibit more predictable behavior, making them suitable for mean-reversion strategies when momentum is low.
This indicator captures these dynamics to give traders a strategic edge in identifying both momentum and reversal opportunities.
👽 Indicator Settings
👾 Rebalance Period: The frequency at which momentum and trade suggestions are recalculated (Daily, Weekly, Monthly).
Shorter Periods (Daily): Fast updates, suitable for short-term trades, but more noise.
Longer Periods (Weekly/Monthly): Smoother signals, ideal for swing trading and more stable trends.
👾 Momentum Period: The lookback period for momentum calculation (default is 14 bars).
Shorter Periods: More responsive but prone to noise.
Longer Periods : Reflects broader trends, reducing sensitivity to short-term fluctuations.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
Weekly and daily separators ภาษาไทยเอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะเอามาแก้ภาษา
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
Watermark with dynamic variables [BM]█ OVERVIEW
This indicator allows users to add highly customizable watermark messages to their charts. Perfect for branding, annotation, or displaying dynamic chart information, this script offers advanced customization options including dynamic variables, text formatting, and flexible positioning.
█ CONCEPTS
Watermarks are overlay messages on charts. This script introduces placeholders — special keywords wrapped in % signs — that dynamically replace themselves with chart-related data. These watermarks can enhance charts with context, timestamps, or branding.
█ FEATURES
Dynamic Variables : Replace placeholders with real-time data such as bar index, timestamps, and more.
Advanced Customization : Modify text size, color, background, and alignment.
Multiple Messages : Add up to four independent messages per group, with two groups supported (A and B).
Positioning Options : Place watermarks anywhere on the chart using predefined locations.
Timezone Support : Display timestamps in a preferred timezone with customizable formats.
█ INPUTS
The script offers comprehensive input options for customization. Each Watermark (A and B) contains identical inputs for configuration.
Watermark settings are divided into two levels:
Watermark-Level Settings
These settings apply to the entire watermark group (A/B):
Show Watermark: Toggle the visibility of the watermark group on the chart.
Position: Choose where the watermark group is displayed on the chart.
Reverse Line Order: Enable to reverse the order of the lines displayed in Watermark A.
Message-Level Settings
Each watermark contains up to four configurable messages. These messages can be independently customized with the following options:
Message Content: Enter the custom text to be displayed. You can include placeholders for dynamic data.
Text Size: Select from predefined sizes (Tiny, Small, Normal, Large, Huge) or specify a custom size.
Text Alignment and Colors:
- Adjust the alignment of the text (Left, Center, Right).
- Set text and background colors for better visibility.
Format Time: Enable time formatting for this watermark message and configure the format and timezone. The settings for each message include message content, text size, alignment, and more. Please refer to Formatting dates and times for more details on valid formatting tokens.
█ PLACEHOLDERS
Placeholders are special keywords surrounded by % signs, which the script dynamically replaces with specific chart-related data. These placeholders allow users to insert dynamic content, such as bar information or timestamps, into watermark messages.
Below is the complete list of currently available placeholders:
bar_index , barstate.isconfirmed , barstate.isfirst , barstate.ishistory , barstate.islast , barstate.islastconfirmedhistory , barstate.isnew , barstate.isrealtime , chart.is_heikinashi , chart.is_kagi , chart.is_linebreak , chart.is_pnf , chart.is_range , chart.is_renko , chart.is_standard , chart.left_visible_bar_time , chart.right_visible_bar_time , close , dayofmonth , dayofweek , dividends.future_amount , dividends.future_ex_date , dividends.future_pay_date , earnings.future_eps , earnings.future_period_end_time , earnings.future_revenue , earnings.future_time , high , hl2 , hlc3 , hlcc4 , hour , last_bar_index , last_bar_time , low , minute , month , ohlc4 , open , second , session.isfirstbar , session.isfirstbar_regular , session.islastbar , session.islastbar_regular , session.ismarket , session.ispostmarket , session.ispremarket , syminfo.basecurrency , syminfo.country , syminfo.currency , syminfo.description , syminfo.employees , syminfo.expiration_date , syminfo.industry , syminfo.main_tickerid , syminfo.mincontract , syminfo.minmove , syminfo.mintick , syminfo.pointvalue , syminfo.prefix , syminfo.pricescale , syminfo.recommendations_buy , syminfo.recommendations_buy_strong , syminfo.recommendations_date , syminfo.recommendations_hold , syminfo.recommendations_sell , syminfo.recommendations_sell_strong , syminfo.recommendations_total , syminfo.root , syminfo.sector , syminfo.session , syminfo.shareholders , syminfo.shares_outstanding_float , syminfo.shares_outstanding_total , syminfo.target_price_average , syminfo.target_price_date , syminfo.target_price_estimates , syminfo.target_price_high , syminfo.target_price_low , syminfo.target_price_median , syminfo.ticker , syminfo.tickerid , syminfo.timezone , syminfo.type , syminfo.volumetype , ta.accdist , ta.iii , ta.nvi , ta.obv , ta.pvi , ta.pvt , ta.tr , ta.vwap , ta.wad , ta.wvad , time , time_close , time_tradingday , timeframe.isdaily , timeframe.isdwm , timeframe.isintraday , timeframe.isminutes , timeframe.ismonthly , timeframe.isseconds , timeframe.isticks , timeframe.isweekly , timeframe.main_period , timeframe.multiplier , timeframe.period , timenow , volume , weekofyear , year
█ HOW TO USE
1 — Add the Script:
Apply "Watermark with dynamic variables " to your chart from the TradingView platform.
2 — Configure Inputs:
Open the script settings by clicking the gear icon next to the script's name.
Customize visibility, message content, and appearance for Watermark A and Watermark B.
3 — Utilize Placeholders:
Add placeholders like %bar_index% or %timenow% in the "Watermark - Message" fields to display dynamic data.
Empty lines in the message box are reflected on the chart, allowing you to shift text up or down.
Using in the message box translates to a new line on the chart.
4 — Preview Changes:
Adjust settings and view updates in real-time on your chart.
█ EXAMPLES
Branding
DodgyDD's charts
Debugging
█ LIMITATIONS
Only supports variables defined within the script.
Limited to four messages per watermark.
Visual alignment may vary across different chart resolutions or zoom levels.
Placeholder parsing relies on correct input formatting.
█ NOTES
This script is designed for users seeking enhanced chart annotation capabilities. It provides tools for dynamic, customizable watermarks but is not a replacement for chart objects like text labels or drawings. Please ensure placeholders are properly formatted for correct parsing.
Additionally, this script can be a valuable tool for Pine Script developers during debugging . By utilizing dynamic placeholders, developers can display real-time values of variables and chart data directly on their charts, enabling easier troubleshooting and code validation.
CandleCandle: A Comprehensive Pine Script™ Library for Candlestick Analysis
Overview
The Candle library, developed in Pine Script™, provides traders and developers with a robust toolkit for analyzing candlestick data. By offering easy access to fundamental candlestick components like open, high, low, and close prices, along with advanced derived metrics such as body-to-wick ratios, percentage calculations, and volatility analysis, this library enables detailed insights into market behavior.
This library is ideal for creating custom indicators, trading strategies, and backtesting frameworks, making it a powerful resource for any Pine Script™ developer.
Key Features
1. Core Candlestick Data
• Open : Access the opening price of the current candle.
• High : Retrieve the highest price.
• Low : Retrieve the lowest price.
• Close : Access the closing price.
2. Candle Metrics
• Full Size : Calculates the total range of the candle (high - low).
• Body Size : Computes the size of the candle’s body (open - close).
• Wick Size : Provides the combined size of the upper and lower wicks.
3. Wick and Body Ratios
• Upper Wick Size and Lower Wick Size .
• Body-to-Wick Ratio and Wick-to-Body Ratio .
4. Percentage Calculations
• Upper Wick Percentage : The proportion of the upper wick size relative to the full candle size.
• Lower Wick Percentage : The proportion of the lower wick size relative to the full candle size.
• Body Percentage and Wick Percentage relative to the candle’s range.
5. Candle Direction Analysis
• Determines if a candle is "Bullish" or "Bearish" based on its closing and opening prices.
6. Price Metrics
• Average Price : The mean of the open, high, low, and close prices.
• Midpoint Price : The midpoint between the high and low prices.
7. Volatility Measurement
• Calculates the standard deviation of the OHLC prices, providing a volatility metric for the current candle.
Code Architecture
Example Functionality
The library employs a modular structure, exporting various functions that can be used independently or in combination. For instance:
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © DevArjun
//@version=6
indicator("Candle Data", overlay = true)
import DevArjun/Candle/1 as Candle
// Body Size %
bodySize = Candle.BodySize()
// Determining the candle direction
candleDirection = Candle.CandleDirection()
// Calculating the volatility of the current candle
volatility = Candle.Volatility()
// Plotting the metrics (for demonstration)
plot(bodySize, title="Body Size", color=color.blue)
label.new(bar_index, high, candleDirection, style=label.style_circle)
Scalability
The modularity of the Candle library allows seamless integration into more extensive trading systems. Functions can be mixed and matched to suit specific analytical or strategic needs.
Use Cases
Trading Strategies
Developers can use the library to create strategies based on candle properties such as:
• Identifying long-bodied candles (momentum signals).
• Detecting wicks as potential reversal zones.
• Filtering trades based on candle ratios.
Visualization
Plotting components like body size, wick size, and directional labels helps visualize market behavior and identify patterns.
Backtesting
By incorporating volatility and ratio metrics, traders can design and test strategies on historical data, ensuring robust performance before live trading.
Education
This library is a great tool for teaching candlestick analysis and how each component contributes to market behavior.
Portfolio Highlights
Project Objective
To create a Pine Script™ library that simplifies candlestick analysis by providing comprehensive metrics and insights, empowering traders and developers with advanced tools for market analysis.
Development Challenges and Solutions
• Challenge : Achieving high precision in calculating ratios and percentages.
• Solution : Implemented robust mathematical operations and safeguarded against division-by-zero errors.
• Challenge : Ensuring modularity and scalability.
• Solution : Designed functions as independent modules, allowing flexible integration.
Impact
• Efficiency : The library reduces the time required to calculate complex candlestick metrics.
• Versatility : Supports various trading styles, from scalping to swing trading.
• Clarity : Clean code and detailed documentation ensure usability for developers of all levels.
Conclusion
The Candle library exemplifies the power of Pine Script™ in simplifying and enhancing candlestick analysis. By including this project in your portfolio, you showcase your expertise in:
• Financial data analysis.
• Pine Script™ development.
• Creating tools that solve real-world trading challenges.
This project demonstrates both technical proficiency and a keen understanding of market analysis, making it an excellent addition to your professional portfolio.
Library "Candle"
A comprehensive library to access and analyze the basic components of a candlestick, including open, high, low, close prices, and various derived metrics such as full size, body size, wick sizes, ratios, percentages, and additional analysis metrics.
Open()
Open
@description Returns the opening price of the current candle.
Returns: float - The opening price of the current candle.
High()
High
@description Returns the highest price of the current candle.
Returns: float - The highest price of the current candle.
Low()
Low
@description Returns the lowest price of the current candle.
Returns: float - The lowest price of the current candle.
Close()
Close
@description Returns the closing price of the current candle.
Returns: float - The closing price of the current candle.
FullSize()
FullSize
@description Returns the full size (range) of the current candle (high - low).
Returns: float - The full size of the current candle.
BodySize()
BodySize
@description Returns the body size of the current candle (open - close).
Returns: float - The body size of the current candle.
WickSize()
WickSize
@description Returns the size of the wicks of the current candle (full size - body size).
Returns: float - The size of the wicks of the current candle.
UpperWickSize()
UpperWickSize
@description Returns the size of the upper wick of the current candle.
Returns: float - The size of the upper wick of the current candle.
LowerWickSize()
LowerWickSize
@description Returns the size of the lower wick of the current candle.
Returns: float - The size of the lower wick of the current candle.
BodyToWickRatio()
BodyToWickRatio
@description Returns the ratio of the body size to the wick size of the current candle.
Returns: float - The body to wick ratio of the current candle.
UpperWickPercentage()
UpperWickPercentage
@description Returns the percentage of the upper wick size relative to the full size of the current candle.
Returns: float - The percentage of the upper wick size relative to the full size of the current candle.
LowerWickPercentage()
LowerWickPercentage
@description Returns the percentage of the lower wick size relative to the full size of the current candle.
Returns: float - The percentage of the lower wick size relative to the full size of the current candle.
WickToBodyRatio()
WickToBodyRatio
@description Returns the ratio of the wick size to the body size of the current candle.
Returns: float - The wick to body ratio of the current candle.
BodyPercentage()
BodyPercentage
@description Returns the percentage of the body size relative to the full size of the current candle.
Returns: float - The percentage of the body size relative to the full size of the current candle.
WickPercentage()
WickPercentage
@description Returns the percentage of the wick size relative to the full size of the current candle.
Returns: float - The percentage of the wick size relative to the full size of the current candle.
CandleDirection()
CandleDirection
@description Returns the direction of the current candle.
Returns: string - "Bullish" if the candle is bullish, "Bearish" if the candle is bearish.
AveragePrice()
AveragePrice
@description Returns the average price of the current candle (mean of open, high, low, and close).
Returns: float - The average price of the current candle.
MidpointPrice()
MidpointPrice
@description Returns the midpoint price of the current candle (mean of high and low).
Returns: float - The midpoint price of the current candle.
Volatility()
Volatility
@description Returns the standard deviation of the OHLC prices of the current candle.
Returns: float - The volatility of the current candle.
Median Deviation Suite [InvestorUnknown]The Median Deviation Suite uses a median-based baseline derived from a Double Exponential Moving Average (DEMA) and layers multiple deviation measures around it. By comparing price to these deviation-based ranges, it attempts to identify trends and potential turning points in the market. The indicator also incorporates several deviation types—Average Absolute Deviation (AAD), Median Absolute Deviation (MAD), Standard Deviation (STDEV), and Average True Range (ATR)—allowing traders to visualize different forms of volatility and dispersion. Users should calibrate the settings to suit their specific trading approach, as the default values are not optimized.
Core Components
Median of a DEMA:
The foundation of the indicator is a Median applied to the 7-day DEMA (Double Exponential Moving Average). DEMA aims to reduce lag compared to simple or exponential moving averages. By then taking a median over median_len periods of the DEMA values, the indicator creates a robust and stable central tendency line.
float dema = ta.dema(src, 7)
float median = ta.median(dema, median_len)
Multiple Deviation Measures:
Around this median, the indicator calculates several measures of dispersion:
ATR (Average True Range): A popular volatility measure.
STDEV (Standard Deviation): Measures the spread of price data from its mean.
MAD (Median Absolute Deviation): A robust measure of variability less influenced by outliers.
AAD (Average Absolute Deviation): Similar to MAD, but uses the mean absolute deviation instead of median.
Average of Deviations (avg_dev): The average of the above four measures (ATR, STDEV, MAD, AAD), providing a combined sense of volatility.
Each measure is multiplied by a user-defined multiplier (dev_mul) to scale the width of the bands.
aad = f_aad(src, dev_len, median) * dev_mul
mad = f_mad(src, dev_len, median) * dev_mul
stdev = ta.stdev(src, dev_len) * dev_mul
atr = ta.atr(dev_len) * dev_mul
avg_dev = math.avg(aad, mad, stdev, atr)
Deviation-Based Bands:
The indicator creates multiple upper and lower lines based on each deviation type. For example, using MAD:
float mad_p = median + mad // already multiplied by dev_mul
float mad_m = median - mad
Similar calculations are done for AAD, STDEV, ATR, and the average of these deviations. The indicator then determines the overall upper and lower boundaries by combining these lines:
float upper = f_max4(aad_p, mad_p, stdev_p, atr_p)
float lower = f_min4(aad_m, mad_m, stdev_m, atr_m)
float upper2 = f_min4(aad_p, mad_p, stdev_p, atr_p)
float lower2 = f_max4(aad_m, mad_m, stdev_m, atr_m)
This creates a layered structure of volatility envelopes. Traders can observe which layers price interacts with to gauge trend strength.
Determining Trend
The indicator generates trend signals by assessing where price stands relative to these deviation-based lines. It assigns a trend score by summing individual signals from each deviation measure. For instance, if price crosses above the MAD-based upper line, it contributes a bullish point; crossing below an ATR-based lower line contributes a bearish point.
When the aggregated trend score crosses above zero, it suggests a shift towards a bullish environment; crossing below zero indicates a bearish bias.
// Define Trend scores
var int aad_t = 0
if ta.crossover(src, aad_p)
aad_t := 1
if ta.crossunder(src, aad_m)
aad_t := -1
var int mad_t = 0
if ta.crossover(src, mad_p)
mad_t := 1
if ta.crossunder(src, mad_m)
mad_t := -1
var int stdev_t = 0
if ta.crossover(src, stdev_p)
stdev_t := 1
if ta.crossunder(src, stdev_m)
stdev_t := -1
var int atr_t = 0
if ta.crossover(src, atr_p)
atr_t := 1
if ta.crossunder(src, atr_m)
atr_t := -1
var int adev_t = 0
if ta.crossover(src, adev_p)
adev_t := 1
if ta.crossunder(src, adev_m)
adev_t := -1
int upper_t = src > upper ? 3 : 0
int lower_t = src < lower ? 0 : -3
int upper2_t = src > upper2 ? 1 : 0
int lower2_t = src < lower2 ? 0 : -1
float trend = aad_t + mad_t + stdev_t + atr_t + adev_t + upper_t + lower_t + upper2_t + lower2_t
var float sig = 0
if ta.crossover(trend, 0)
sig := 1
else if ta.crossunder(trend, 0)
sig := -1
Practical Usage and Calibration
Default settings are not optimized: The given parameters serve as a starting point for demonstration. Users should adjust:
median_len: Affects how smooth and lagging the median of the DEMA is.
dev_len and dev_mul: Influence the sensitivity of the deviation measures. Larger multipliers widen the bands, potentially reducing false signals but introducing more lag. Smaller multipliers tighten the bands, producing quicker signals but potentially more whipsaws.
This flexibility allows the trader to tailor the indicator for various markets (stocks, forex, crypto) and time frames.
Backtesting and Performance Metrics
The code integrates with a backtesting library that allows traders to:
Evaluate the strategy historically
Compare the indicator’s signals with a simple buy-and-hold approach
Generate performance metrics (e.g., mean returns, Sharpe Ratio, Sortino Ratio) to assess historical effectiveness.
Disclaimer
No guaranteed results: Historical performance does not guarantee future outcomes. Market conditions can vary widely.
User responsibility: Traders should combine this indicator with other forms of analysis, appropriate risk management, and careful calibration of parameters.
R-based Strategy Template [Daveatt]Have you ever wondered how to properly track your trading performance based on risk rather than just profits?
This template solves that problem by implementing R-multiple tracking directly in TradingView's strategy tester.
This script is a tool that you must update with your own trading entry logic.
Quick notes
Before we dive in, I want to be clear: this is a template focused on R-multiple calculation and visualization.
I'm using a basic RSI strategy with dummy values just to demonstrate how the R tracking works. The actual trading signals aren't important here - you should replace them with your own strategy logic.
R multiple logic
Let's talk about what R-multiple means in practice.
Think of R as your initial risk per trade.
For instance, if you have a $10,000 account and you're risking 1% per trade, your 1R would be $100.
A trade that makes twice your risk would be +2R ($200), while hitting your stop loss would be -1R (-$100).
This way of measuring makes it much easier to evaluate your strategy's performance regardless of account size.
Whenever the SL is hit, we lose -1R
Proof showing the strategy tester whenever the SL is hit: i.imgur.com
The magic happens in how we calculate position sizes.
The script automatically determines the right position size to risk exactly your specified percentage on each trade.
This is done through a simple but powerful calculation:
risk_amount = (strategy.equity * (risk_per_trade_percent / 100))
sl_distance = math.abs(entry_price - sl_price)
position_size = risk_amount / (sl_distance * syminfo.pointvalue)
Limitations with lower timeframe gaps
This ensures that if your stop loss gets hit, you'll lose exactly the amount you intended to risk. No more, no less.
Well, could be more or less actually ... let's assume you're trading futures on a 15-minute chart but in the 1-minute chart there is a gap ... then your 15 minute SL won't get filled and you'll likely to not lose exactly -1R
This is annoying but it can't be fixed - and that's how trading works anyway.
Features
The template gives you flexibility in how you set your stop losses. You can use fixed points, ATR-based stops, percentage-based stops, or even tick-based stops.
Regardless of which method you choose, the position sizing will automatically adjust to maintain your desired risk per trade.
To help you track performance, I've added a comprehensive statistics table in the top right corner of your chart.
It shows you everything you need to know about your strategy's performance in terms of R-multiples: how many R you've won or lost, your win rate, average R per trade, and even your longest winning and losing streaks.
Happy trading!
And remember, measuring your performance in R-multiples is one of the most classical ways to evaluate and improve your trading strategies.
Daveatt
Spread Analysis (COIN/BTC)The Spread Analysis (COIN/BTC) indicator calculates the Z-score of the price ratio between Coinbase stock ( NASDAQ:COIN ) and Bitcoin ( CRYPTOCAP:BTC ). It helps identify overbought or oversold conditions based on deviations from the historical mean of their price relationship.
Key Features:
Z-Score Calculation:
• Tracks the relative price ratio of NASDAQ:COIN to $BTC.
• Compares the current ratio to its historical average, highlighting extreme overvaluation or undervaluation.
• Buy and Sell Signals:
• Buy Signal: Triggered when the Z-score is less than -2, indicating NASDAQ:COIN may be undervalued relative to $BTC.
• Sell Signal: Triggered when the Z-score exceeds 2, suggesting NASDAQ:COIN may be overvalued relative to $BTC.
• Dynamic Z-Score Visualization:
• Blue line plots the Z-score over time.
• Dashed lines at +2 and -2 mark overbought and oversold thresholds.
• Green and red triangles highlight actionable buy and sell signals.
Use Case:
This indicator is ideal for identifying relative valuation opportunities between NASDAQ:COIN and $BTC. Use it to exploit divergences in their historical relationship and anticipate potential reversions to the mean.
Limitations:
• Best suited for range-bound markets; may produce false signals in strongly trending conditions.
• Assumes a consistent correlation between NASDAQ:COIN and CRYPTOCAP:BTC , which may break during independent price drivers like news or earnings.
IV Proxy with Support and Resistance LevelsThis is a simple script that I have created that allows us to visualize the support and resistance levels as well as the implied volatility of a particular stock better. It is self-explanatory and intuitive to use. Given the indicator's function, it is completely adjustable and requires no further inputs.
This is useful for those who wish to automate the process of finding the opening and closing prices of any security as well as their support and resistance levels. it facilitates the process of analyzing and can be used as a tool to decide on entry and exit points
Market MonitorOverview
The Market Monitor Indicator provides a customisable view of dynamic percentage changes across selected indices or sectors, calculated by comparing current and previous closing prices over the chosen timeframe.
Key Features
Choose up to 20 predefined indices or your own selected indices/stocks.
Use checkboxes to show or hide individual entries.
Monitor returns over daily, weekly, monthly, quarterly, half-yearly, or yearly timeframes
Sort by returns (descending) to quickly identify top-performing indices or alphabetically for an organised and systematic review.
Customisation
Switch between Light Mode (Blue or Green themes) and Dark Mode for visual clarity.
Adjust the table’s size, position, and location.
Customise the table title to your own choice e.g. Sectoral, Broad, Portfolio etc.
Use Cases
Use multiple instances of the script with varying timeframes to study sectoral rotation and trends.
Customise the stocks to see your portfolio returns for the day or over the past week, or longer.
TradingCharts SCTR [Bginvestor]This indicator is replicating Tradingcharts, SCTR plot. If you know, you know.
Brief description: The StockCharts Technical Rank (SCTR), conceived by technical analyst John Murphy, emerges as a pivotal tool in evaluating a stock’s technical prowess. This numerical system, colloquially known as “scooter,” gauges a stock’s strength within various groups, employing six key technical indicators across different time frames.
How to use it:
Long-term indicators (30% weight each)
-Percent above/below the 200-day exponential moving average (EMA)
-125-day rate-of-change (ROC)
Medium-term indicators (15% weight each)
-percent above/below 50-day EMA
-20-day rate-of-change
Short-term indicators (5% weight each)
-Three-day slope of percentage price oscillator histogram divided by three
-Relative strength index
How to use SCTR:
Investors select a specific group for analysis, and the SCTR assigns rankings within that group. A score of 99.99 denotes robust technical performance, while zero signals pronounced underperformance. Traders leverage this data for strategic decision-making, identifying stocks with increasing SCTR for potential buying or spotting weak stocks for potential shorting.
Credit: I've made some modifications, but credit goes to GodziBear for back engineering the averaging / scaling of the equations.
Note: Not a perfect match to TradingCharts, but very, very close.
Sector Relative Strength [Afnan]This indicator calculates and displays the relative strength (RS) of multiple sectors against a chosen benchmark. It allows you to quickly compare the performance of various sectors within any global stock market. While the default settings are configured for the Indian stock market , this tool is not limited to it; you can use it for any market by selecting the appropriate benchmark and sector indices.
📊 Key Features ⚙️
Customizable Benchmark: Select any symbol as your benchmark for relative strength calculation. The default benchmark is set to `NSE:CNX100`. This allows for global market analysis by selecting the appropriate benchmark index of any country.
Multiple Sectors: Analyze up to 23 different sector indices. The default settings include major NSE sector indices. This can be customized to any market by using the relevant sector indices of that country.
Individual Sector Control: Toggle the visibility of each sector's RS on the chart.
Color-Coded Plots: Each sector's RS is plotted with a distinct color for easy identification.
Adjustable Lookback Period: Customize the lookback period for RS calculation.
Interactive Table: A sortable table displays the current RS values for all visible sectors, allowing for quick ranking.
Table Customization: Adjust the table's position, text size, and visibility.
Zero Line: A horizontal line at zero provides a reference point for RS values.
🧭 How to Use 🗺️
Add the indicator to your TradingView chart.
Select your desired benchmark symbol. The default is `NSE:CNX100`. For example, use SPY for the US market, or DAX for the German market.
Adjust the lookback period as needed.
Enable/disable the sector indices you want to analyze. The default includes major NSE sector indices like `NSE:CNXIT`, `NSE:CNXAUTO`, etc.
Customize the table's appearance as needed.
Observe the RS plots and the table to identify sectors with relative strength or weakness.
📝 Note 💡
This indicator is designed for sectorial analysis. You can use it with any market by selecting the appropriate benchmark and sector indices.
The default settings are configured for the Indian stock market with `NSE:CNX100` as the benchmark and major NSE sector indices pre-selected.
The relative strength calculation is based on the price change of the sector index compared to the benchmark over the lookback period.
Positive RS values indicate relative outperformance, while negative values indicate relative underperformance.
👨💻 Developer 🛠️
Afnan Tajuddin
Scatter Plot with Symbol or Data Source InputsDescription of setting items
Use Symbol for X Data?
Type: Checkbox (input.bool)
Explanation: Selects whether the data used for the X axis is obtained from a “symbol” or a “data source”.
If true: data for the X axis will be taken from a symbol (e.g. stock ticker).
If false: X axis data will be taken from the specified data source (e.g., closing price or volume).
Use Symbol for Y Data?
type: checkbox (input.bool)
Explanation: Selects whether the data used for the Y axis is retrieved from a “symbol” or a “data source”.
If true: Y-axis data is obtained from symbols.
If false: Data for the Y axis is obtained from the specified data source.
Select Ticker Symbol for X Data
type: symbol input (input.symbol)
description: selects the symbol to be used for the X axis (default is “AAPL”).
If “Use Symbol for X Data?” is set to true, this symbol will be used as the data for the X axis.
Select Ticker Symbol for Y Data
Type: Symbol input (input.symbol)
description: selects the symbol to be used for the Y axis (default is “GOOG”).
If “Use Symbol for Y Data?” is set to true, this symbol will be used as the data for the Y axis.
X Data Source
type: data source input (input.source)
description: specifies the data source to be used for the X axis.
Default is “close” (closing price).
Other possible values include open, high, low, volume, etc.
Y Data Source
Type: data source input (input.source)
Description: Specifies the data source to be used for the Y axis.
Default is “volume” (volume).
Other possible values include open, high, low, close, etc.
X Offset
type: integer input (input.int)
description: sets the offset value of the X axis.
This shifts the position of the X axis on the grid. The range is from -500 to 500.
Y Offset
Type: Integer input (constant)
description: offset value for y-axis.
Defaults to 0, but can be changed to adjust the Y axis position.
grid_width
type: integer input (input.int)
description: sets the width of the grid.
The default is 200. Increasing the value results in a finer grid.
grid_height
type: integer input (input.int)
description: sets the height of the grid.
Defaults to 200. Increasing the value results in a finer grid.
Frequency of updates
type: integer input (input.int)
description: set frequency of updates.
The higher the frequency of updates, the more bars will be used to calculate minimum and maximum values.
X Tick Interval
type: integer input (input.int)
description: sets the tick interval for the X axis.
The default is 10. To increase the number of ticks, decrease the value.
Y Tick Interval
Box border color
type: select color (input.color)
description: select color for grid box border
Default is blue.
Explanation of usage
To use symbol data: Set Use Symbol for X Data?
When “Use Symbol for X Data?” and “Use Symbol for Y Data?” are set to true, the data of the specified symbol is displayed on each axis. For example, you can use “AAPL” (Apple's stock price data) for the X axis and “GOOG” (Google's stock price data) for the Y axis.
To set the symbol, select the desired ticker in Select Ticker Symbol for X Data and Select Ticker Symbol for Y Data.
To use a data source: select the
You can set Use Symbol for X Data? and Use Symbol for Y Data? to false and use the data source specified in X Data Source or Y Data Source instead (e.g., closing price or volume).
Change Grid Size:.
Set the width and height of the grid with grid_width and grid_height. Larger values allow for more detailed scatter plots.
Set Tick Intervals: Set the X Tick Interval and Y Tick Interval.
Adjust X Tick Interval and Y Tick Interval to change the tick spacing on the X and Y axes.
Data Range Adjustment: Adjust the Frequency of updates to change the frequency of updates.
The Frequency of updates can be changed to control how often the data range is updated. The higher this value, the more historical data is considered and displayed.
Box Color.
Box Border Color allows you to change the color of the box border.
This script is useful for visualizing different symbols and data sources, especially to show the relationship between financial data.
Caution.
Some data may exceed the memory size, but the scale is the same, so you will know most of the locations.
*I made it myself because I could not find anything to draw a scatter plot. You can also compare more than 3 pieces of data by displaying more than one scatter plot. Here is how to do it. Set X or Y as the reference data. Set the data you want to compare to the one that is not the standard. Next, set the same indicator and set the reference to another set of data you wish to compare. Now you can compare the three sets of data. It is effective to change the color of the display box to prevent the user from not knowing which is which. Thus, you should be able to compare more than 3 pieces of data, so give it a try.
Employee Portfolio Generator [By MUQWISHI]▋ INTRODUCTION :
The “Employee Portfolio Generator” simplifies the process of building a long-term investment portfolio tailored for employees seeking to build wealth through investments rather than traditional bank savings. The tool empowers employees to set up recurring deposits at customizable intervals, enabling to make additional purchases in a list of preferred holdings, with the ability to define the purchasing investment weight for each security. The tool serves as a comprehensive solution for tracking portfolio performance, conducting research, and analyzing specific aspects of portfolio investments. The output includes an index value, a table of holdings, and chart plots, providing a deeper understanding of the portfolio's historical movements.
_______________________
▋ OVERVIEW:
● Scenario (The chart above can be taken as an example) :
Let say, in 2010, a newly employed individual committed to saving $1,000 each month. Rather than relying on a traditional savings account, chose to invest the majority of monthly savings in stable well-established stocks. Allocating 30% of monthly saving to AMEX:SPY and another 30% to NASDAQ:QQQ , recognizing these as reliable options for steady growth. Additionally, there was an admired toward innovative business models of NASDAQ:AAPL , NASDAQ:MSFT , NASDAQ:AMZN , and NASDAQ:EBAY , leading to invest 10% in each of those companies. By the end of 2024, after 15 years, the total monthly deposits amounted to $179,000, which would have been the result of traditional saving alone. However, by sticking into long term invest, the value of the portfolio assets grew, reaching nearly $900,000.
_______________________
▋ OUTPUTS:
The table can be displayed in three formats:
1. Portfolio Index Title: displays the index name at the top, and at the bottom, it shows the index value, along with the chart timeframe, e.g., daily change in points and percentage.
2. Specifications: displays the essential information on portfolio performance, including the investment date range, total deposits, free cash, returns, and assets.
3. Holdings: a list of the holding securities inside a table that contains the ticker, last price, entry price, return percentage of the portfolio's total deposits, and latest weighted percentage of the portfolio. Additionally, a tooltip appears when the user passes the cursor over a ticker's cell, showing brief information about the company, such as the company's name, exchange market, country, sector, and industry.
4. Indication of New Deposit: An indication of a new deposit added to the portfolio for additional purchasing.
5. Chart: The portfolio's historical movements can be visualized in a plot, displayed as a bar chart, candlestick chart, or line chart, depending on the preferred format, as shown below.
_______________________
▋ INDICATOR SETTINGS:
Section(1): Table Settings
(1) Naming the index.
(2) Table location on the chart and cell size.
(3) Sorting Holdings Table. By securities’ {Return(%) Portfolio, Weight(%) Portfolio, or Ticker Alphabetical} order.
(4) Choose the type of index: {Assets, Return, or Return (%)}, and the plot type for the portfolio index: {Candle, Bar, or Line}.
(5) Positive/Negative colors.
(6) Table Colors (Title, Cell, and Text).
(7) To show/hide any of selected indicator’s components.
Section(2): Recurring Deposit Settings
(1) From DateTime of starting the investment.
(2) To DateTime of ending the investment
(3) The amount of recurring deposit into portfolio and currency.
(4) The frequency of recurring deposits into the portfolio {Weekly, 2-Weeks, Monthly, Quarterly, Yearly}
(5) The Depositing Model:
● Fixed: The amount for recurring deposits remains constant throughout the entire investment period.
● Increased %: The recurring deposit amount increases at the selected frequency and percentage throughout the entire investment period.
(5B) If the user selects “ Depositing Model: Increased % ”, specify the growth model (linear or exponential) and define the rate of increase.
Section(3): Portfolio Holdings
(1) Enable a ticker in the investment portfolio.
(2) The selected deposit frequency weight for a ticker. For example, if the monthly deposit is $1,000 and the selected weight for XYZ stock is 30%, $300 will be used to purchase shares of XYZ stock.
(3) Select up to 6 tickers that the investor is interested in for long-term investment.
Please let me know if you have any questions
Calculate Order Entry Units based on set Dollar ValuesFUNCTIONS
- Calculate UNITS quantity based on user's input dollar values.
- Show Units in table
USAGE
- Enter 6 usual order $ values
- Use units value in order entry
Tradingview doesn't have order entry in dollar value for most connections/exchanges so it's really tedious to calculate Units some other way every time.
This gives you the Units based on your most used order value sizes in a quick way.
Possible future updates
- Allow user settings for number of values to display
- Allow user option to set titles for each row
Note:
Tradingview really need to get off their butts and give us a real DOM panel and working dollar value order entry for all exchanges among other order entry panel updates.
I hope everyone is suggesting this to them.
Salience Theory Crypto Returns (AiBitcoinTrend)The Salience Theory Crypto Returns Indicator is a sophisticated tool rooted in behavioral finance, designed to identify trading opportunities in the cryptocurrency market. Based on research by Bordalo et al. (2012) and extended by Cai and Zhao (2022), it leverages salience theory—the tendency of investors, particularly retail traders, to overemphasize standout returns.
In the crypto market, dominated by sentiment-driven retail investors, salience effects are amplified. Attention disproportionately focused on certain cryptocurrencies often leads to temporary price surges, followed by reversals as the market stabilizes. This indicator quantifies these effects using a relative return salience measure, enabling traders to capitalize on price reversals and trends, offering a clear edge in navigating the volatile crypto landscape.
👽 How the Indicator Works
Salience Measure Calculation :
👾 The indicator calculates how much each cryptocurrency's return deviates from the average return of all cryptos over the selected ranking period (e.g., 21 days).
👾 This deviation is the salience measure.
👾 The more a return stands out (salient outcome), the higher the salience measure.
Ranking:
👾 Cryptos are ranked in ascending order based on their salience measures.
👾 Rank 1 (lowest salience) means the crypto is closer to the average return and is more predictable.
👾 Higher ranks indicate greater deviation and unpredictability.
Color Interpretation:
👾 Green: Low salience (closer to average) – Trending or Predictable.
👾 Red/Orange: High salience (far from average) – Overpriced/Unpredictable.
👾 Text Gradient (Teal to Light Blue): Helps visualize potential opportunities for mean reversion trades (i.e., cryptos that may return to equilibrium).
👽 Core Features
Salience Measure Calculation
The indicator calculates the salience measure for each cryptocurrency by evaluating how much its return deviates from the average market return over a user-defined ranking period. This measure helps identify which assets are trending predictably and which are likely to experience a reversal.
Dynamic Ranking System
Cryptocurrencies are dynamically ranked based on their salience measures. The ranking helps differentiate between:
Low Salience Cryptos (Green): These are trending or predictable assets.
High Salience Cryptos (Red): These are overpriced or deviating significantly from the average, signaling potential reversals.
👽 Deep Dive into the Core Mathematics
Salience Theory in Action
Salience theory explains how investors, particularly in the crypto market, tend to prefer assets with standout returns (salient outcomes). This behavior often leads to overpricing of assets with high positive returns and underpricing of those with standout negative returns. The indicator captures these deviations to anticipate mean reversions or trend continuations.
Salience Measure Calculation
// Calculate the average return
avgReturn = array.avg(returns)
// Calculate salience measure for each symbol
salienceMeasures = array.new_float()
for i = 0 to array.size(returns) - 1
ret = array.get(returns, i)
salienceMeasure = math.abs(ret - avgReturn) / (math.abs(ret) + math.abs(avgReturn) + 0.1)
array.push(salienceMeasures, salienceMeasure)
Dynamic Ranking
Cryptos are ranked in ascending order based on their salience measures:
Low Ranks: Cryptos with low salience (predictable, trending).
High Ranks: Cryptos with high salience (unpredictable, likely to revert).
👽 Applications
👾 Trend Identification
Identify cryptocurrencies that are currently trending with low salience measures (green). These assets are likely to continue their current direction, making them good candidates for trend-following strategies.
👾 Mean Reversion Trading
Cryptos with high salience measures (red to light blue) may be poised for a mean reversion. These assets are likely to correct back towards the market average.
👾 Reversal Signals
Anticipate potential reversals by focusing on high-ranked cryptos (red). These assets exhibit significant deviation and are prone to price corrections.
👽 Why It Works in Crypto
The cryptocurrency market is dominated by retail investors prone to sentiment-driven behavior. This leads to exaggerated price movements, making the salience effect a powerful predictor of reversals.
👽 Indicator Settings
👾 Ranking Period : Number of bars used to calculate the average return and salience measure.
Higher Values: Smooth out short-term volatility.
Lower Values: Make the ranking more sensitive to recent price movements.
👾 Number of Quantiles : Divide ranked assets into quantile groups (e.g., quintiles).
Higher Values: More detailed segmentation (deciles, percentiles).
Lower Values: Broader grouping (quintiles, quartiles).
👾 Portfolio Percentage : Percentage of the portfolio allocated to each selected asset.
Enter a percentage (e.g., 20 for 20%), automatically converted to a decimal (e.g., 0.20).
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
Psychological Levels- Rounding Numbers Psychological Levels Indicator
Overview:
The Psychological Levels Indicator automatically identifies and plots significant price levels based on psychological thresholds, which are key areas where market participants often focus their attention. These levels act as potential support or resistance zones due to human behavioral tendencies to round off numbers. This indicator dynamically adjusts the levels based on the stock's price range and ensures seamless visibility across the chart.
Key Features:
Dynamic Step Sizes:
The indicator adjusts the levels dynamically based on the stock price:
For prices below 500: Levels are spaced at 10.
For prices between 500 and 3000: Levels are spaced at 50, 100, and 1000.
For prices between 3000 and 10,000: Levels are spaced at 100 and 1000.
For prices above 10,000: Levels are spaced at 500 and 1000.
Extended Visibility:
The plotted levels are extended across the entire chart for improved visualization, ensuring traders can easily monitor these critical zones over time.
Customization Options:
Line Color: Choose the color for the levels to suit your charting style.
Line Style: Select from solid, dashed, or dotted lines.
Line Width: Adjust the thickness of the lines for better clarity.
Clean and Efficient Design:
The indicator only plots levels relevant to the visible chart range, avoiding unnecessary clutter and ensuring a clean workspace.
How It Works:
It calculates the relevant step sizes based on the price:
Smaller step sizes for lower-priced stocks.
Larger step sizes for higher-priced stocks.
Primary, secondary, and (if applicable) tertiary levels are plotted dynamically:
Primary Levels: The most granular levels based on the stock price.
Secondary Levels: Higher-order levels for broader significance.
Tertiary Levels: Additional levels for lower-priced stocks to enhance detail.
These levels are plotted across the chart, allowing traders to visualize key psychological areas effortlessly.
Use Cases:
Day Trading: Identify potential intraday support and resistance levels.
Swing Trading: Recognize key price zones where trends may pause or reverse.
Long-Term Investing: Gain insights into significant price zones for entry or exit strategies.
AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend)The AiTrend Pattern Matrix for kNN Forecasting (AiBitcoinTrend) is a cutting-edge indicator that combines advanced mathematical modeling, AI-driven analytics, and segment-based pattern recognition to forecast price movements with precision. This tool is designed to provide traders with deep insights into market dynamics by leveraging multivariate pattern detection and sophisticated predictive algorithms.
👽 Core Features
Segment-Based Pattern Recognition
At its heart, the indicator divides price data into discrete segments, capturing key elements like candle bodies, high-low ranges, and wicks. These segments are normalized using ATR-based volatility adjustments to ensure robustness across varying market conditions.
AI-Powered k-Nearest Neighbors (kNN) Prediction
The predictive engine uses the kNN algorithm to identify the closest historical patterns in a multivariate dictionary. By calculating the distance between current and historical segments, the algorithm determines the most likely outcomes, weighting predictions based on either proximity (distance) or averages.
Dynamic Dictionary of Historical Patterns
The indicator maintains a rolling dictionary of historical patterns, storing multivariate data for:
Candle body ranges, High-low ranges, Wick highs and lows.
This dynamic approach ensures the model adapts continuously to evolving market conditions.
Volatility-Normalized Forecasting
Using ATR bands, the indicator normalizes patterns, reducing noise and enhancing the reliability of predictions in high-volatility environments.
AI-Driven Trend Detection
The indicator not only predicts price levels but also identifies market regimes by comparing current conditions to historically significant highs, lows, and midpoints. This allows for clear visualizations of trend shifts and momentum changes.
👽 Deep Dive into the Core Mathematics
👾 Segment-Based Multivariate Pattern Analysis
The indicator analyzes price data by dividing each bar into distinct segments, isolating key components such as:
Body Ranges: Differences between the open and close prices.
High-Low Ranges: Capturing the full volatility of a bar.
Wick Extremes: Quantifying deviations beyond the body, both above and below.
Each segment contributes uniquely to the predictive model, ensuring a rich, multidimensional understanding of price action. These segments are stored in a rolling dictionary of patterns, enabling the indicator to reference historical behavior dynamically.
👾 Volatility Normalization Using ATR
To ensure robustness across varying market conditions, the indicator normalizes patterns using Average True Range (ATR). This process scales each component to account for the prevailing market volatility, allowing the algorithm to compare patterns on a level playing field regardless of differing price scales or fluctuations.
👾 k-Nearest Neighbors (kNN) Algorithm
The AI core employs the kNN algorithm, a machine-learning technique that evaluates the similarity between the current pattern and a library of historical patterns.
Euclidean Distance Calculation:
The indicator computes the multivariate distance across four distinct dimensions: body range, high-low range, wick low, and wick high. This ensures a comprehensive and precise comparison between patterns.
Weighting Schemes: The contribution of each pattern to the forecast is either weighted by its proximity (distance) or averaged, based on user settings.
👾 Prediction Horizon and Refinement
The indicator forecasts future price movements (Y_hat) by predicting logarithmic changes in the price and projecting them forward using exponential scaling. This forecast is smoothed using a user-defined EMA filter to reduce noise and enhance actionable clarity.
👽 AI-Driven Pattern Recognition
Dynamic Dictionary of Patterns: The indicator maintains a rolling dictionary of N multivariate patterns, continuously updated to reflect the latest market data. This ensures it adapts seamlessly to changing market conditions.
Nearest Neighbor Matching: At each bar, the algorithm identifies the most similar historical pattern. The prediction is based on the aggregated outcomes of the closest neighbors, providing confidence levels and directional bias.
Multivariate Synthesis: By combining multiple dimensions of price action into a unified prediction, the indicator achieves a level of depth and accuracy unattainable by single-variable models.
Visual Outputs
Forecast Line (Y_hat_line):
A smoothed projection of the expected price trend, based on the weighted contribution of similar historical patterns.
Trend Regime Bands:
Dynamic high, low, and midlines highlight the current market regime, providing actionable insights into momentum and range.
Historical Pattern Matching:
The nearest historical pattern is displayed, allowing traders to visualize similarities
👽 Applications
Trend Identification:
Detect and follow emerging trends early using dynamic trend regime analysis.
Reversal Signals:
Anticipate market reversals with high-confidence predictions based on historically similar scenarios.
Range and Momentum Trading:
Leverage multivariate analysis to understand price ranges and momentum, making it suitable for both breakout and mean-reversion strategies.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
Standard Deviation of Returns: DivergencePurpose:
The "Standard Deviation of Returns: Divergence" indicator is designed to help traders identify potential trend reversals or continuation signals by analyzing divergences between price action and the statistical volatility of returns. Divergences can signal weakening momentum in the prevailing trend, offering insight into potential buying or selling opportunities.
Key Components
1. Returns Calculation:
* The indicator uses logarithmic returns (log(close / close )) to measure relative price changes in a normalized manner.
* Log returns are more effective than simple price differences when analyzing data across varying price levels, as they account for percentage-based changes.
2. Standard Deviation of Returns:
* The script computes the standard deviation of returns over a user-defined lookback period (ta.stdev(returns, lookback)).
* Standard deviation measures the dispersion of returns around their average, effectively quantifying market volatility.
* A higher standard deviation indicates increased volatility, while lower standard deviation reflects a calmer market.
3. Price Action:
* Detects higher highs (new peaks in price) and lower lows (new troughs in price) over the lookback period.
* Price trends are compared to the behavior of the standard deviation.
4. Divergence Detection:
A divergence occurs when price action (higher highs or lower lows) is not confirmed by a corresponding movement in standard deviation:
Bullish Divergence: Price makes a lower low, but the standard deviation does not, signaling potential upward momentum.
Bearish Divergence: Price makes a higher high, but the standard deviation does not, signaling potential downward momentum.
5. Visual Cues:
The script highlights divergence regions directly on the chart:
Green Background: Indicates a bullish divergence (potential buy signal).
Red Background: Indicates a bearish divergence (potential sell signal).
How It Works
Inputs:
* The user specifies the lookback period (lookback) for calculating the standard deviation and detecting divergences.
Calculation:
* Each bar’s returns are computed and used to calculate the standard deviation over the specified lookback period.
* The indicator evaluates price highs/lows and compares these with the highest and lowest values of the standard deviation within the same lookback period.
Highlight of Divergences:
When divergences are detected:
Bullish Divergence: The background of the chart is shaded green.
Bearish Divergence: The background of the chart is shaded red.
Trading Application
Bullish Divergence:
* Occurs when the market is oversold, or downward momentum is weakening.
* Suggests a potential reversal to an uptrend, signaling a buying opportunity.
Bearish Divergence:
* Occurs when the market is overbought, or upward momentum is weakening.
* Suggests a potential reversal to a downtrend, signaling a selling opportunity.
Contextual Use:
* Use this indicator in conjunction with other technical tools like RSI, MACD, or moving averages to confirm signals.
* Effective in volatile or ranging markets to help anticipate shifts in momentum.
Summary
The "Standard Deviation of Returns: Divergence" indicator is a robust tool for spotting divergences that can signal weakening market trends. It combines statistical volatility with price action analysis to highlight key areas of potential reversals. By integrating this tool into your trading strategy, you can gain additional confirmation for entries or exits while keeping a close watch on momentum shifts.
Disclaimer: This is not a financial advise; please consult your financial advisor for personalized advice.
Crypto Sectors Performance [Daveatt]IMPORTANT
⚠️ This script must be used on the Daily timeframe only.
OVERVIEW
This indicator brings the powerful sector analysis capabilities from velo.xyz/market's
Sector Performance chart to TradingView.
It enables traders to track and compare performance across the crypto market's major sectors, providing essential insights for sector rotation strategies and market analysis.
CALCULATION METHOD
The indicator calculates performance across six key crypto sectors: DeFi, Gaming, Layer 1s, Layer 2s, AI, and Memecoins.
For each sector, it computes a rolling percentage performance by averaging the performance of multiple representative tokens.
All sector performances are rebased to 0% at the start of each period, making relative comparisons clear and intuitive.
VISUALIZATION MODES
The script features two distinct visualization methods:
Plots Mode:
Displays continuous performance lines for each sector over time, ideal for tracking relative strength trends and sector momentum. Each sector has its own color-coded line with performance values clearly marked.
Bars Mode:
Presents current sector performance as vertical bars, offering an immediate visual comparison of sector gains and losses.
The bars are color-coded and labeled with exact percentage values for precise analysis.
For the "Bars Mode", I used the box.new() function
SECTOR COMPOSITION
Each sector comprises carefully selected representative tokens:
- DeFi: AAVE, 1INCH, JUP, MKR, UNI
- Gaming: GALA, AXS, RONIN, SAND
- Layer 1: BTC, ETH, AVAX, APT, SOL, BNB, SUI
- Layer 2: ARB, OP, ZK, POL, STRK, MNT
- AI: FET, NEAR, RENDER, TAO
- Memecoins: PEPE, BONK, SHIB, DOGE, WIFU, POPCAT
PERFORMANCE TRACKING
The indicator implements a rolling window approach for performance calculations.
Starting from 0% at the beginning of each period, it tracks relative performance with positive values indicating outperformance and negative values showing underperformance.
Multiple timeframe options (1W, 1M, 3M, 6M, and 1Y) allow for both short-term and long-term analysis.
APPLICATIONS
This tool proves invaluable for:
- Sector rotation analysis
- Identifying trending sectors
- Comparing relative strength
- Gauging market sentiment
- Understanding market structure through sector performance
Thanks for reading and for the support
Daveatt