Dynamic Price Oscillator [CHE]Dynamic Price Oscillator
Overview:
Welcome to the Dynamic Price Oscillator ! This indicator is designed to help traders identify potential trend reversals and divergences by comparing short-term and long-term price movements in percentage terms. It’s a powerful tool to enhance your trading strategies by spotting bullish and bearish divergences effectively.
Key Features:
Dynamic Oscillator Calculation: The DPO calculates the percentage difference between two EMAs (Exponential Moving Averages), offering insight into the relative strength of price movements.
Bullish & Bearish Divergence Detection:
The indicator highlights divergences between price and the oscillator, allowing you to identify potential reversal points with ease.
Long-Term Divergence Option: Enable or disable long-term divergences to focus on either short-term trends or broader market movements.
High/Low Markers:
Visual markers for significant peaks and troughs in the DPO, helping you quickly spot potential trade setups.
Custom Alerts: Set up alerts for both bullish and bearish divergence signals, ensuring you never miss an important opportunity.
How to Use:
Bullish Divergence: A bullish divergence occurs when price is making lower lows, but the DPO shows higher lows. This can indicate a potential reversal to the upside.
Bearish Divergence: A bearish divergence happens when price is making higher highs, but the DPO shows lower highs. This can signal a potential downside reversal.
Customizable Settings: Adjust the fast and slow EMA periods, smoothing factor, and divergence lookback to fit your personal trading style.
Ideal For:
Swing traders and day traders looking for early signs of market reversals.
Those who want a clear, visual representation of divergence between price and momentum.
Traders who appreciate flexibility with customizable parameters and built-in alerts.
Why Use Dynamic Price Oscillator ?
This indicator gives you the edge by providing a reliable way to measure price momentum and detect divergences that are often missed by other indicators. With the option to enable long-term divergences, you can tailor the indicator to fit both short-term and long-term strategies.
Give it a try and see how the Dynamic Price Oscillator can enhance your trading performance!
Best regards Chervolino
Циклический анализ
Elliott Wave Oscillator with Peak DetectionThe Elliott Wave Oscillator with Derivative Peak Detection and Breakout Bands is a technical indicator that blends traditional Elliott Wave theory with modern derivative-based peak detection and breakout bands for a clearer view of market trends.
Key Components:
Elliott Wave Oscillator (EWO):
The core of the indicator is based on the difference between two simple moving averages (SMA): a short-term SMA (default length: 5) and a long-term SMA (default length: 35).
This difference is expressed either as an absolute value or a percentage of the current price, depending on the user’s input.
Smoothing:
The EWO is smoothed using an Exponential Moving Average (EMA) to filter out noise and provide a clearer trend direction.
The smoothing length is adaptive based on the current chart's timeframe (e.g., longer smoothing for daily charts).
Derivative Peak Detection:
The smoothed EWO is analyzed for peaks (positive) and troughs (negative) by calculating the derivative (rate of change) between consecutive values.
Peaks are detected when the derivative transitions from positive to negative, while troughs are identified when the derivative switches from negative to positive.
Tolerance levels are adjustable and vary by timeframe to avoid false signals.
Breakout Bands:
Upper and lower breakout bands are dynamically generated based on the smoothed EWO.
The bands help to filter significant peaks and troughs, only highlighting those that occur beyond the breakout levels.
Users can choose to display these bands and use them to filter out less significant peaks and troughs.
Visualization:
The original, unsmoothed EWO is plotted as a histogram, with positive values in green and negative values in red.
The smoothed EWO is plotted as a blue line, providing a clearer view of the underlying trend.
The breakout bands, if enabled, are plotted as white lines to visualize the upper and lower bounds of the oscillator's movement.
Positive peaks and negative troughs that meet the filtering criteria are marked with purple triangles (for peaks) and red triangles (for troughs) on the chart.
Customization Options:
Timeframe-based Smoothing and Tolerance: Different smoothing lengths and tolerance levels can be set for daily, hourly, and 5-minute charts.
Breakout Bands: Users can toggle the display of breakout bands and adjust their visual properties.
Peak Filtering: Peaks and troughs can be filtered based on whether they break out beyond the bands, or all peaks can be shown.
This indicator provides a unique blend of trend detection through the Elliott Wave Oscillator and derivative analysis to highlight significant market reversals while offering breakout bands as a filtering mechanism for false signals.
Short-Only Cycle IndicatorThis script is a follow-up to my previous 60-day Cycle, Long-Only Indicator.
The "Short-Only Cycle Indicator" is designed to help traders navigate optimal shorting opportunities by analyzing cyclical price behavior over a defined period. It focuses on recognizing distribution phases (ideal for shorting) and accumulation phases (where shorting should be avoided). It should be used with assets that the trader has an existing thesis for downward price movement.
Key Features:
1. Cycle Length: The indicator uses a 60-day cycle to identify high and low points in price, which are then used to determine the current market phase.
2. Distribution Phase: When the price is near the cycle high, the indicator signals a distribution phase, indicating potential shorting opportunities.
3. Accumulation Phase: When the price is near the cycle low, the indicator signals an accumulation phase, advising traders to avoid shorting.
4. Short Signal: A short signal is triggered when the price crosses below the cycle high, which is visually marked on the chart for easy identification.
This indicator is particularly useful for traders who prefer a short-only strategy, as it helps them time their entries and avoid shorting during unfavorable market conditions.
Inflation-Adjusted Price IndicatorThis indicator allows traders to adjust historical prices for inflation using customizable CPI data. The script computes the adjusted price by selecting a reference date, the original price, and the CPI source (US CPI or custom input) and plots it as a line on the chart. Additionally, a table summarizes the adjusted price values and average and total inflation rates.
While the indicator serves as a standalone tool to understand inflation's impact on prices, it is a supportive element in more advanced trading strategies requiring accurate analysis of inflation-adjusted data.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Fourier For Loop [BackQuant]Fourier For Loop
PLEASE Read the following, as understanding an indicator's functionality is essential before integrating it into a trading strategy. Knowing the core logic behind each tool allows for a sound and strategic approach to trading.
Introducing BackQuant's Fourier For Loop (FFL) — a cutting-edge trading indicator that combines Fourier transforms with a for-loop scoring mechanism. This innovative approach leverages mathematical precision to extract trends and reversals in the market, helping traders make informed decisions. Let's break down the components, rationale, and potential use-cases of this indicator.
Understanding Fourier Transform in Trading
The Fourier Transform decomposes price movements into their frequency components, allowing for a detailed analysis of cyclical behavior in the market. By transforming the price data from the time domain into the frequency domain, this indicator identifies underlying patterns that traditional methods may overlook.
In this script, Fourier transforms are applied to the specified calculation source (defaulted to HLC3). The transformation yields magnitude values that can be used to score market movements over a defined range. This scoring process helps uncover long and short signals based on relative strength and trend direction.
Why Use Fourier Transforms?
Fourier Transforms excel in identifying recurring cycles and smoothing noisy data, making them ideal for fast-paced markets where price movements may be erratic. They also provide a unique perspective on market volatility, offering traders additional insights beyond standard indicators.
Calculation Logic: For-Loop Scoring Mechanism
The For Loop Scoring mechanism compares the magnitude of each transformed point in the series, summing the results to generate a score. This score forms the backbone of the signal generation system.
Long Signals: Generated when the score surpasses the defined long threshold (default set at 40). This indicates a strong bullish trend, signaling potential upward momentum.
Short Signals: Triggered when the score crosses under the short threshold (default set at -10). This suggests a bearish trend or potential downside risk.'
Thresholds & Customization
The indicator offers customizable settings to fit various trading styles:
Calculation Periods: Control how many periods the Fourier transform covers.
Long/Short Thresholds: Adjust the sensitivity of the signals to match different timeframes or risk preferences.
Visualization Options: Traders can visualize the thresholds, change the color of bars based on trend direction, and even color the background for enhanced clarity.
Trading Applications
This Fourier For Loop indicator is designed to be versatile across various market conditions and timeframes. Some of its key use-cases include:
Cycle Detection: Fourier transforms help identify recurring patterns or cycles, giving traders a head-start on market direction.
Trend Following: The for-loop scoring system helps confirm the strength of trends, allowing traders to enter positions with greater confidence.
Risk Management: With clearly defined long and short signals, traders can manage their positions effectively, minimizing exposure to false signals.
Final Note
Incorporating this indicator into your trading strategy adds a layer of mathematical precision to traditional technical analysis. Be sure to adjust the calculation start/end points and thresholds to match your specific trading style, and remember that no indicator guarantees success. Always backtest thoroughly and integrate the Fourier For Loop into a balanced trading system.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future .
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
2024 - Seasonality - Open to CloseScript Description:
This Pine Script is designed to visualise **seasonality** in the financial markets by calculating the **open-to-close percentage change** for each month of a selected asset. It creates a **heatmap** table to display the monthly performance over multiple years. The script provides detailed statistical summaries, including:
- **Average monthly percentage changes**
- **Standard deviation** of the changes
- **Percentage of months with positive returns**
The script also allows users to adjust colour intensities for positive and negative values, specify which year to start from, and skip specific months. Key metrics such as averages, standard deviations, and percentages of positive months can be toggled on or off based on user preferences. The result is a clear, visual representation of how an asset typically performs month by month, aiding in seasonality analysis.
Fed Net LiquidityNet Liquidity = Federal Reserve Total Assets - Treasury General Account (TGA) - Reverse Repurchase Agreements (RRP) Balance
1. Federal Reserve Total Assets: This is the sum of everything the Fed owns, like government bonds and mortgage-backed securities. You can snag this data from the Fed’s weekly balance sheet report.
2. Treasury General Account (TGA): Think of this as the U.S. government’s checking account at the Fed. When the TGA balance goes up, it means the government is pulling liquidity out of the market, and vice versa.
3. Reverse Repurchase Agreements (RRP) Balance: This represents the liquidity the Fed absorbs from the market through reverse repo operations. When financial institutions park money in the Fed’s RRP account, there’s less cash available in the market.
Why Use Net Liquidity?
Net liquidity is seen as a key indicator of the actual amount of money available in the market. It helps gauge the overall liquidity conditions that can influence financial markets.
Where to Find the Data:
1. Federal Reserve Total Assets: You can find this in the Fed’s weekly balance sheet (the H.4.1 report). Here’s the link: Federal Reserve Statistical Release - H.4.1.
Steps to Calculate Net Liquidity Yourself:
1. Get the Fed’s Total Assets: Look up the latest H.4.1 report and jot down the total assets figure.
2. Find the TGA Balance: Head over to the U.S. Treasury’s Daily Treasury Statement to locate the “Treasury General Account” balance.
3. Get the RRP Balance: You can find this number in the H.4.1 report or on the New York Fed’s website under “Reverse Repurchase Agreements.”
4. Do the Math: Simply subtract the TGA and RRP balances from the Fed’s total assets—that gives you the net liquidity.
Relative PPP for USDBRLThis indicator calculates the USDBRL exchange rate using the Relative Purchasing Power Parity method, which considers that the variation in the exchange rate is equal to the variation in inflation in Brazil minus the variation in inflation in the US. It is derived from the Law of One Price, which states that an identical good should have the same price in different markets when adjusted for exchange rates, assuming the absence of arbitrage barriers such as transaction costs or trade restrictions.
The indicator is calculated starting from June 1994, at the launch of the Real Plan, which equalized the value of the Brazilian Real and the US Dollar at that time. This indicator is useful for providing an idea of the long-term trend of the Dollar exchange rate (months or years), acting similarly to a moving average, around which the exchange rate gravitates.
It's useful for analysts who have to forecast the USDBRL in the long term.
US Recessions (NBER)This indicator is designed to replace the US Recessions indicator.
Unfortunately, the original indicator is now broken, and the author is not responding: www.tradingview.com .
There are other similar indicators, but they are not based on live data and either show non-officially recognized recessions or fail to display all officially recognized recessions.
This indicator shades US recession periods based on live monthly data from USREC . It highlights all officially recognized US recessions according to the NBER and will automatically shade any future recessions when they occur. The indicator works across all timeframes, correctly shading recessions whether you are viewing a 30-minute, 2-hour, daily, weekly, or any other chart timeframe.
Warning & Risks :
This indicator uses the barmerge.lookahead_on option to correctly handle monthly recession data from USREC . The purpose of this setting is to ensure that the monthly data points are applied retroactively to the corresponding bars on the chart. However, this means that while past recession periods are accurately shaded, the script is effectively displaying data from future candles and plotting it backward onto the chart.
This behavior does not introduce a “future leak” in the traditional sense—since USREC data is backward-looking and the current month always remains non-recessionary until officially confirmed. Nonetheless, it can cause confusion, as users may see recession periods shaded retroactively only after the data becomes available. Therefore, the current month will always appear non-recessionary until the next data point is released, and historical recession periods may be adjusted after the fact .
Sessions Full Markets [TradingFinder] Forex Stocks Index 7 Time🔵 Introduction
In global financial markets, particularly in FOREX and stocks, precise timing of trading sessions plays a crucial role in the success of traders. Each trading session—Asian, European, and American—has its own unique characteristics in terms of volatility and trading volume.
The Asian session (Tokyo), Sydney session, Shanghai session, European session (London and Frankfurt), and American session (New York AM and New York PM) are examples of these trading sessions, each of which opens and closes at specific times.
This session indicator also includes a Time Convertor, enabling users to view FOREX market hours based on GMT, UTC, EST, and local time. Another valuable feature of this indicator is the automatic detection of Daylight Saving Time (DST), which automatically applies time changes for the New York, London, and Sydney sessions.
🔵 How to Use
The indicator also displays session times based on the exact opening and closing times for each geographic region. Users can utilize this indicator to view trading hours either locally or in UTC time, and if needed, set their own custom trading times.
Additionally, the session information table includes the start and end times of each session and whether they are open or closed. This functionality helps traders make better trading decisions by using accurate and precise time data.
Key Features of the Session Indicator
The session indicator is a versatile and advanced tool that provides several unique features for traders.
Some of these features are :
• Automatic Daylight Saving Time (DST) Detection : This indicator dynamically detects Daylight Saving Time (DST) changes for various trading sessions, including New York, London, and Sydney, without requiring manual adjustments. This feature allows traders to manage their trades without worrying about time changes.
Below are the start and end dates for DST in the New York, London, and Sydney trading sessions :
1. New York :
Start of DST: Second Sunday of March, at 2:00 AM.
End of DST: First Sunday of November, at 2:00 AM
2. London :
Start of DST: Last Sunday of March, at 1:00 AM.
End of DST: Last Sunday of October, at 2:00 AM.
3. Sydney :
Start of DST: First Sunday of October, at 2:00 AM.
End of DST: First Sunday of April, at 3:00 AM.
• Session Display Based on Different Time Zones : The session indicator allows users to view trading times based on different time zones, such as UTC, the local time of each market, or the user’s local time. This feature is especially useful for traders operating in diverse geographic regions.
• Custom Trading Time Setup : Another notable feature of this indicator is the ability to set custom trading times. Traders can adjust their own trading times according to their personal strategies and benefit from this flexibility.
• Session Information Table : The session indicator provides a complete information table that includes the exact start and end times of each trading session and whether they are open or closed. This table helps users simultaneously and accurately monitor the status of all trading sessions and make better trading decisions.
🟣 Session Trading Hours Based on Market Mode and Time Zones
The session indicator provides precise information on the start and end times of trading sessions.
These times are adjusted based on different market modes (FOREX, stocks, and TFlab suggestions) and time zones (UTC and local time) :
🟣 (FOREX Session Time) Forex Market Mode
• Sessions in UTC (DST inactive) :
Sydney: 22:00 - 06:00
Tokyo: 23:00 - 07:00
Shanghai: 01:00 - 09:00
Asia: 22:00 - 07:00
Europe: 07:00 - 16:00
London: 08:00 - 16:00
New York: 13:00 - 21:00
• Sessions in UTC (DST active) :
Sydney: 21:00 - 05:00
Tokyo: 23:00 - 07:00
Shanghai: 01:00 - 09:00
Asia: 21:00 - 07:00
Europe: 06:00 - 15:00
London: 07:00 - 15:00
New York: 12:00 - 20:00
• Sessions in Local Time :
Sydney: 08:00 - 16:00
Tokyo: 08:00 - 16:00
Shanghai: 09:00 - 17:00
Asia: 22:00 - 07:00
Europe: 07:00 - 16:00
London: 08:00 - 16:00
New York: 08:00 - 16:00
🟣 Stock Market Trading Hours (Stock Market Mode)
• Sessions in UTC (DST inactive) :
Sydney: 00:00 - 06:00
Asia: 00:00 - 06:00
Europe: 07:00 - 16:30
London: 08:00 - 16:30
New York: 14:30 - 21:00
Tokyo: 00:00 - 06:00
Shanghai: 01:30 - 07:00
• Sessions in UTC (DST active) :
Sydney: 23:00 - 05:00
Asia: 23:00 - 06:00
Europe: 06:00 - 15:30
London: 07:00 - 15:30
New York: 13:30 - 20:00
Tokyo: 00:00 - 06:00
Shanghai: 01:30 - 07:00
• Sessions in Local Time:
Sydney: 10:00 - 16:00
Tokyo: 09:00 - 15:00
Shanghai: 09:30 - 15:00
Asia: 00:00 - 06:00
Europe: 07:00 - 16:30
London: 08:00 - 16:30
New York: 09:30 - 16:00
🟣 TFlab Suggestion Mode
• Sessions in UTC (DST inactive) :
Sydney: 23:00 - 05:00
Tokyo: 00:00 - 06:00
Shanghai: 01:00 - 09:00
Asia: 23:00 - 06:00
Europe: 07:00 - 16:00
London: 08:00 - 16:00
New York: 13:00 - 21:00
• Sessions in UTC (DST active) :
Sydney: 22:00 - 04:00
Tokyo: 00:00 - 06:00
Shanghai: 01:00 - 09:00
Asia: 22:00 - 06:00
Europe: 06:00 - 15:00
London: 07:00 - 15:00
New York: 12:00 - 20:00
• Sessions in Local Time :
Sydney: 09:00 - 16:00
Tokyo: 09:00 - 15:00
Shanghai: 09:00 - 17:00
Asia: 23:00 - 06:00
Europe: 07:00 - 16:00
London: 08:00 - 16:00
New York: 08:00 - 16:00
🔵 Setting
Using the session indicator is straightforward and practical. Users can add this indicator to their trading chart and take advantage of its features.
The usage steps are as follows :
Selecting Market Mode : The user can choose one of the three main modes.
Forex Market Mode: Displays the forex market trading hours.
oStock Market Mode: Displays the trading hours of stock exchanges.
Custom Mode: Allows the user to set trading hours based on their needs.
TFlab Suggestion Mode: Displays the higher volume hours of the forex market in Asia.
Setting the Time Zone : The indicator allows displaying sessions based on various time zones. The user can select one of the following options:
UTC (Coordinated Universal Time)
Local Time of the Session
User’s Local Time
Displaying Comprehensive Session Information : The session information table includes the opening and closing times of each session and whether they are open or closed. This table helps users monitor all sessions at a glance and precisely set the best time for entering and exiting trades.
🔵Conclusion
The session indicator is a highly efficient and essential tool for active traders in the FOREX and stock markets. With its unique features, such as automatic DST detection and the ability to display sessions based on different time zones, the session indicator helps traders to precisely and efficiently adjust their trading activities.
This indicator not only shows users the exact opening and closing times of sessions, but by providing a session status table, it helps traders identify the best times to enter and exit trades. Moreover, the ability to set custom trading times allows traders to easily personalize their trading schedules according to their strategies.
In conclusion, using the session indicator ensures that traders are continuously and accurately informed of time changes and the opening and closing hours of markets, eliminating the need for manual updates to align with DST changes. These features enable traders to optimize their trading strategies with greater confidence and up-to-date information, allowing them to capitalize on opportunities in the market.
Prometheus Topological Persistent EntropyPersistence Entropy falls under the branch of math topology. Topology is a study of shapes as they twist and contort. It can be useful in the context of markets to determine how volatile they may be and different from the past.
The key idea is to create a persistence diagram from these log return segments. The persistence diagram tracks the "birth" and "death" of price features:
A birth occurs when a new price pattern or feature emerges in the data.
A death occurs when that pattern disappears.
By comparing prices within each segment, the script tracks how long specific price features persist before they die out. The lifetime of each feature (difference between death and birth) represents how robust or fleeting the pattern is. Persistent price features tend to reflect stable trends, while shorter-lived features indicate volatility.
Entropy Calculation: The lifetimes of these patterns are then used to compute the entropy of the system. Entropy, in this case, measures the amount of disorder or randomness in the price movements. The more varied the lifetimes, the higher the entropy, indicating a more volatile market. If the price patterns exhibit longer, more consistent lifetimes, the entropy is lower, signaling a more stable market.
Calculation:
We start by getting log returns for a user defined look back value. In the compute_persistent_entropy function we separate the overall log returns into windows. We then compute persistence diagrams of the windows. It tracks the birth and death of price patterns to see how persistent they are. Then we calculate the entropy of the windows.
After we go through that process we get an array of entropies, we then smooth it by taking the sum of all of them and dividing it by how many we have so the indicator can function better.
// Calculate log returns
log_returns = array.new()
for i = 1 to lgr_lkb
array.push(log_returns, math.log(close / close ))
// Function to compute a simplified persistence diagram
compute_persistence_diagram(segment) =>
n = array.size(segment)
lifetimes = array.new()
for i = 0 to n - 1
for j = i + 1 to n - 1
birth = array.get(segment, i)
death = array.get(segment, j-1)
if birth != death
array.push(lifetimes, math.abs(death - birth))
lifetimes
// Function to compute entropy of a list of values
compute_entropy(values) =>
n = array.size(values)
if n == 0
0.0
else
freq_map = map.new()
total_sum = 0.0
for i = 0 to n - 1
value = array.get(values, i)
//freq_map := freq_map.get(value, 0.0) + 1
map.put(freq_map, value, value + 1)
total_sum += 1
entropy = 0.0
for in freq_map
p = count / total_sum
entropy -= p * math.log(p)
entropy
compute_persistent_entropy(log_returns, window_size) =>
n = (lgr_lkb) - (2 * window_size) + 1
entropies = array.new()
for i = 0 to n - 1
segment1 = array.new()
segment2 = array.new()
for j = 0 to window_size - 1
array.push(segment1, array.get(log_returns, i + j))
array.push(segment2, array.get(log_returns, i + window_size + j))
dgm1 = compute_persistence_diagram(segment1)
dgm2 = compute_persistence_diagram(segment2)
combined_diagram = array.concat(dgm1, dgm2)
entropy = compute_entropy(combined_diagram)
array.push(entropies, entropy)
entropies
//---------------------------------------------
//---------------PE----------------------------
//---------------------------------------------
// Calculate Persistent Entropy
entropies = compute_persistent_entropy(log_returns, window_size)
smooth_pe = array.sum(entropies) / array.size(entropies)
This image illustrates how the indicator works for traders. The purple line is the actual indicator value. The line that changes from green to red is a SMA of the indicator value, we use this to determine bullish or bearish. When the smoothed persistence entropy is above it’s SMA that signals bearishness.
The indicator tends to look prettier on higher time frames, we see NASDAQ:TSLA on a 4 hour here and below we see it on the 5 minute.
On a lower time frame it looks a little weird but still functions the same way.
Prometheus encourages users to use indicators as tools along with their own discretion. No indicator is 100% accurate. We encourage comments about requested features and criticism.
Leonid's Bitcoin Sharpe RatioThe Sharpe ratio is an old formula used to value the risk-adjusted return of an asset. It was developed by Nobel Laureate William F. Sharpe. In this case, I have applied it to Bitcoin with an adjustable look-back date.
The Sharpe Ratio shows you the average return earned after subtracting out the risk-free rate per unit of volatility (I've defaulted this to 0.02 ).
Volatility is a measure of the price fluctuations of an asset or portfolio. Subtracting the risk-free rate from the mean return allows you to understand what the extra returns are for taking the risk.
If the indicator is flashing red, Bitcoin is temporarily overbought (expensive).
If the indicator is flashing green, Bitcoin is temporarily oversold (cheap).
The goal of this indicator is to signal out local tops & bottoms. It can be adjusted as far as the lookback time but I have found 25-26 days to be ideal.
Crossover CounterExplanation:
Crossover Detection: We detect the crossover of the 20-period and 50-period moving averages using ta.crossover().
Tracking Price Movement: After the crossover, we start tracking the price to check if it moves up or down by 2%. If an up movement occurs before a down movement, we increment the positive counter. If a down movement occurs first, we increment the negative counter.
Reset Condition: Once either a 2% up or down move is detected, we stop tracking until the next crossover.
Table Display: A table shows the counts of positive and negative events.
Bitcoin Cycle Master [InvestorUnknown]The "Bitcoin Cycle Master" indicator is designed for in-depth, long-term analysis of Bitcoin's price cycles, using several key metrics to track market behavior and forecast potential price tops and bottoms. The indicator integrates multiple moving averages and on-chain metrics, offering a comprehensive view of Bitcoin’s historical and projected performance. Each of its components plays a crucial role in identifying critical cycle points:
Top Cap: This is a multiple of the Average Cap, which is calculated as the cumulative sum of Bitcoin’s price (price has a longer history than Market Cap) divided by its age in days. Top Cap serves as an upper boundary for speculative price peaks, multiplied by a factor of 35.
Time_dif() =>
date = ta.valuewhen(bar_index == 0, time, 0)
sec_r = math.floor(date / 1000)
min_r = math.floor(sec_r / 60)
h_r = math.floor(min_r / 60)
d_r = math.floor(h_r / 24)
// Launch of BTC
start = timestamp(2009, 1, 3, 00, 00)
sec_rb = math.floor(start / 1000)
min_rb = math.floor(sec_rb / 60)
h_rb = math.floor(min_rb / 60)
d_rb = math.floor(h_rb / 24)
difference = d_r - d_rb
AverageCap() =>
ta.cum(btc_price) / (Time_dif() + btc_age)
TopCap() =>
// To calculate Top Cap, it is first necessary to calculate Average Cap, which is the cumulative sum of Market Cap divided by the age of the market in days.
// This creates a constant time-based moving average of market cap.
// Once Average cap is calculated, those values are multiplied by 35. The result is Top Cap.
// For AverageCap the BTC price was used instead of the MC because it has more history
// (the result should have minimal if any deviation since MC would have to be divided by Supply)
AverageCap() * 35
Delta Top: Defined as the difference between the Realized Cap and the Average Cap, this metric is further multiplied by a factor of 7. Delta Top provides a historically reliable signal for Bitcoin market cycle tops.
DeltaTop() =>
// Delta Cap = Realized Cap - Average Cap
// Average Cap is explained in the Top Cap section above.
// Once Delta Cap is calculated, its values over time are then multiplied by 7. The result is Delta Top.
(RealizedPrice() - AverageCap()) * 7
Terminal Price: Derived from Coin Days Destroyed, Terminal Price normalizes Bitcoin’s historical price behavior by its finite supply (21 million bitcoins), offering an adjusted price forecast as all bitcoins approach being mined. The original formula for Terminal Price didn’t produce expected results, hence the calculation was adjusted slightly.
CVDD() =>
// CVDD stands for Cumulative Value Coin Days Destroyed.
// Coin Days Destroyed is a term used for bitcoin to identify a value of sorts to UTXO’s (unspent transaction outputs). They can be thought of as coins moving between wallets.
(MCR - TV) / 21000000
TerminalPrice() =>
// Theory:
// Before Terminal price is calculated, it is first necessary to calculate Transferred Price.
// Transferred price takes the sum of > Coin Days Destroyed and divides it by the existing supply of bitcoin and the time it has been in circulation.
// The value of Transferred Price is then multiplied by 21. Remember that there can only ever be 21 million bitcoin mined.
// This creates a 'terminal' value as the supply is all mined, a kind of reverse supply adjustment.
// Instead of heavily weighting later behavior, it normalizes historical behavior to today. By normalizing by 21, a terminal value is created
// Unfortunately the theoretical calculation didn't produce results it should, in pinescript.
// Therefore the calculation was slightly adjusted/improvised
TransferredPrice = CVDD() / (Supply * math.log(btc_age))
tp = TransferredPrice * 210000000 * 3
Realized Price: Calculated as the Market Cap Realized divided by the current supply of Bitcoin, this metric shows the average value of Bitcoin based on the price at which coins last moved, giving a market consensus price for long-term holders.
CVDD (Cumulative Value Coin Days Destroyed): This on-chain metric analyzes Bitcoin’s UTXOs (unspent transaction outputs) and the velocity of coins moving between wallets. It highlights key market dynamics during prolonged accumulation or distribution phases.
Balanced Price: The Balanced Price is the difference between the Realized Price and the Terminal Price, adjusted by Bitcoin's supply constraints. This metric provides a useful signal for identifying oversold market conditions during bear markets.
BalancedPrice() =>
// It is calculated by subtracting Transferred Price from Realized Price
RealizedPrice() - (TerminalPrice() / (21 * 3))
Each component can be toggled individually, allowing users to focus on specific aspects of Bitcoin’s price cycle and derive meaningful insights from its long-term behavior. The combination of these models provides a well-rounded view of both speculative peaks and long-term value trends.
Important consideration:
Top Cap did historically provide reliable signals for cycle peaks, however it may not be a relevant indication of peaks in the future.
Pivot-based Swing Highs and LowsRelease Notes for Pivot-based Swing Highs and Lows Indicator with HH, HL, LH, LL and Labels
Version 1.0.0
Release Date: 29th Sept 2024
Overview:
This Pine Script version 5 indicator is designed to identify and display Swing Highs and Swing Lows based on pivot points. The indicator visually marks Higher Highs (HH), Lower Highs (LH), Higher Lows (HL), and Lower Lows (LL) on the chart. The release introduces an improved visual representation with dotted lines and colored labels for easy identification of market structure, using plotshape() and line.new().
Key Features:
1. Pivot-Based Swing Identification:
The indicator uses ta.pivothigh() and ta.pivotlow() to detect significant pivot points on the chart.
The length of the pivot can be adjusted through the pivot_length parameter, allowing users to customize the sensitivity of swing identification.
2. Swing Highs and Lows with Labels:
Higher High (HH) and Lower High (LH) points are marked with green downward triangles.
Higher Low (HL) and Lower Low (LL) points are marked with red upward triangles.
The plotshape() function is used to provide clear visual markers, making it easy to spot the changes in market structure.
3. Dotted Line Visuals:
Green Dotted Lines: Connect Higher Highs (HH) and Higher Lows (HL) to their corresponding previous swings.
Red Dotted Lines: Connect Lower Highs (LH) and Lower Lows (LL) to their corresponding previous swings.
The use of color-coded dotted lines ensures better visual understanding of the trend continuation or reversal patterns.
4. Customizable Input:
The user can adjust the pivot_length parameter to fine-tune the detection of pivot highs and lows according to different timeframes or trading strategies.
Usage:
Higher High (HH): Green downward triangle, indicating a new high compared to the previous pivot high.
Lower High (LH): Green downward triangle, indicating a lower high compared to the previous pivot high.
Higher Low (HL): Red upward triangle, indicating a higher low compared to the previous pivot low.
Lower Low (LL): Red upward triangle, indicating a new lower low compared to the previous pivot low.
Dotted Lines: Connect previous swing points, helping users visualize the trend and potential market structure changes.
Improvements:
Label Substitution: In place of label.new() (which might cause issues in some environments), the indicator now uses plotshape() to provide a reliable and visually effective solution for marking swings.
Streamlined Performance: The logic for determining higher highs, lower highs, higher lows, and lower lows has been optimized for smooth performance across multiple timeframes.
Known Limitations:
No Direct Text Labels: Due to the constraints of plotshape(), text labels like "HH", "LH", "HL", and "LL" are not directly displayed. Instead, color-coded shapes are used for easy identification.
How to Use:
Apply the script to your chart via the TradingView Pine Editor.
Customize the pivot_length to suit your trading style or the timeframe you are analyzing.
Monitor the chart for marked Higher Highs, Lower Highs, Higher Lows, and Lower Lows for potential trend continuation or reversal opportunities.
Use the dotted lines to trace the evolution of market structure.
Please share your comments, thoughts. Also please follow me for more scripts in future. Mean time Happy Trading :)
ANN Trend PredictionThis trend indicator utilizes an artificial neural network (ANN) to predict the next market reversal within a certain range of previous candles. The larger the range of previous candles you set, the fewer reversals will be predicted, and trends will tend to last longer.
The ANN is trained on the BTCUSD 4-hour chart, so using it on other assets or timeframes may yield suboptimal results. It takes three input values: the closing price, the Stochastic RSI, and a Choppiness Indicator. Based on these inputs, the ANN categorizes the current candle as part of an uptrend, downtrend, or as undefined.
Compared to an EMA-based trend indicator, this ANN identifies reversals several candles earlier. It achieves this by detecting subtle patterns in the input values that typically appear before a market turnaround. These patterns are somewhat specific to that chosen asset and timeframe.
The results are displayed using rows of triangles that indicate the predicted price direction. The price levels of the triangles correspond to the closing price at the last reversal. The area between the triangle row and the price is colored green if the ANN correctly predicted the move, and red if it did not.
This indicator is designed to showcase the capabilities and potential of ANNs, and is not intended for actual trading use. The ANN can be trained on any other input values, assets and timeframes for several predictions tasks.
You can use the Predicted_Trend_Signal of this Indicator in any backtest indicator. In the Backtester just grap the Predicted_Trend_Signal. downtrend = 1, uptrend = -1, undefined = 0
Feel free to write me a comment.
asia session w shieldIntroduction
This Script displays the Asia Session Range
Description
The Indicator is based on UTC -7 timing but displays the Session Boxes automatically correct at your chart so you do not have to adjust any timings based on your Time Zone and don't have to do any calculations based on your UTC. It is already perfect.
You will see on default settings the blue Asia Box, the special ' invalid shield ' feature is there because first two hours are spread timing.
Most Timing-based Indicators have "bugged" boxes or don't show clean boxes at all and don't adjust at daylight savings times, we made sure that everything automatically gets adjusted so you don't have to! So the timings will always display at the correct time regarding the daylight savings times.
Combining Timing with Liquidity Zones the right way and in a clear, clean, and simple format.
Different than others this script also shows the "true" Asia range as it respects the "day open gap" which affects the Asia range in other scripts and it also covers the full 8 hours of Asia Session.
Recommended Use
The most beautiful display is on the M5 Timeframe as you have a clear overview of all sessions without losing the intraday view. You can also use it on the M1 for more details or the M15 for the bigger picture. The Template can hide on higher time frames starting from the H1 to not flood your chart with boxes.
How to use the Asia Session Range Box
Use the Asia Range Box as your intraday Guide, keep in mind that a Breakout of Asia high or low induces Liquidity and a common price behavior is a reversal after the fake breakout of that range.
Advanced MA Difference (and more)This Pine Script indicator calculates the difference between the price and a main moving average (SMA or EMA), allowing you to track deviations in either absolute or relative (percentage) terms. It offers several features to help visualize and smooth this difference:
- Main MA Difference: Shows the price deviation from the moving average, either as an absolute dollar amount or as a percentage.
- Fast and Slow Moving Averages: Optionally smooths the difference using fast and slow moving averages, giving insights into short-term and long-term trends in price deviations.
- Difference Between Fast and Slow MAs : Highlights the gap between these MAs, helping to identify momentum shifts.
- Customizable Visuals: Offers flexibility in displaying the difference and moving averages using lines or histograms, and includes a zero line for reference.
When to Use It:
- Use the absolute difference for tracking raw price deviations if you’re focused on concrete moves in the asset’s price.
- Use the relative difference for normalized, percentage-based deviations, especially useful when comparing different assets or time frames.
This indicator is suitable for traders looking to spot trends, price deviations, or momentum shifts relative to a moving average. Its flexibility makes it a good fit for both short-term and long-term analysis.
New York Midnight Indicator█ OVERVIEW
This script provides a visual tool for traders to track the New York Midnight (NY Midnight), a significant time marker for those who rely on New York’s financial markets. The script calculates the exact moment of midnight in New York and places a vertical line on the chart at this time, helping traders identify when a new trading day begins according to the New York time zone. The indicator also marks the midnight point with a lime-colored downward triangle to enhance visibility on the chart. It is specifically useful for traders who want to synchronize their strategies with New York’s trading hours, especially in global markets.
The script is flexible, allowing traders to adjust the UTC offset to accommodate different time zones. This is critical for those trading in different regions but still using New York as the main time reference.
█ CONCEPTS
New York Midnight: For many traders, especially those following the Forex and US stock markets, midnight in New York signifies the start of a new trading day. This point is essential for technical analysis as it often aligns with daily opening ranges, trend shifts, and volume spikes.
UTC Offset: The script includes a user-input parameter (utcOffset) to adjust the calculated time for New York midnight, ensuring that it accounts for time zone differences. This allows it to be used effectively regardless of the user’s local time zone, offering flexibility to global traders.
█ METHODOLOGY
UTC Offset Adjustment: The script starts by asking the trader to input their UTC offset (e.g., UTC -5 for New York without daylight saving time). This offset is added to the current chart time to align it with New York’s local time.
Current Hour Calculation: Once the UTC offset is applied, the script calculates the New York Hour by taking the chart’s current hour and adjusting it with the offset. This ensures that the displayed hour matches New York’s local time, regardless of the trader's location.
Vertical Line at Midnight: When the current New York hour equals 00:00 (midnight), the script plots a black vertical line on the chart. This line serves as a visual reference for the exact moment when New York's trading day begins, allowing traders to align their strategies accordingly.
Downward Triangle Plot: In addition to the vertical line, the script also adds a lime-colored downward triangle at the same bar location to further highlight the midnight point. This is useful for traders who prefer shape markers to visualize significant time events.
█ HOW TO USE
Identifying Daily Resets: The script makes it easy for traders to track when New York’s trading day resets. This is especially useful in Forex markets, where daily cycles and time zone-based volatility play an important role in price movement and volume spikes.
Time Zone Flexibility: By adjusting the UTC offset parameter, traders across the globe can synchronize their charts with New York time. This is critical for international traders who want to execute trades based on New York market patterns but reside in different time zones.
Strategic Time Marking: The vertical line and shape markers at midnight allow traders to quickly see when a new trading day starts, helping them identify patterns like the daily range, key support/resistance levels, or even potential reversals around this time.
Session-Based Analysis: Traders who work with session-based strategies (e.g., trading the Asian, European, or US sessions) can use this marker to better time their entries or exits relative to the start of the New York session.
█ METHOD VARIANTS
This script can be modified or extended in various ways to better suit specific trading strategies:
Highlighting Other Session Starts: It could be adapted to plot lines for other key session starts (e.g., London open, Tokyo open).
Multiple Time Zones: For traders who monitor several markets, the script could be extended to display midnight markers for multiple time zones.
Custom Line Styles: Users could modify the line color, thickness, or style to better match their chart aesthetic or preferences.
Monthly Breakout StrategyThis Monthly High/Low Breakout Strategy is designed to take long or short positions based on breakouts from the high or low of the previous month. Users can select whether they want to go long at a breakout above the previous month’s high, short at a breakdown below the previous month’s low, or use the reverse logic. Additionally, it includes a month filter, allowing trades to be executed only during user-specified months.
Breakout strategies, particularly those based on monthly highs and lows, aim to capitalize on price momentum. These systems rely on the assumption that once a significant price level is breached (such as the previous month's high or low), the market is likely to continue moving in the same direction due to increased volatility and trend-following behaviors by traders. Studies have demonstrated the potential effectiveness of breakout strategies in financial markets.
Scientific Evidence Supporting Breakout Strategies:
Momentum in Financial Markets:
Research on momentum-based strategies, which include breakout trading, shows that securities breaking key levels of support or resistance tend to continue their price movement in the direction of the breakout. Jegadeesh and Titman (1993) found that stocks with strong performance over a given period tend to continue performing well in subsequent periods, a principle also applied to breakout strategies.
Behavioral Finance:
The psychological factor of herd behavior is one of the driving forces behind breakout strategies. When prices break out of a key level (such as a monthly high), it triggers increased buying or selling pressure as traders join the trend. Barberis, Shleifer, and Vishny (1998) explained how cognitive biases, such as overconfidence and sentiment, can amplify price trends, which breakout strategies attempt to exploit.
Market Efficiency:
While markets are generally efficient, periods of inefficiency can occur, particularly around the breakouts of significant price levels. These inefficiencies often result in temporary price trends, which breakout strategies can exploit before the market corrects itself (Fama, 1970).
Risk Considerations:
Despite the potential for profit, the Monthly Breakout Strategy comes with several risks:
False Breakouts:
One of the most common risks in breakout strategies is the occurrence of false breakouts. These happen when the price temporarily moves above (or below) a key level but quickly reverses direction, causing losses for traders who entered positions too early. This is particularly risky in low-volatility environments.
Market Volatility:
Monthly breakout strategies rely on momentum, which may not be consistent across different market conditions. During periods of low volatility, price breakouts might lack the follow-through required for the strategy to succeed, leading to poor performance.
Whipsaw Risk:
The strategy is vulnerable to whipsaw markets, where prices oscillate around key levels without establishing a clear direction. This can result in frequent entry and exit signals that lead to losses, especially if trading costs are not managed properly.
Overfitting to Past Data:
If the month-selection filter is overly optimized based on historical data, the strategy may suffer from overfitting—performing well in backtests but poorly in real-time trading. This happens when strategies are tailored to past market conditions that may not repeat.
Conclusion:
While monthly breakout strategies can be effective in markets with strong momentum, they are subject to several risks, including false breakouts, volatility dependency, and whipsaw behavior. It is crucial to backtest this strategy thoroughly and ensure it aligns with your risk tolerance before implementing it in live trading.
References:
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1), 65-91.
Barberis, N., Shleifer, A., & Vishny, R. (1998). A Model of Investor Sentiment. Journal of Financial Economics, 49(3), 307-343.
Fama, E. F. (1970). Efficient Capital Markets: A Review of Theory and Empirical Work. Journal of Finance, 25(2), 383-417.
Inamdar Wave - Winning Wave
The **"Inamdar Wave"**, also known as the **"Winning Wave"**, is a cutting-edge market indicator designed to help traders ride the waves of momentum and capitalize on high-probability opportunities. With its unique ability to adapt to market shifts, the Inamdar Wave ensures you're always in sync with the market's most profitable moves, making it an indispensable tool for traders looking for consistent success.
### Key Features of the "Inamdar Wave":
1. **Dynamic Market Movement Detection**:
- The **Inamdar Wave** tracks the market’s momentum and identifies clear waves of movement, allowing traders to catch both upswings and downswings with ease.
- This indicator dynamically adjusts based on price action and volatility, ensuring you're always aligned with the market’s natural flow.
- Whether the market is trending or ranging, the **Inamdar Wave** keeps you on the right path, helping you surf the market's waves effortlessly.
2. **Highly Profitable Buy/Sell Signals**:
- The **Inamdar Wave** generates precise buy and sell signals that guide you to the most profitable entry and exit points.
- Its built-in filters ensure you avoid market noise, focusing only on high-probability trades that maximize your potential for profit.
- You’ll confidently enter trades at the start of each new wave, ensuring you ride the momentum for maximum gains.
3. **Visual Wave Highlighting**:
- Color-coded zones help you easily spot bullish (upward) and bearish (downward) waves.
- Green highlights signal upward waves, while red zones indicate downward waves, making it visually simple to recognize the current market direction.
- This feature allows for quick decision-making and a clear understanding of the market's direction at a glance.
4. **Tailored for Any Market Condition**:
- Whether you’re trading a calm or highly volatile market, the **Inamdar Wave** adapts to the changing conditions, ensuring consistent performance across all environments.
- Its flexibility allows it to work seamlessly with any asset class—stocks, forex, crypto, or commodities—making it an all-in-one solution for traders.
- The **Inamdar Wave**'s real-time adjustments keep it relevant regardless of market conditions or timeframes.
5. **Real-Time Alerts**:
- Get instant alerts when a new wave begins, whether it's a buy, sell, or wave reversal.
- You’ll never miss out on a profitable opportunity with real-time notifications that keep you one step ahead of the market.
- These alerts help you act quickly, maximizing the potential of every market movement.
### Inputs:
- **Wave Period**: Customize the sensitivity of the wave detection with adjustable periods to suit your trading style.
- **Signal Source**: Choose from different price sources to fine-tune how the **Inamdar Wave** reacts to market movements.
- **Signal Strength**: Control the sensitivity of wave detection to focus on only the strongest and most profitable moves.
- **Buy/Sell Signals**: Easily toggle buy/sell signals on your chart for enhanced clarity.
- **Wave Highlighting**: Turn visual wave highlights on or off, depending on your preference.
### Use Case:
The **Inamdar Wave** is perfect for traders looking to capture the most profitable waves in any market. Whether you're a short-term scalper or a long-term trend follower, this indicator keeps you in sync with the market’s natural rhythm, ensuring that you're always riding the winning wave. With its powerful buy/sell signals and dynamic wave detection, you'll be better positioned to take advantage of market momentum and secure consistent profits.
In conclusion, the **"Inamdar Wave"** is not just another indicator—it’s your key to riding the market’s most profitable waves with precision and confidence. By following the signals and staying in tune with the market’s natural flow, you’ll be able to maximize your gains and minimize your risks, ensuring a successful trading journey.
Killzones And Macros LibraryKillzones & Macros Library for Trading Sessions
This Pine Script library is designed to help traders identify and act during high-volatility trading windows, commonly referred to as "Killzones." These are specific times during the day when institutional traders are most active, resulting in increased liquidity and price movement. The library provides boolean fields that return true when the current time falls within one of the killzones or macroeconomic event windows, allowing for enhanced trade timing and precision.
Killzones Include:
London Open, New York Open, Midnight Open, London Lunch, New York PM, and more.
Capture high-volume periods like Power Hour, Equities Open, and Asian Range.
Macros:
Identify key moments like London 02:33, New York 08:50, and other significant times aligned with market movements or events.
This library is perfect for integrating into your custom strategies, backtesting, or setting alerts for optimal trade execution during major trading sessions and events.
Pi Cycle Top & Bottom Indicator [InvestorUnknown]The Pi Cycle Top & Bottom Indicator is designed for long-term cycle analysis, particularly useful for detecting significant market tops and bottoms in assets like Bitcoin. By comparing the behavior of two moving averages, one with a shorter period (default 111) and the other with a longer period (default 350), the indicator helps investors identify potential turning points in the market.
Key Features:
Dual Moving Average System:
The indicator uses two moving averages (MA) to create a cyclic oscillator. The shorter moving average (Short Length MA) is more reactive to recent price changes, while the longer moving average (Long Length MA) smooths out long-term trends. Users can select between:
Simple Moving Average (SMA): A straightforward average of closing prices.
Exponential Moving Average (EMA): Places more weight on recent prices, making it more responsive to market changes.
Oscillator Mode Options:
The Pi Cycle Indicator offers two modes of oscillation to better suit different analysis styles:
RAW Mode: This mode calculates the raw ratio of the Short MA to the Long MA, offering a simple comparison of the two averages.
LOG(X) Mode: In this mode, the oscillator takes the natural logarithm of the Short MA to Long MA ratio. This transformation compresses extreme values and highlights relative changes more effectively, making it particularly useful for spotting shifts in long-term trends.
Cyclical Analysis:
The core of the Pi Cycle Indicator is its ability to visualize the relationship between the two moving averages. The ratio of the Short MA to the Long MA is plotted as an oscillator. When the oscillator crosses above or below a baseline (which is 1 for RAW mode and 0 for LOG(X) mode), it signals potential market turning points.
Visual Representation:
The indicator provides a clear visual display of market conditions:
Orange Line: Represents the Pi Cycle Oscillator, which shows the relationship between the short and long moving averages.
Gray Baseline: A reference line that dynamically adjusts based on the oscillator mode. Crosses above or below this line help indicate possible trend reversals.
Shaded Areas: Color-filled areas between the oscillator and the baseline, which are shaded green when the market is bullish (oscillator above baseline) and red when bearish (oscillator below baseline). This provides a visual cue to assist in identifying potential market tops and bottoms.
Use Cases:
The Pi Cycle Top & Bottom Indicator is primarily used in long-term market analysis, such as Bitcoin cycles, to identify significant tops and bottoms. These moments often coincide with large cyclical shifts, making it valuable for those aiming to enter or exit positions at key moments in the market cycle.
By analyzing the interaction between short-term and long-term trends, investors can gain insight into broader market dynamics and make more informed decisions regarding entry and exit points. The ability to switch between moving average types (SMA/EMA) and oscillator modes (RAW/LOG) adds flexibility for adapting to different market environments.