DCA Simulation for CryptoCommunity v1.1DCA Simulation for CryptoCommunity v1.1
#Currently take profit is single transaction. Take profit DCA is still TBD.
This should help you to visualise how DCA strategy under your desired parameters would perform in history.
- Most importantly, it demonstrates the average price movement as DCA buy orders are occurring, providing an easy way to see how your strategy could look like.
- Dashboard will show the money spent and how many contracts acquired.
- Base order is first order, rest of orders are DCA.
- Safety orders are reset when new Higher High is made.
- TradingView has limit of 999 open trades, so if your strategy doesn't fit, just reduce the buy frequency to fit longer timeframe.
The script differs from existing published DCA's by:
- combining interval DCA & safety order DCA (based on % drops) in single script
- visualising on chart the buy levels, average price and profit taking
- calculations on dashboard to show the budget used, contracts bought. + max amounts if profit taking is in use
Statistics
QTALibrary "QTA"
This is simple library for basic Quantitative Technical Analysis for retail investors. One example of it being used can be seen here ().
calculateKellyRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns from bets.
Returns: The calculated Kelly Ratio, which indicates the optimal bet size based on winning and losing probabilities.
calculateAdjustedKellyFraction(kellyRatio, riskTolerance, fedStance)
Parameters:
kellyRatio (float) : The calculated Kelly Ratio.
riskTolerance (float) : A float representing the risk tolerance level.
fedStance (string) : A string indicating the Federal Reserve's stance ("dovish", "hawkish", or neutral).
Returns: The adjusted Kelly Fraction, constrained within the bounds of .
calculateStdDev(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the returns, or 0 if insufficient data.
calculateMaxDrawdown(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The maximum drawdown as a percentage.
calculateEV(avgWinReturn, winProb, avgLossReturn)
Parameters:
avgWinReturn (float) : The average return from winning bets.
winProb (float) : The probability of winning a bet.
avgLossReturn (float) : The average return from losing bets.
Returns: The calculated Expected Value of the bet.
calculateTailRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The Tail Ratio, or na if the 5th percentile is zero to avoid division by zero.
calculateSharpeRatio(avgReturn, riskFreeRate, stdDev)
Parameters:
avgReturn (float) : The average return of the investment.
riskFreeRate (float) : The risk-free rate of return.
stdDev (float) : The standard deviation of the investment's returns.
Returns: The calculated Sharpe Ratio, or na if standard deviation is zero.
calculateDownsideDeviation(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the downside returns, or 0 if no downside returns exist.
calculateSortinoRatio(avgReturn, downsideDeviation)
Parameters:
avgReturn (float) : The average return of the investment.
downsideDeviation (float) : The standard deviation of the downside returns.
Returns: The calculated Sortino Ratio, or na if downside deviation is zero.
calculateVaR(returns, confidenceLevel)
Parameters:
returns (array) : An array of floats representing the returns.
confidenceLevel (float) : A float representing the confidence level (e.g., 0.95 for 95% confidence).
Returns: The Value at Risk at the specified confidence level.
calculateCVaR(returns, varValue)
Parameters:
returns (array) : An array of floats representing the returns.
varValue (float) : The Value at Risk threshold.
Returns: The average Conditional Value at Risk, or na if no returns are below the threshold.
calculateExpectedPriceRange(currentPrice, ev, stdDev, confidenceLevel)
Parameters:
currentPrice (float) : The current price of the asset.
ev (float) : The expected value (in percentage terms).
stdDev (float) : The standard deviation (in percentage terms).
confidenceLevel (float) : The confidence level for the price range (e.g., 1.96 for 95% confidence).
Returns: A tuple containing the minimum and maximum expected prices.
calculateRollingStdDev(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling standard deviation of returns.
calculateRollingVariance(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling variance of returns.
calculateRollingMean(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling mean of returns.
calculateRollingCoefficientOfVariation(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling coefficient of variation of returns.
calculateRollingSumOfPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling sum of percent returns.
calculateRollingCumulativeProduct(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling cumulative product of returns.
calculateRollingCorrelation(priceReturns, volumeReturns, window)
Parameters:
priceReturns (array) : An array of floats representing the price returns.
volumeReturns (array) : An array of floats representing the volume returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling correlation.
calculateRollingPercentile(returns, window, percentile)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
percentile (int) : An integer representing the desired percentile (0-100).
Returns: An array of floats representing the rolling percentile of returns.
calculateRollingMaxMinPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: A tuple containing two arrays: rolling max and rolling min percent returns.
calculateRollingPriceToVolumeRatio(price, volData, window)
Parameters:
price (array) : An array of floats representing the price data.
volData (array) : An array of floats representing the volume data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling price-to-volume ratio.
determineMarketRegime(priceChanges)
Parameters:
priceChanges (array) : An array of floats representing the price changes.
Returns: A string indicating the market regime ("Bull", "Bear", or "Neutral").
determineVolatilityRegime(price, window)
Parameters:
price (array) : An array of floats representing the price data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the calculated volatility.
classifyVolatilityRegime(volatility)
Parameters:
volatility (array) : An array of floats representing the calculated volatility.
Returns: A string indicating the volatility regime ("Low" or "High").
method percentPositive(thisArray)
Returns the percentage of positive non-na values in this array.
This method calculates the percentage of positive values in the provided array, ignoring NA values.
Namespace types: array
Parameters:
thisArray (array)
_candleRange()
_PreviousCandleRange(barsback)
Parameters:
barsback (int) : An integer representing how far back you want to get a range
redCandle()
greenCandle()
_WhiteBody()
_BlackBody()
HighOpenDiff()
OpenLowDiff()
_isCloseAbovePreviousOpen(length)
Parameters:
length (int)
_isCloseBelowPrevious()
_isOpenGreaterThanPrevious()
_isOpenLessThanPrevious()
BodyHigh()
BodyLow()
_candleBody()
_BodyAvg(length)
_BodyAvg function.
Parameters:
length (simple int) : Required (recommended is 6).
_SmallBody(length)
Parameters:
length (simple int) : Length of the slow EMA
Returns: a series of bools, after checking if the candle body was less than body average.
_LongBody(length)
Parameters:
length (simple int)
bearWick()
bearWick() function.
Returns: a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
bullWick()
barlength()
sumbarlength()
sumbull()
sumbear()
bull_vol()
bear_vol()
volumeFightMA()
volumeFightDelta()
weightedAVG_BullVolume()
weightedAVG_BearVolume()
VolumeFightDiff()
VolumeFightFlatFilter()
avg_bull_vol(userMA)
avg_bull_vol(int) function.
Parameters:
userMA (int)
avg_bear_vol(userMA)
avg_bear_vol(int) function.
Parameters:
userMA (int)
diff_vol(userMA)
diff_vol(int) function.
Parameters:
userMA (int)
vol_flat(userMA)
vol_flat(int) function.
Parameters:
userMA (int)
_isEngulfingBullish()
_isEngulfingBearish()
dojiup()
dojidown()
EveningStar()
MorningStar()
ShootingStar()
Hammer()
InvertedHammer()
BearishHarami()
BullishHarami()
BullishBelt()
BullishKicker()
BearishKicker()
HangingMan()
DarkCloudCover()
lib_divergenceLibrary "lib_divergence"
offers a commonly usable function to detect divergences. This will take the default RSI or other symbols / indicators / oscillators as source data.
divergence(osc, pivot_left_bars, pivot_right_bars, div_min_range, div_max_range, ref_low, ref_high, min_divergence_offset_fraction, min_divergence_offset_dev_len, min_divergence_offset_atr_mul)
Detects Divergences between Price and Oscillator action. For bullish divergences, look at trend lines between lows. For bearish divergences, look at trend lines between highs. (strong) oscillator trending, price opposing it | (medium) oscillator trending, price trend flat | (weak) price opposite trending, oscillator trend flat | (hidden) price trending, oscillator opposing it. Pivot detection is only properly done in oscillator data, reference price data is only compared at the oscillator pivot (speed optimization)
Parameters:
osc (float) : (series float) oscillator data (can be anything, even another instrument price)
pivot_left_bars (simple int) : (simple int) optional number of bars left of a confirmed pivot point, confirming it is the highest/lowest in the range before and up to the pivot (default: 5)
pivot_right_bars (simple int) : (simple int) optional number of bars right of a confirmed pivot point, confirming it is the highest/lowest in the range from and after the pivot (default: 5)
div_min_range (simple int) : (simple int) optional minimum distance to the pivot point creating a divergence (default: 5)
div_max_range (simple int) : (simple int) optional maximum amount of bars in a divergence (default: 50)
ref_low (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: low)
ref_high (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: high)
min_divergence_offset_fraction (simple float) : (simple float) optional scaling factor for the offset zone (xDeviation) around the last oscillator H/L detecting following equal H/Ls (default: 0.01)
min_divergence_offset_dev_len (simple int) : (simple int) optional lookback distance for the deviation detection for the offset zone around the last oscillator H/L detecting following equal H/Ls. Used as well for the ATR that does the equal H/L detection for the reference price. (default: 14)
min_divergence_offset_atr_mul (simple float) : (simple float) optional scaling factor for the offset zone (xATR) around the last price H/L detecting following equal H/Ls (default: 1)
@return A tuple of deviation flags.
Effort vs Result with Std DevSummary Table:
Condition Effort-Result Ratio Interpretation
High Volume, Big Price Move Above +2 SD Strong move, efficient effort.
High Volume, Small Price Move Below Mean / -2 SD Weak move, possible exhaustion.
Low Volume, Big Price Move Above Mean / +2 SD Efficient effort, momentum strong.
Low Volume, Small Price Move Near Mean Market indecision, low activity.
Time Blocks Indicator with EMA Signals (UTC+2)This indicator shows the posable time's when retracement can happen during the London session
A "Time Blocks Indicator with EMA Signals" is a technical analysis tool that combines the concept of time-based price blocks with the signals generated by Exponential Moving Averages (EMAs) to identify potential trading opportunities by highlighting specific price levels within a given timeframe, where EMA crossovers or trend changes might occur, providing a more focused view on potential entry and exit points
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.
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.
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.
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!
Weekly and daily separators ภาษาไทยเอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา เอามาแก้ภาษา
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะเอามาแก้ภาษา
ก็ลองดู
จะให้พิมพ์ไรเยอะแยะ
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.
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.
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.