Correlation Heatmap█ OVERVIEW
This indicator creates a correlation matrix for a user-specified list of symbols based on their time-aligned weekly or monthly price returns. It calculates the Pearson correlation coefficient for each possible symbol pair, and it displays the results in a symmetric table with heatmap-colored cells. This format provides an intuitive view of the linear relationships between various symbols' price movements over a specific time range.
█ CONCEPTS
Correlation
Correlation typically refers to an observable statistical relationship between two datasets. In a financial time series context, it usually represents the extent to which sampled values from a pair of datasets, such as two series of price returns, vary jointly over time. More specifically, in this context, correlation describes the strength and direction of the relationship between the samples from both series.
If two separate time series tend to rise and fall together proportionally, they might be highly correlated. Likewise, if the series often vary in opposite directions, they might have a strong anticorrelation . If the two series do not exhibit a clear relationship, they might be uncorrelated .
Traders frequently analyze asset correlations to help optimize portfolios, assess market behaviors, identify potential risks, and support trading decisions. For instance, correlation often plays a key role in diversification . When two instruments exhibit a strong correlation in their returns, it might indicate that buying or selling both carries elevated unsystematic risk . Therefore, traders often aim to create balanced portfolios of relatively uncorrelated or anticorrelated assets to help promote investment diversity and potentially offset some of the risks.
When using correlation analysis to support investment decisions, it is crucial to understand the following caveats:
• Correlation does not imply causation . Two assets might vary jointly over an analyzed range, resulting in high correlation or anticorrelation in their returns, but that does not indicate that either instrument directly influences the other. Joint variability between assets might occur because of shared sensitivities to external factors, such as interest rates or global sentiment, or it might be entirely coincidental. In other words, correlation does not provide sufficient information to identify cause-and-effect relationships.
• Correlation does not predict the future relationship between two assets. It only reflects the estimated strength and direction of the relationship between the current analyzed samples. Financial time series are ever-changing. A strong trend between two assets can weaken or reverse in the future.
Correlation coefficient
A correlation coefficient is a numeric measure of correlation. Several coefficients exist, each quantifying different types of relationships between two datasets. The most common and widely known measure is the Pearson product-moment correlation coefficient , also known as the Pearson correlation coefficient or Pearson's r . Usually, when the term "correlation coefficient" is used without context, it refers to this correlation measure.
The Pearson correlation coefficient quantifies the strength and direction of the linear relationship between two variables. In other words, it indicates how consistently variables' values move together or in opposite directions in a proportional, linear manner. Its formula is as follows:
𝑟(𝑥, 𝑦) = cov(𝑥, 𝑦) / (𝜎𝑥 * 𝜎𝑦)
Where:
• 𝑥 is the first variable, and 𝑦 is the second variable.
• cov(𝑥, 𝑦) is the covariance between 𝑥 and 𝑦.
• 𝜎𝑥 is the standard deviation of 𝑥.
• 𝜎𝑦 is the standard deviation of 𝑦.
In essence, the correlation coefficient measures the covariance between two variables, normalized by the product of their standard deviations. The coefficient's value ranges from -1 to 1, allowing a more straightforward interpretation of the relationship between two datasets than what covariance alone provides:
• A value of 1 indicates a perfect positive correlation over the analyzed sample. As one variable's value changes, the other variable's value changes proportionally in the same direction .
• A value of -1 indicates a perfect negative correlation (anticorrelation). As one variable's value increases, the other variable's value decreases proportionally.
• A value of 0 indicates no linear relationship between the variables over the analyzed sample.
Aligning returns across instruments
In a financial time series, each data point (i.e., bar) in a sample represents information collected in periodic intervals. For instance, on a "1D" chart, bars form at specific times as successive days elapse.
However, the times of the data points for a symbol's standard dataset depend on its active sessions , and sessions vary across instrument types. For example, the daily session for NYSE stocks is 09:30 - 16:00 UTC-4/-5 on weekdays, Forex instruments have 24-hour sessions that span from 17:00 UTC-4/-5 on one weekday to 17:00 on the next, and new daily sessions for cryptocurrencies start at 00:00 UTC every day because crypto markets are consistently open.
Therefore, comparing the standard datasets for different asset types to identify correlations presents a challenge. If two symbols' datasets have bars that form at unaligned times, their correlation coefficient does not accurately describe their relationship. When calculating correlations between the returns for two assets, both datasets must maintain consistent time alignment in their values and cover identical ranges for meaningful results.
To address the issue of time alignment across instruments, this indicator requests confirmed weekly or monthly data from spread tickers constructed from the chart's ticker and another specified ticker. The datasets for spreads are derived from lower-timeframe data to ensure the values from all symbols come from aligned points in time, allowing a fair comparison between different instrument types. Additionally, each spread ticker ID includes necessary modifiers, such as extended hours and adjustments.
In this indicator, we use the following process to retrieve time-aligned returns for correlation calculations:
1. Request the current and previous prices from a spread representing the sum of the chart symbol and another symbol ( "chartSymbol + anotherSymbol" ).
2. Request the prices from another spread representing the difference between the two symbols ( "chartSymbol - anotherSymbol" ).
3. Calculate half of the difference between the values from both spreads ( 0.5 * (requestedSum - requestedDifference) ). The results represent the symbol's prices at times aligned with the sample points on the current chart.
4. Calculate the arithmetic return of the retrieved prices: (currentPrice - previousPrice) / previousPrice
5. Repeat steps 1-4 for each symbol requiring analysis.
It's crucial to note that because this process retrieves prices for a symbol at times consistent with periodic points on the current chart, the values can represent prices from before or after the closing time of the symbol's usual session.
Additionally, note that the maximum number of weeks or months in the correlation calculations depends on the chart's range and the largest time range common to all the requested symbols. To maximize the amount of data available for the calculations, we recommend setting the chart to use a daily or higher timeframe and specifying a chart symbol that covers a sufficient time range for your needs.
█ FEATURES
This indicator analyzes the correlations between several pairs of user-specified symbols to provide a structured, intuitive view of the relationships in their returns. Below are the indicator's key features:
Requesting a list of securities
The "Symbol list" text box in the indicator's "Settings/Inputs" tab accepts a comma-separated list of symbols or ticker identifiers with optional spaces (e.g., "XOM, MSFT, BITSTAMP:BTCUSD"). The indicator dynamically requests returns for each symbol in the list, then calculates the correlation between each pair of return series for its heatmap display.
Each item in the list must represent a valid symbol or ticker ID. If the list includes an invalid symbol, the script raises a runtime error.
To specify a broker/exchange for a symbol, include its name as a prefix with a colon in the "EXCHANGE:SYMBOL" format. If a symbol in the list does not specify an exchange prefix, the indicator selects the most commonly used exchange when requesting the data.
Note that the number of symbols allowed in the list depends on the user's plan. Users with non-professional plans can compare up to 20 symbols with this indicator, and users with professional plans can compare up to 32 symbols.
Timeframe and data length selection
The "Returns timeframe" input specifies whether the indicator uses weekly or monthly returns in its calculations. By default, its value is "1M", meaning the indicator analyzes monthly returns. Note that this script requires a chart timeframe lower than or equal to "1M". If the chart uses a higher timeframe, it causes a runtime error.
To customize the length of the data used in the correlation calculations, use the "Max periods" input. When enabled, the indicator limits the calculation window to the number of periods specified in the input field. Otherwise, it uses the chart's time range as the limit. The top-left corner of the table shows the number of confirmed weeks or months used in the calculations.
It's important to note that the number of confirmed periods in the correlation calculations is limited to the largest time range common to all the requested datasets, because a meaningful correlation matrix requires analyzing each symbol's returns under the same market conditions. Therefore, the correlation matrix can show different results for the same symbol pair if another listed symbol restricts the aligned data to a shorter time range.
Heatmap display
This indicator displays the correlations for each symbol pair in a heatmap-styled table representing a symmetric correlation matrix. Each row and column corresponds to a specific symbol, and the cells at their intersections correspond to symbol pairs . For example, the cell at the "AAPL" row and "MSFT" column shows the weekly or monthly correlation between those two symbols' returns. Likewise, the cell at the "MSFT" row and "AAPL" column shows the same value.
Note that the main diagonal cells in the display, where the row and column refer to the same symbol, all show a value of 1 because any series of non-na data is always perfectly correlated with itself.
The background of each correlation cell uses a gradient color based on the correlation value. By default, the gradient uses blue hues for positive correlation, orange hues for negative correlation, and white for no correlation. The intensity of each blue or orange hue corresponds to the strength of the measured correlation or anticorrelation. Users can customize the gradient's base colors using the inputs in the "Color gradient" section of the "Settings/Inputs" tab.
█ FOR Pine Script® CODERS
• This script uses the `getArrayFromString()` function from our ValueAtTime library to process the input list of symbols. The function splits the "string" value by its commas, then constructs an array of non-empty strings without leading or trailing whitespaces. Additionally, it uses the str.upper() function to convert each symbol's characters to uppercase.
• The script's `getAlignedReturns()` function requests time-aligned prices with two request.security() calls that use spread tickers based on the chart's symbol and another symbol. Then, it calculates the arithmetic return using the `changePercent()` function from the ta library. The `collectReturns()` function uses `getAlignedReturns()` within a loop and stores the data from each call within a matrix . The script calls the `arrayCorrelation()` function on pairs of rows from the returned matrix to calculate the correlation values.
• For consistency, the `getAlignedReturns()` function includes extended hours and dividend adjustment modifiers in its data requests. Additionally, it includes other settings inherited from the chart's context, such as "settlement-as-close" preferences.
• A Pine script can execute up to 40 or 64 unique `request.*()` function calls, depending on the user's plan. The maximum number of symbols this script compares is half the plan's limit, because `getAlignedReturns()` uses two request.security() calls.
• This script can use the request.security() function within a loop because all scripts in Pine v6 enable dynamic requests by default. Refer to the Dynamic requests section of the Other timeframes and data page to learn more about this feature, and see our v6 migration guide to learn what's new in Pine v6.
• The script's table uses two distinct color.from_gradient() calls in a switch structure to determine the cell colors for positive and negative correlation values. One call calculates the color for values from -1 to 0 based on the first and second input colors, and the other calculates the colors for values from 0 to 1 based on the second and third input colors.
Look first. Then leap.
Statistics
Intrinsic Event (Multi DC OS)Overview
This indicator implements an event-based approach to analyze price movements in the foreign exchange market, inspired by the intrinsic time framework introduced in Fractals and Intrinsic Time - A Challenge to Econometricians by U. A. Müller et al. (1995). It identifies significant price events using an intrinsic time perspective and supports multi-agent analysis to reflect the heterogeneous nature of financial markets. The script plots these events as lines and labels on the chart, offering a visual tool for traders to understand market dynamics at different scales.
Key Features
Intrinsic Events : The indicator detects directional change (DC) and overshoot (OS) events based on user-defined thresholds (delta), aligning with the paper’s concept of intrinsic time (Section 6). Intrinsic time redefines time based on market activity, expanding during volatile periods and contracting during inactive ones, rather than relying on a physical clock.
Multi-Agent Analysis : Supports up to five agents, each with its own threshold and color settings, reflecting the heterogeneous market hypothesis (Section 5). This allows the indicator to capture the perspectives of market participants with different time horizons, such as short-term FX dealers and long-term central banks.
How It Works
Intrinsic Events Detection : The script identifies two types of events using intrinsic time principles:
Directional Change (DC) : Triggered when the price reverses by the threshold (delta) against the current trend (e.g., a drop by delta in an uptrend signals a "Down DC").
Overshoot (OS) : Occurs when the price continues in the trend direction by the threshold (e.g., a rise by delta in an uptrend signals an "Up OS").
DC events are plotted as solid lines, and OS events as dashed lines, with labels like "Up DC" or "OS Down" for clarity. The label style adjusts based on the trend to ensure visibility.
Multi-Agent Setup : Each agent operates independently with its own threshold, mimicking market participants with varying time horizons (Section 5). Smaller thresholds detect frequent, short-term events, while larger thresholds capture broader, long-term movements.
Settings
Each agent can be configured with:
Enable Agent : Toggle the agent on or off.
Threshold (%) : The percentage threshold (delta) for detecting DC and OS events (default values: 0.1%, 0.2%, 0.5%, 1%, 2% for agents 1–5).
Up Mode Color : Color for lines and labels in up mode (DC events).
Down Mode Color : Color for lines and labels in down mode (OS events).
Usage Notes
This indicator is designed for the foreign exchange market, leveraging its high liquidity, as noted in the paper (Section 1). Adjust the threshold values based on the instrument’s volatility—higher volatility leads to more intrinsic events (Section 4). It can be adapted to other markets where event-based analysis applies.
Reference
The methodology is based on:
Fractals and Intrinsic Time - A Challenge to Econometricians by U. A. Müller, M. M. Dacorogna, R. D. Davé, O. V. Pictet, R. B. Olsen, and J. R. Ward (June 28, 1995). Olsen & Associates Preprint.
Up/Down Volume Delta USDT/COIN NachomixCryptoFeatures:
Custom Timeframe Option: The user can select whether to use a custom timeframe for the analysis or stick with the default.
If enabled, the user can choose a custom timeframe.
The script defaults to using a 1-minute chart when no custom timeframe is specified.
Volume Data (Up and Down Volume): The script calculates buy (up) and sell (down) volume using the requestUpAndDownVolume() function for the selected timeframe.
Up Volume: The volume of buying activity.
Down Volume: The volume of selling activity.
Delta: The difference between up and down volume.
Plotting the Volume Data:
Up Volume: Plots the buy volume as green columns.
Down Volume: Plots the sell volume as red columns.
Delta: Displays the delta value (the difference between up and down volume) as a character on the chart, colored green for positive and red for negative values.
Label Positioning:
Users can choose the position of the buy and sell labels (e.g., above or below the bar, at the price level, high, or low of the candle).
There are inputs for adjusting the horizontal offset (how far the labels are placed in bars) and the vertical position for both buy and sell labels.
Label Creation:
Buy Label: Displays the buy volume in USDT at the chosen position.
Sell Label: Displays the sell volume in USDT at the chosen position.
Both labels are created dynamically and are adjusted based on the specified horizontal and vertical offsets.
Volume Data in Table:
A table is created on the chart to display the following information:
Buy Volume: Displays the total buy volume in both USDT and base currency (e.g., BTC).
Sell Volume: Displays the total sell volume in both USDT and base currency.
Total Volume: The difference between the buy and sell volumes in both USDT and the base currency.
Percentage: The percentage of buy and sell volume relative to the total volume.
The table is displayed in the top right corner of the chart.
Error Handling:
If no volume data is available for the selected symbol, an error is triggered to notify the user.
Inputs:
useCustomTimeframeInput: Boolean input to toggle custom timeframes.
lowerTimeframeInput: Timeframe input for custom timeframe selection.
labelBuyPositionOption: Input to select the position of the buy label (e.g., price, high, low, above, or below the bar).
labelSellPositionOption: Input to select the position of the sell label (e.g., price, high, low, above, or below the bar).
buyLabelOffset: Horizontal offset for the buy label (in bars).
sellLabelOffset: Horizontal offset for the sell label (in bars).
Calculation:
Buy and Sell Amount in USDT: The buy and sell volume is multiplied by the current price (close) to calculate the total amount in USDT.
Buy and Sell Amount in Base Currency: The up and down volume is used directly to represent the amount in the base currency (e.g., BTC).
Total Volume: The total volume is the difference between the buy and sell volumes in USDT.
Labels and Table:
The buy and sell labels are dynamically created and positioned based on user input. The labels display the total buy and sell volumes in USDT.
A table in the top right corner displays the volume data, including both the absolute amount and the percentage of each volume type.
Vietnamese VN-Index/VN30/VNI Big Drop TableOverview:
The VNIndex/VN30/VN30F1M 6.5% Downside Drop Indicator is a powerful tool designed to help traders and investors identify significant market drops on the VNIndex/VN30 (or any other asset) based on a specific downside threshold (default = 6.5%). This Pine Script® indicator automatically detects when the price of an asset drops by more than 6.5% within a single day and visually marks those events on the chart.
Key Features:
Specific (Default = 6.5%) Downside Drop Detection: Automatically calculates the daily percentage drop and identifies when the price falls by more than 6.5%.
Table Display: Shows the dates and corresponding percentage drops of all identified instances in a convenient table at the bottom right of the chart.
Markers: Red down-pointing markers are plotted above bars where the price drop exceeds the 6.5% threshold, making it easy to spot critical drop events at a glance.
Easy-to-Read Table: Lists the date and drop percentage, updating dynamically as new drops are detected. This allows for easy tracking of significant downside moves over time.
How to Use:
Install the Script: Add this indicator to your TradingView chart.
Monitor Price Drops: The indicator automatically detects when the price drops by over 6.5% from the previous close and displays a marker on the chart and in the table.
View the Table: The table displays the date and percentage drop of each detected event, making it easy to track past significant moves.
Alerts: Set an alert for 6.5% drops to receive real-time notifications.
Customization Options:
The drop percentage threshold (default = 6.5%) can be adjusted to fit different market conditions or assets.
The table can be resized or styled based on user preferences for better visibility.
Why Use This Indicator?
This indicator is perfect for traders looking to spot large, significant price movements quickly. Large downside drops can signal potential market reversals or trading opportunities, and this tool helps you track such events effortlessly. Whether you're monitoring the VNIndex or any other asset, this indicator provides crucial insights into volatile price action, helping you make more informed decisions.
Open Source License:
This indicator is open source and free to use under the Mozilla Public License 2.0. You are welcome to modify, distribute, and contribute to the project.
Contributions:
Feel free to contribute improvements, fixes, or new features by creating a pull request. Let’s collaborate to make this indicator even better for the community!
Sigma (Standard Deviation)Calculates the standard deviation (sigma) of a stock in percentages. You can edit the length as per your need.
Timed Reversion Markers (Custom Session Alerts)This script plots vertical histogram markers at specific intraday time points defined by the user. It is designed for traders who follow time-based reversion or breakout setups tied to predictable market behavior at key clock times, such as institutional opening moves, midday reversals, or end-of-day volatility.
Unlike traditional price-action indicators, this tool focuses purely on time-based triggers, a technique often used in time cycle analysis, market internals, and volume-timing strategies.
The indicator includes eight fully customizable time inputs, allowing users to mark any intraday minute with precision using a decimal hour format (for example, 9.55 for 9:55 AM). Each input is automatically converted into hour and minute format, and a visual histogram marker is plotted once per day at that exact time.
Example use cases:
Mark institutional session opens (e.g., 9:30, 10:00, 15:30)
Time-based mean reversion or volatility windows
Backtest recurring time-based reactions
Highlight algorithmic spike zones
The vertical plots serve as non-intrusive, high-contrast visual markers for scalping setups, session analysis, and decision-making checkpoints. All markers are displayed at the top of the chart without interfering with price candles.
HM_RTH_UtilsLibrary "HM_RTH_Utils"
getPrevRTHData(session)
Parameters:
session (string)
RTHData
Fields:
open (series float)
high (series float)
low (series float)
close (series float)
highVolume (series float)
lowVolume (series float)
totalVolume (series float)
RK_RAVI [RK_RAVI]this indicator includes
eme20
ema50
tr true range
atr averave true range
datr daily average true range
Statistical OHLC Projections [neo|]█ OVERVIEW
Statistical OHLC Projections is an indicator designed to offer users a customizable deep-dive on measuring historical price levels for any timeframe. The indicator separates price into two distinct levels, "Manipulation" and "Distribution", where the idea is that for higher timeframe candles, e.g. an up-close candle, the distance from the open to the bottom of the wick would constitute the Manipulation, and the rest would be considered the Distribution. By measuring out these levels, we can gain insight on how far the market may move from higher timeframe opens to their manipulations and distributions, and apply this knowledge to our analysis.
IMPORTANT: Since levels are based on the lookback available on your chart, if the levels aren't being displayed this likely means you don't have enough lookback for your selected timeframe. To check this, enable the stat table to see how many values are available for your timeframe, and either reduce the lookback or increase your chart timeframe.
█ CONCEPTS
The core concept revolves around understanding market behavior through the lens of historical candle structure. The indicator dissects OHLC data to provide statistical boundaries of expected price movement.
- Manipulation Levels: These represent the areas typically seen as liquidity grabs or false moves where price extends in one direction before reversing.
- Distribution Levels: These highlight where the bulk of directional movement tends to occur, often following the manipulation move.
The tool aggregates this data across your selected timeframe to inform you of potential levels associated with it.
█ FEATURES
Multiple Display Types: Display statistical data through two sleek styles, areas or lines. Where areas represent the area between two customizable lookback values, and lines represent one average value.
Adjustable Timeframe Selection: Whether you want to see data based on the 1D chart, or the 1W chart, anything is possible. Simply change the timeframe on the dropdown menu and if there is sufficient lookback the indicator will adjust to your requested timeframe.
Customizable Historical Lookback: By default, the indicator will measure the average 60 values of your requested timeframe, however this may be adjusted to be higher or lower based on your preference. If you want to measure recent moves, 10-20 lookback may be better for you, or if you want more data for less volatile instruments, a value of 100 may be better.
Historical Display: Prevent historical levels from being removed by unchecking the "Remove Previous Drawings" option, this will allow you to examine how the levels previously interacted with price.
NY Midnight Anchoring: By checking the "Use NY Midnight" option, you may see the projection anchored to the New York midnight open time, which is often a significant level on indices.
Alerts: You may enable alerts for any of the indicator's provided levels to stay informed, even when off the charts.
█ How to use
To use the indicator, simply apply it to your chart and modify any of your desired inputs.
By default, the indicator will provide levels for the "1D" timeframe, with a desired lookback of 60, on most instruments and plans this can be gotten when you are on the 30 minute timeframe or above.
When price reaches or extends beyond a manipulation level, observe how it reacts and whether it rejects from that level, if it does this may be an indication that the candle for the timeframe you selected may be reversing.
█ SETTINGS AND OPTIONS
Customize the indicator’s behavior, timeframe sources, and visual appearance to fit your analysis style. Each setting has been designed with flexibility in mind, whether you're working on lower or higher timeframes.
Display Mode: Switch between different display styles for levels: - Default: Shows all statistical levels as individual lines.
- Areas: Plots filled zones between two customizable lookbacks to represent the range between them.
This is ideal for visually mapping high-probability zones of price activity.
Timeframe Settings:
- Show First/Second Timeframe: Choose to show one or both timeframe projections simultaneously.
- First Timeframe / Second Timeframe: Define the higher timeframe candle you want to base calculations on (e.g., 1D, 1W).
- Use NY Midnight: When enabled and using the daily timeframe, the levels will be anchored to the New York Midnight Open (00:00 EST), a key institutional timing reference, especially useful for indices and forex.
Calculation Settings:
- Main Lookback Period: The number of historical candles used in the statistical calculations. A lower number focuses on recent price action, while a higher number smooths results across broader history.
- First Lookback / Second Lookback: Used when “Areas” mode is selected to define the range of the shaded zone. For example, an area from 20 to 60 candles creates a band between short- and long-term price behavior averages.
Visual Settings:
- Line Style: Set your preferred visual style: Solid, Dashed, or Dotted.
- Remove Previous Drawings: When enabled, only the most recent projection is shown on the chart. Disable to retain previous levels and visually backtest their reactions over time.
Color Settings:
Customize each level independently to match your chart theme:
- Manipulation High/Low
- Distribution High/Low
- Open Level
- Label Text Color
Premium/Discount Zones:
- Enable Premium/Discount Zones: Overlay price zones above and below equilibrium to visualize potential overbought (premium) and oversold (discount) areas.
- Premium/Discount Colors: Fully customizable zone colors for clarity and emphasis.
Table Settings:
- Show Statistics Table: Adds an on-chart table summarizing key levels from your active timeframe(s).
- Table Cell Color: Set the background color of the table cells for visibility.
- Table Position: Choose from preset chart locations to position the table where it works best for your layout.
Alerts:
Stay on top of price interactions with key levels even when you're away from the charts.
- Manipulation Hits (High)
- Manipulation Hits (Low)
- Distribution Hits (High)
- Distribution Hits (Low)
Weekend BackgroundThis script shows you the weekend days, so you can see who your cryptocoin performs on average on weekend days.
Aggregated BTC VolumeTracks BTC volume since a desired date and time, lets you set a volume goal to be notified upon hitting with an alert.
TrendLibrary "Trend"
calculateSlopeTrend(source, length, thresholdMultiplier)
Parameters:
source (float)
length (int)
thresholdMultiplier (float)
Purpose:
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
Parameters:
`source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
`length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
`thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
Calculation Steps:
Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`:
If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
Return Value:
The function returns an integer representing the determined trend direction:
`1`: Upward trend
`-1`: Downward trend
`0`: Flat trend
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
XRP/USD Advanced Trading StrategyKey Features:
Triple Confirmation System combines:
Moving Average crossover (9-period vs 21-period)
RSI oversold/overbought conditions (14-period)
MACD histogram crossover
Risk Management:
Built-in stop loss/profit taking (modify via strategy settings)
Margin requirements specified (100:1 leverage)
Visual Elements:
Clean price chart overlay
Clear buy/sell arrows with labels
Moving average plots for trend identification
Optimization Tips:
Adjust MA lengths for different timeframes (shorter for day trading)
Modify RSI levels based on market volatility
Combine with Ichimoku Cloud for additional confirmation
Use Bollinger Bands® to filter false breakouts
Backtesting:
Test on multiple timeframes (4h/daily weekly)
Check performance during different market conditions
Optimize parameters using Strategy Tester
This strategy reduces false signals by requiring confirmation from three different technical indicators while maintaining clarity in signal generation. Always validate with fundamental analysis and market news before executing trade
Chonky ATR Levels 2.0Show ATR based high/low projections.
Choose a custom ATR calculation in the indicator's settings.
The default is a 20day RMA based ATR.
----------How projections are calculated----------
To project the ATR High, the ATR value is added to the low of the current candle that matches the ATR's timeframe.
To project the ATR Low, the ATR value is subtracted from the high of the current candle that matches the ATR's timeframe.
Example:
If a 20day RMA ATR is used:
- the ATR High will be the current day's low + the ATR value.
- the ATR Low will be the current day's high - the ATR value.
*However*, if the price action exceeds either ATR projection, the opposite ATR level will be fixed to the extreme of the period.
See the AUDUSD screenshot above for an example.
The ATR Low was exceeded, so the ATR High projection is capped at the high of day.
If the ATR High is exceeded, the ATR Low would be capped at the low of day.
SmallCapToLargecapRatioThis Ratio Shows when to shift your allocation from Small Cap to Large Cap before a potential crash. So that you can protect your wealth.
Ex. When the ratio is around 2 (1.6-1.8) (Shift from SMALL CAP to LARGE CAP )
When the ratio is 1 or below (Shift from LARGE CAP to SMALL CAP )
Metatrader CalculatorThe “ Metatrader Calculator ” indicator calculates the position size, risk, and potential gain of a trade, taking into account the account balance, risk percentage, entry price, stop loss price, and risk/reward ratio. It supports the XAUUSD, XAGUSD, and BTCUSD pairs, automatically calculating the position size (in lots) based on these parameters. The calculation is displayed in a table on the chart, showing the lot size, loss in dollars, and potential gain based on the defined risk.
Saeki Hisoka's Crypto Market SessionsSaeki Hisoka’s Crypto Trading Sessions Indicator Documentation
🚨 Attention Crypto Traders : Timing is everything in the market. 🚨
Crypto markets are active 24/7, but specific regions experience more liquidity and volatility at certain times. Knowing these active periods can be the difference between successful trades and missed opportunities. That's why we developed **Saeki Hisoka’s Crypto Trading Sessions Indicator**—to help you track when the major market sessions are active.
💡 Purpose of This Indicator
The Crypto market never sleeps. However, certain regions like Asia, Europe, and the US have distinct active hours that influence volatility and liquidity. This indicator helps you easily visualize these timeframes so you can align your trading strategy with peak market activity.
🌍 T rading Sessions Covered :
- Asia Session (00:00 - 09:00 UTC) :
- Key Hubs: Tokyo, Hong Kong, Singapore, Shanghai, Seoul
- Asia sets the tone for the day's price action with high liquidity and institutional movements.
- Europe Session (07:00 - 16:00 UTC) :
- Key Hubs: London, Frankfurt, Zurich, Paris, Amsterdam
- Europe drives significant volatility, especially during overlaps with the Asia session.
- US Session (13:00 - 22:00 UTC) :
- Key Hubs: New York, Chicago, Toronto, San Francisco
- The US session is often where the final big moves happen, driven by major institutional players.
🔧 Setup Instructions
This indicator is plug-and-play and easy to use! Once added to your chart, the indicator will automatically highlight the three key trading sessions with corresponding labels:
- Asia : Light blue background with an "Asia" label
- Europe : Light green background with a "Europe" label
- US : Light red background with a "US" label
How to Add :
Follow these simple steps to add the Crypto Trading Sessions Indicator to your TradingView chart:
1. Open TradingView :
- Log into your TradingView account or create one if you haven’t already.
- Open the chart of your choice.
2. Go to the Pine Script Editor :
- At the top of your TradingView chart, click on the **Pine Editor** tab.
3. Copy and Paste the Provided Code :
- Copy the code provided for the **Saeki Hisoka’s Crypto Trading Sessions Indicator**.
- Paste the code into the Pine Script Editor window.
4. Add to Chart :
- After pasting the code, click on **Add to Chart** at the top of the editor.
- The indicator will now be applied to your chart, automatically highlighting the trading sessions for Asia, Europe, and the US with corresponding labels and background colors.
5. Adjust and Customize (Optional) :
- You can customize the appearance of the indicator by modifying the color settings or label positions directly in the script.
- If you wish to modify time settings for the trading sessions, adjust the times in the session definitions within the code.
6. Verify :
- Once the indicator is added, the chart will automatically show the regions with background colors and labels for Asia , Europe , and US trading sessions.
- The sessions will be clearly marked, giving you insight into when liquidity and volatility are expected to be highest.
Important Note:This version of the indicator is currently restricted to timeframes up to 8 hours . Future updates and versions will enable support for all timeframes.
How to Use
* Strategic Entry & Exit Points : With the indicator showing you the exact active times for each session, you can time your entries and exits around periods of high liquidity and volatility.
* Identify Key Breakouts & Volatility Shifts : The Asia session often opens with slower movements, the Europe session may bring consolidation or reversals, and the US session typically results in more volatile moves. Use this information to plan your trades effectively.
* Risk Management : During volatile periods (such as the overlap between the European and US sessions), manage your risk by setting stop losses and take profits before sharp price movements.
Key Takeaways:
- Crypto markets never sleep**, but each region has its most active time periods.
- Timing your trades** around these sessions can give you a competitive edge.
- This indicator helps align your strategy with the market’s natural flow, reducing emotional trading and increasing profitability.
Conclusion: A Strategic Edge for Every Trader
By knowing when the major trading regions are active, you gain a tactical advantage in your trading. This tool isn't just for retail traders—it's how the major institutional players navigate the market.
Stay ahead. Trade smart. Leverage the Saeki Hisoka’s Crypto Trading Sessions Indicator.
-
Disclaimer:
The system is rigged, but we can play the game better.* This indicator is a tool for precision. It’s not just about speculation—it’s about control. Follow Saeki Hisoka for more insights on the markets.
Feel free to share this documentation with your audience. The tool is ready for plug-and-play use, and future updates will ensure more functionality across all timeframes.