Point and Figure (PnF) Bollinger BandsThis is live and non-repainting Point and Figure Chart Bollinger Bands tool. The script has it’s own P&F engine and not using integrated function of Trading View.
Point and Figure method is over 150 years old. It consist of columns that represent filtered price movements. Time is not a factor on P&F chart but as you can see with this script P&F chart created on time chart.
P&F chart provide several advantages, some of them are filtering insignificant price movements and noise, focusing on important price movements and making support/resistance levels much easier to identify.
P&F Bollinger Bands is calculated and shown by using its own P&F engine. Because of Point and Figure Chart Moving averages are already smoothed, better to use smaller moving average periods, 5 or 10 etc. This period can be chosen by prives movements and characteristics. You can see the consolidation areas and with P&F Breakout signals it’s possible to see the direction. Narrowing bands indicate a consolidation and narrowing does not provide a direction clue. You must look for the next P&F signal to establish direction. But beware of the ‘head fake’. This occurs when prices break a band, then suddenly reverse and move the other way (Trap).
An example for Head Fake:
If you are new to Point & Figure Chart then you better get some information about it before using this tool. There are very good web sites and books. Please PM me if you need help about resources.
Options in the Script
Box size is one of the most important part of Point and Figure Charting. Chart price movement sensitivity is determined by the Point and Figure scale. Large box sizes see little movement across a specific price region, small box sizes see greater price movement on P&F chart. There are four different box scaling with this tool: Traditional, Percentage, Dynamic (ATR), or User-Defined
4 different methods for Box size can be used in this tool.
User Defined: The box size is set by user. A larger box size will result in more filtered price movements and fewer reversals. A smaller box size will result in less filtered price movements and more reversals.
ATR: Box size is dynamically calculated by using ATR, default period is 20.
Percentage: uses box sizes that are a fixed percentage of the stock's price. If percentage is 1 and stock’s price is $100 then box size will be $1
Traditional: uses a predefined table of price ranges to determine what the box size should be.
Price Range Box Size
Under 0.25 0.0625
0.25 to 1.00 0.125
1.00 to 5.00 0.25
5.00 to 20.00 0.50
20.00 to 100 1.0
100 to 200 2.0
200 to 500 4.0
500 to 1000 5.0
1000 to 25000 50.0
25000 and up 500.0
Default value is “ATR”, you may use one of these scaling method that suits your trading strategy.
If ATR or Percentage is chosen then there is rounding algorithm according to mintick value of the security. For example if mintick value is 0.001 and box size (ATR/Percentage) is 0.00124 then box size becomes 0.001.
And also while using dynamic box size (ATR or Percentage), box size changes only when closing price changed.
Reversal : It is the number of boxes required to change from a column of Xs to a column of Os or from a column of Os to a column of Xs. Default value is 3 (most used). For example if you choose reversal = 2 then you get the chart similar to Renko chart.
Source: Closing price or High-Low prices can be chosen as data source for P&F charting.
Options P&F Bollimger Bands:
Length: Base Moving Average Length, default value is 5
StdDev: Standart Deviation, default value ise 2. (Standart deviation is calculated by the engine)
MA Source: Moving averages on P&F charts are based on the average price of each column. Bar chart moving averages are based on each close price. Average price means “(ClosePrice + OpenPrice) / 2”. You can choose Close Price or Average Price as source. Default is Average Price.
Buscar en scripts para "摩根标普500指数基金的收益如何"
Point and Figure (PnF) RSIThis is live and non-repainting Point and Figure Chart RSI tool. The script has it’s own P&F engine and not using integrated function of Trading View.
Point and Figure method is over 150 years old. It consist of columns that represent filtered price movements. Time is not a factor on P&F chart but as you can see with this script P&F chart created on time chart.
P&F chart provide several advantages, some of them are filtering insignificant price movements and noise, focusing on important price movements and making support/resistance levels much easier to identify.
P&F RSI is calculated and shown by using its own P&F engine.
If you are new to Point & Figure Chart then you better get some information about it before using this tool. There are very good web sites and books. Please PM me if you need help about resources.
Options in the Script
Box size is one of the most important part of Point and Figure Charting. Chart price movement sensitivity is determined by the Point and Figure scale. Large box sizes see little movement across a specific price region, small box sizes see greater price movement on P&F chart. There are four different box scaling with this tool: Traditional, Percentage, Dynamic (ATR), or User-Defined
4 different methods for Box size can be used in this tool.
User Defined: The box size is set by user. A larger box size will result in more filtered price movements and fewer reversals. A smaller box size will result in less filtered price movements and more reversals.
ATR: Box size is dynamically calculated by using ATR, default period is 20.
Percentage: uses box sizes that are a fixed percentage of the stock's price. If percentage is 1 and stock’s price is $100 then box size will be $1
Traditional: uses a predefined table of price ranges to determine what the box size should be.
Price Range Box Size
Under 0.25 0.0625
0.25 to 1.00 0.125
1.00 to 5.00 0.25
5.00 to 20.00 0.50
20.00 to 100 1.0
100 to 200 2.0
200 to 500 4.0
500 to 1000 5.0
1000 to 25000 50.0
25000 and up 500.0
Default value is “ATR”, you may use one of these scaling method that suits your trading strategy.
If ATR or Percentage is chosen then there is rounding algorithm according to mintick value of the security. For example if mintick value is 0.001 and box size (ATR/Percentage) is 0.00124 then box size becomes 0.001.
And also while using dynamic box size (ATR or Percentage), box size changes only when closing price changed.
Reversal : It is the number of boxes required to change from a column of Xs to a column of Os or from a column of Os to a column of Xs. Default value is 3 (most used). For example if you choose reversal = 2 then you get the chart similar to Renko chart.
Source: Closing price or High-Low prices can be chosen as data source for P&F charting.
you can use PNF type RSI or RENKO type RSI.
What is the difference between them?
While calculating PNF type RSI, the script checks last X/O column's closing price but when using RENKO type RSI the scipt calculates RSI on every price changes according to number of boxes. and also with RENKO type RSI, calculation is made for each boxes on price changes.
Important note if you use this PNF script with reversal = 2 then you get RENKO chart. So, with this RENKO chart better to use RENKO type RSI ;)
Point and Figure (PnF) ChartThis is live and non-repainting Point and Figure Charting tool. The tool has it’s own P&F engine and not using integrated function of Trading View.
Point and Figure method is over 150 years old. It consist of columns that represent filtered price movements. Time is not a factor on P&F chart but as you can see with this script P&F chart created on time chart.
P&F chart provide several advantages, some of them are filtering insignificant price movements and noise, focusing on important price movements and making support/resistance levels much easier to identify.
If you are new to Point & Figure Chart then you better get some information about it before using this tool. There are very good web sites and books. Please PM me if you need help about resources.
Options in the Script
Box size is one of the most important part of Point and Figure Charting. Chart price movement sensitivity is determined by the Point and Figure scale. Large box sizes see little movement across a specific price region, small box sizes see greater price movement on P&F chart. There are four different box scaling with this tool: Traditional, Percentage, Dynamic (ATR), or User-Defined
4 different methods for Box size can be used in this tool.
User Defined: The box size is set by user. A larger box size will result in more filtered price movements and fewer reversals. A smaller box size will result in less filtered price movements and more reversals.
ATR: Box size is dynamically calculated by using ATR, default period is 20.
Percentage: uses box sizes that are a fixed percentage of the stock's price. If percentage is 1 and stock’s price is $100 then box size will be $1
Traditional: uses a predefined table of price ranges to determine what the box size should be.
Price Range Box Size
Under 0.25 0.0625
0.25 to 1.00 0.125
1.00 to 5.00 0.25
5.00 to 20.00 0.50
20.00 to 100 1.0
100 to 200 2.0
200 to 500 4.0
500 to 1000 5.0
1000 to 25000 50.0
25000 and up 500.0
Default value is “ATR”, you may use one of these scaling method that suits your trading strategy.
If ATR or Percentage is chosen then there is rounding algorithm according to mintick value of the security. For example if mintick value is 0.001 and box size (ATR/Percentage) is 0.00124 then box size becomes 0.001.
And also while using dynamic box size (ATR or Percentage), box size changes only when closing price changed.
Reversal : It is the number of boxes required to change from a column of Xs to a column of Os or from a column of Os to a column of Xs. Default value is 3 (most used). For example if you choose reversal = 2 then you get the chart similar to Renko chart.
Source: Closing price or High-Low prices can be chosen as data source for P&F charting.
Chart Style: There are 3 options for chart style: “Candle”, “Area” or “Don’t show”.
As Area:
As Candle:
X/O Column Style: it can show all columns from opening price or only last Xs/Os.
Color Theme: different themes exist => Green/Red, Yellow/Blue, White/Yellow, Orange/Blue, Lime/Red, Blue/Red
Show Breakouts is the option to show Breakouts
This tool detects & shows following Breakouts:
Triple Top/Bottom,
Triple Top Ascending,
Triple Bottom Descending,
Simple Buy/Sell (Double Top/Bottom),
Simple Buy With Rising Bottom,
Simple Sell With Declining Top
Catapult bullish/bearish
Show Horizontal Count Targets: Finds the congestion or consolidation pattern and if there is breakout then it calculates the Target by using Horizontal Count method (based on the width of congestion pattern). It shows how many column exist on congestion area. There is no guarantee that prices will reach the target.
Show Vertical Count Targets: When Triple Top/Bottom Breakouts occured the script calculates the target by using Vertical Count Method (based on the length of the column). There is no guarantee that prices will reach the target.
For both methods there is auto target cancellation if price goes below congestion bottom or above congestion top.
trend is calculated by EMA of closing price of the P&F
Whipsaw protection:
Last options are “Show info panel” and Labeling Offset. Script shows current box size, reversal, and recommanded minimum and maximum box size. And also it shows the price level to reverse the column (Xs <-> Os) and the price level to add at least 1 more box to column. This is the option to put these labels 10, 20, 30, 50 or 100 bars away from the last bar. Labeling content and color change according to X/O column.
do not hesitate to comment.
Candlesticks ANN for Stock Markets TF : 1WHello, this script consists of training candlesticks with Artificial Neural Networks (ANN).
In addition to the first series, candlesticks' bodies and wicks were also introduced as training inputs.
The inputs are individually trained to find the relationship between the subsequent historical value of all candlestick values 1.(High,Low,Close,Open)
The outputs are adapted to the current values with a simple forecast code.
Once the OHLC value is found, the exponential moving averages of 5 and 20 periods are used.
Reminder : OHLC = (Open + High + Close + Low ) / 4
First version :
Script is designed for S&P 500 Indices,Funds,ETFs, especially S&P 500 Stocks,and for all liquid Stocks all around the World.
NOTE: This script is only suitable for 1W time-frame for Stocks.
The average training error rates are less than 5 per thousand for each candlestick variable. (Average Error < 0.005 )
I've just finished it and haven't tested it in detail.
So let's use it carefully as a supporter.
Best regards !
TNZ - Index above MA Use this indicator to filter stock selection based on the relevant index value being above the selected simple moving average.
For example, only buying the S+P 500 stock if the S+P 500 index value is above the 10 period moving average.
The time frame used is that displayed
Macroeconomic Artificial Neural Networks
This script was created by training 20 selected macroeconomic data to construct artificial neural networks on the S&P 500 index.
No technical analysis data were used.
The average error rate is 0.01.
In this respect, there is a strong relationship between the index and macroeconomic data.
Although it affects the whole world,I personally recommend using it under the following conditions: S&P 500 and related ETFs in 1W time-frame (TF = 1W SPX500USD, SP1!, SPY, SPX etc. )
Macroeconomic Parameters
Effective Federal Funds Rate (FEDFUNDS)
Initial Claims (ICSA)
Civilian Unemployment Rate (UNRATE)
10 Year Treasury Constant Maturity Rate (DGS10)
Gross Domestic Product , 1 Decimal (GDP)
Trade Weighted US Dollar Index : Major Currencies (DTWEXM)
Consumer Price Index For All Urban Consumers (CPIAUCSL)
M1 Money Stock (M1)
M2 Money Stock (M2)
2 - Year Treasury Constant Maturity Rate (DGS2)
30 Year Treasury Constant Maturity Rate (DGS30)
Industrial Production Index (INDPRO)
5-Year Treasury Constant Maturity Rate (FRED : DGS5)
Light Weight Vehicle Sales: Autos and Light Trucks (ALTSALES)
Civilian Employment Population Ratio (EMRATIO)
Capacity Utilization (TOTAL INDUSTRY) (TCU)
Average (Mean) Duration Of Unemployment (UEMPMEAN)
Manufacturing Employment Index (MAN_EMPL)
Manufacturers' New Orders (NEWORDER)
ISM Manufacturing Index (MAN : PMI)
Artificial Neural Network (ANN) Training Details :
Learning cycles: 16231
AutoSave cycles: 100
Grid
Input columns: 19
Output columns: 1
Excluded columns: 0
Training example rows: 998
Validating example rows: 0
Querying example rows: 0
Excluded example rows: 0
Duplicated example rows: 0
Network
Input nodes connected: 19
Hidden layer 1 nodes: 2
Hidden layer 2 nodes: 0
Hidden layer 3 nodes: 0
Output nodes: 1
Controls
Learning rate: 0.1000
Momentum: 0.8000 (Optimized)
Target error: 0.0100
Training error: 0.010000
NOTE : Alerts added . The red histogram represents the bear market and the green histogram represents the bull market.
Bars subject to region changes are shown as background colors. (Teal = Bull , Maroon = Bear Market )
I hope it will be useful in your studies and analysis, regards.
Damped Sine Wave Weighted FilterIntroduction
Remember that we can make filters by using convolution, that is summing the product between the input and the filter coefficients, the set of filter coefficients is sometime denoted "kernel", those coefficients can be a same value (simple moving average), a linear function (linearly weighted moving average), a gaussian function (gaussian filter), a polynomial function (lsma of degree p with p = order of the polynomial), you can make many types of kernels, note however that it is easy to fall into the redundancy trap.
Today a low-lag filter who weight the price with a damped sine wave is proposed, the filter characteristics are discussed below.
A Damped Sine Wave
A damped sine wave is a like a sine wave with the difference that the sine wave peak amplitude decay over time.
A damped sine wave
Used Kernel
We use a damped sine wave of period length as kernel.
The coefficients underweight older values which allow the filter to reduce lag.
Step Response
Because the filter has overshoot in the step response we can conclude that there are frequencies amplified in the passband, we could have reached to this conclusion by simply seeing the negative values in the kernel or the "zero-lag" effect on the closing price.
Enough ! We Want To See The Filter !
I should indeed stop bothering you with transient responses but its always good to see how the filter act on simpler signals before seeing it on the closing price. The filter has low-lag and can be used as input for other indicators
Filter with length = 100 as input for the rsi.
The bands trailing stop utility using rolling squared mean average error with length 500 using the filter of length 500 as input.
Approximating A Least Squares Moving Average
A least squares moving average has a linear kernel with certain values under 0, a lsma of length k can be approximated using the proposed filter using period p where p = k + k/4 .
Proposed filter (red) with length = 250 and lsma (blue) with length = 200.
Conclusions
The use of damping in filter design can provide extremely useful filters, in fact the ideal kernel, the sinc function, is also a damped sine wave.
VIX reversion-Buschi
English:
A significant intraday reversion (commonly used: 3 points) on a high (over 20 points) S&P 500 Volatility Index (VIX) can be a sign of a market bottom, because there is the assumption that some of the "big guys" liquidated their options / insurances because the worst is over.
This indicator shows these reversions (3 points as default) when the VIX was over 20 points. The character "R" is then shown directly over the daily column, the VIX need not to be loaded explicitly.
Deutsch:
Eine deutliche Intraday-Umkehr (3 Punkte im Normalfall) bei einem hohen (über 20 Punkte) S&P 500 Volatility Index (VIX) kann ein Zeichen für eine Bodenbildung im Markt sein, weil möglicherweise einige "große Jungs" ihre Optionen / Versicherungen auflösen, weil das schlimmste vorbei ist.
Dieser Indikator zeigt diese Umkehr (Standardwert: 3 Punkte), wenn der VIX vorher über 20 Punkte lag. Der Buchstabe "R" wird dabei direkt über dem Tagesbalken angezeigt, wobei der VIX nicht explizit geladen werden muss.
Relative Price StrengthThe strength of a stock relative to the S&P 500 is key part of most traders decision making process. Hence the default reference security is SPY, the most commonly trades S&P 500 ETF.
Most profitable traders buy stocks that are showing persistence intermediate strength verses the S&P as this has been shown to work. Hence the default period is 63 days or 3 months.
TICK Extremes IndicatorSimple TICK indicator, plots candles and HL2 line
Conditional green/red coloring for highs above 500, 900 and lows above 0, and for lows below -500, -900, and highs above 0
Probably best used for 1 - 5 min timeframes
Always open to suggestions if criteria needs tweaking or if something else would make it more useful or user-friendly!
Market direction and pullback based on S&P 500.A simple indicator based on www.swing-trade-stocks.com The link is also the guide for how to use it.
0 - nothing. If the indicator is showing 0 for a prolonged amount of time, it is likely the market is in "momentum mode" (referred to in the link above).
1 - indicates an uptrend based on SMA and EMA and also a place where a reversal to the upside is likely to occur. You should look only for long trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
-1 - indicates a downtrend based on SMA and EMA and also a place where a reversal to the downside is likely to occur. You should look only for short trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
Net XRP Margin PositionTotal XRP Longs minus XRP Shorts in order to give you the total outstanding XRP margin debt.
ie: If 500,000 XRP has been longed, and 400,000 XRP has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 XRP (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
Net DASH Margin PositionTotal DASH Longs minus DASH Shorts in order to give you the total outstanding DASH margin debt.
ie: If 500,000 DASH has been longed, and 400,000 DASH has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 DASH (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
(Anyone know what category this script should be in?)
Net NEO Margin PositionTotal NEO Longs minus NEO Shorts in order to give you the total outstanding NEO margin debt.
ie: If 500,000 NEO has been longed, and 400,000 NEO has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 NEO (net) remaining to be sold to give us an overall neutral margin position.
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances.
(Anyone know what category this script should be in?)
Everyday 0002 _ MAC 1st Trading Hour WalkoverThis is the second strategy for my Everyday project.
Like I wrote the last time - my goal is to create a new strategy everyday
for the rest of 2016 and post it here on TradingView.
I'm a complete beginner so this is my way of learning about coding strategies.
I'll give myself between 15 minutes and 2 hours to complete each creation.
This is basically a repetition of the first strategy I wrote - a Moving Average Crossover,
but I added a tiny thing.
I read that "Statistics have proven that the daily high or low is established within the first hour of trading on more than 70% of the time."
(source: )
My first Moving Average Crossover strategy, tested on VOLVB daily, got stoped out by the volatility
and because of this missed one nice bull run and a very nice bear run.
So I added this single line: if time("60", "1000-1600") regarding when to take exits:
if time("60", "1000-1600")
strategy.exit("Close Long", "Long", profit=2000, loss=500)
strategy.exit("Close Short", "Short", profit=2000, loss=500)
Sweden is UTC+2 so I guess UTC 1000 equals 12.00 in Stockholm. Not sure if this is correct, actually.
Anyway, I hope this means the strategy will only take exits based on price action which occur in the afternoon, when there is a higher probability of a lower volatility.
When I ran the new modified strategy on the same VOLVB daily it didn't get stoped out so easily.
On the other hand I'll have to test this on various stocks .
Reading and learning about how to properly test strategies is on my todo list - all tips on youtube videos or blogs
to read on this topic is very welcome!
Like I said the last time, I'm posting these strategies hoping to learn from the community - so any feedback, advice, or corrections is very much welcome and appreciated!
/pbergden
Ben's BTC Macro Fair Value OscillatorBen's BTC Macro Fair Value Oscillator
Overview
The **BTC Macro Fair Value Oscillator** is a non-crypto fair value framework that uses macro asset relationships (equities, dollar, gold) to estimate Bitcoin's "macro-driven fair value" and identify mean-reversion opportunities.
"Is BTC cheap or expensive right now?" on the 4 Hour Timeframe ONLY
### Key Features
✅ **Macro-driven**: Uses QQQ, DXY, XAUUSD instead of on-chain or crypto metrics
✅ **Dynamic weighting**: Assets weighted by rolling correlation strength
✅ **Mean-reversion signals**: Identifies when BTC is cheap/expensive vs macro
✅ **Validated parameters**: Optimized through 5-year backtest (Sharpe 6.7-9.9)
✅ **Visual transparency**: Live correlation panel, fair value bands, statistics
✅ **Non-repainting**: All calculations use confirmed historical data only
### What This Indicator Does
- Builds a **synthetic macro composite** from traditional assets
- Runs a **rolling regression** to predict BTC price from macro
- Calculates **deviation z-score** (how far BTC is from macro fair value)
- Generates **entry signals** when BTC is extremely cheap vs macro (dev < -2)
- Generates **exit signals** when BTC returns to fair value (dev > 0)
### What This Indicator Is NOT
❌ Not a high-frequency trading system (sparse signals by design)
❌ Not optimized for absolute returns (optimized for Sharpe ratio)
❌ Not suitable as standalone trading system (best as overlay/confirmation)
❌ Not predictive of short-term price movements (mean-reversion timeframe: days to weeks)
---
## Core Concept
### The Premise
Bitcoin doesn't trade in a vacuum. It's influenced by:
- **Risk appetite** (equities: QQQ, SPX)
- **Dollar strength** (DXY - inverse to risk assets)
- **Safe haven flows** (Gold: XAUUSD)
When macro conditions are "good for BTC" (risk-on, weak dollar, strong equities), BTC should trade higher. When macro conditions turn against it, BTC should trade lower.
### The Innovation
Instead of looking at BTC in isolation, this indicator:
1. **Measures how strongly** BTC currently correlates with each macro asset
2. **Builds a weighted composite** of those macro returns (the "D" driver)
3. **Regresses BTC price on D** to estimate "macro fair value"
4. **Tracks the deviation** between actual price and fair value
5. **Signals mean reversion** when deviation becomes extreme
### The Edge
The validated edge comes from:
- **Extreme deviations predict future returns** (dev < -2 → +1.67% over 12 bars)
- **Monotonic relationship** (more negative dev → higher forward returns)
- **Works out-of-sample** (test Sharpe +83-87% better than training)
- **Low correlation with buy & hold** (provides diversification value)
---
## Methodology
### Step 1: Macro Composite Driver D(t)
The indicator builds a weighted composite of macro asset returns:
**Process:**
1. Calculate **log returns** for BTC and each macro reference (QQQ, DXY, XAUUSD)
2. Compute **rolling correlation** between BTC and each reference over `corrLen` bars
3. **Weight each asset** by `|correlation|` if above `minCorrAbs` threshold, else 0
4. **Sign-adjust** weights (+1 for positive corr, -1 for negative) to handle inverse relationships
5. **Z-score normalize** each reference's returns over `fvWindow`
6. **Composite D(t)** = weighted sum of sign-adjusted z-scores
**Formula:**
```
For each reference i:
corr_i = correlation(BTC_returns, ref_i_returns, corrLen)
weight_i = |corr_i| if |corr_i| >= minCorrAbs else 0
sign_i = +1 if corr_i >= 0 else -1
z_i = (ref_i_returns - mean) / std
contrib_i = sign_i * z_i * weight_i
D(t) = sum(contrib_i) / sum(weight_i)
```
**Key Insight:** D(t) represents "how good macro conditions are for BTC right now" in a normalized, correlation-weighted way.
---
### Step 2: Fair Value Regression
Uses rolling linear regression to predict BTC price from D(t):
**Model:**
```
BTC_price(t) = α + β * D(t)
```
**Calculation (Pine Script approach):**
```
corr_CD = correlation(BTC_price, D, fvWindow)
sd_price = stdev(BTC_price, fvWindow)
sd_D = stdev(D, fvWindow)
cov = corr_CD * sd_price * sd_D
var_D = variance(D, fvWindow)
β = cov / var_D
α = mean(BTC_price) - β * mean(D)
fair_value(t) = α + β * D(t)
```
**Result:** A time-varying "macro fair value" line that adapts as correlations change.
---
### Step 3: Deviation Oscillator
Measures how far BTC price has deviated from fair value:
**Calculation:**
```
residual(t) = BTC_price(t) - fair_value(t)
residual_std = stdev(residual, normWindow)
deviation(t) = residual(t) / residual_std
```
**Interpretation:**
- `dev = 0` → BTC at fair value
- `dev = -2` → BTC is 2 standard deviations **cheap** vs macro
- `dev = +2` → BTC is 2 standard deviations **rich** vs macro
---
### Step 4: Signal Generation
**Long Entry:** `dev` crosses below `-2.0` (BTC extremely cheap vs macro)
**Long Exit:** `dev` crosses above `0.0` (BTC returns to fair value)
**No shorting** in default config (risk management choice - crypto volatility)
---
## How It Works
### Visual Components
#### 1. Price Chart (Main Panel)
**Fair Value Line (Orange):**
- The estimated "macro-driven fair value" for BTC
- Calculated from rolling regression on macro composite
**Fair Value Bands:**
- **±1σ** (light): 68% confidence zone
- **±2σ** (medium): 95% confidence zone
- **±3σ** (dark, dots): 99.7% confidence zone
**Entry/Exit Markers:**
- **Green "LONG" label** below bar: Entry signal (dev < -2)
- **Red "EXIT" label** above bar: Exit signal (dev > 0)
#### 2. Deviation Oscillator (Separate Pane)
**Line plot:**
- Shows current deviation z-score
- **Green** when dev < -2 (cheap)
- **Red** when dev > +2 (rich)
- **Gray** when neutral
**Histogram:**
- Visual representation of deviation magnitude
- Green bars = negative deviation (cheap)
- Red bars = positive deviation (rich)
**Threshold lines:**
- **Green dashed at -2.0**: Entry threshold
- **Red dashed at 0.0**: Exit threshold
- **Gray solid at 0**: Fair value line
#### 3. Correlation Panel (Top-Right)
Shows live correlation and weighting for each macro asset:
| Asset | Corr | Weight |
|-------|------|--------|
| QQQ | +0.45 | 0.45 |
| DXY | -0.32 | 0.32 |
| XAUUSD | +0.15 | 0.00 |
| Avg \|Corr\| | 0.31 | 0.77 |
**Reading:**
- **Corr**: Current rolling correlation with BTC (-1 to +1)
- **Weight**: How much this asset contributes to fair value (0 = excluded)
- **Avg |Corr|**: Average correlation strength (should be > 0.2 for reliable signals)
**Colors:**
- Green/Red corr = positive/negative correlation
- White weight = asset included, Gray = excluded (below minCorrAbs)
#### 4. Statistics Label (Bottom-Right)
```
━━━ BTC Macro FV ━━━
Dev: -2.34
Price: $103,192
FV: $110,500
Status: CHEAP ⬇
β: 103.52
```
**Fields:**
- **Dev**: Current deviation z-score
- **Price**: Current BTC close price
- **FV**: Current macro fair value estimate
- **Status**: CHEAP (< -2), RICH (> +2), or FAIR
- **β**: Current regression beta (sensitivity to macro)
---
## Installation & Setup
### TradingView Setup
1. Open TradingView and navigate to any **BTC chart** (BTCUSD, BTCUSDT, etc.)
2. Open **Pine Editor** (bottom panel)
3. Click **"+ New"** → **"Blank indicator"**
4. **Delete** all default code
5. **Copy** the entire Pine Script from `GHPT_optimized.pine`
6. **Paste** into the editor
7. Click **"Save"** and name it "BTC Macro Fair Value Oscillator"
8. Click **"Add to Chart"**
### Recommended Chart Settings
**Timeframe:** 4h (validated timeframe)
**Chart Type:** Candlestick or Heikin Ashi
**Overlay:** Yes (indicator plots on price chart + separate pane)
**Alternative Timeframes:**
- Daily: Works but slower signals
- 1h-2h: May work but not validated
- < 1h: Not recommended (too noisy)
### Symbol Requirements
**Primary:** BTC/USD or BTC/USDT on any exchange
**Macro References:** Automatically fetched
- QQQ (Nasdaq 100 ETF)
- DXY (US Dollar Index)
- XAUUSD (Gold spot)
**Data Requirements:**
- At least **90 bars** of history (warmup period)
- Premium TradingView recommended for full historical data
---
## Reading the Indicator
### Identifying Signals
#### Strong Long Signal (High Conviction)
- ✅ Deviation < -2.0 (extreme undervaluation)
- ✅ Avg |Corr| > 0.3 (strong macro relationships)
- ✅ Price touching or below -2σ band
- ✅ "LONG" label appears below bar
**Interpretation:** BTC is extremely cheap relative to macro conditions. Historical data shows +1.67% average return over next 12 bars (48 hours at 4h timeframe).
#### Moderate Long Signal (Lower Conviction)
- ⚠️ Deviation between -1.5 and -2.0
- ⚠️ Avg |Corr| between 0.2-0.3
- ⚠️ Price approaching -2σ band
**Interpretation:** BTC is cheap but not extreme. Consider as confirmation for other signals.
#### Exit Signal
- 🔴 Deviation crosses above 0 (returns to fair value)
- 🔴 "EXIT" label appears above bar
**Interpretation:** Mean reversion complete. Close long positions.
#### Strong Short/Avoid Signal
- 🔴 Deviation > +2.0 (extreme overvaluation)
- 🔴 Avg |Corr| > 0.3
- 🔴 Price touching or above +2σ band
**Interpretation:** BTC is expensive vs macro. Historical data shows -1.79% average return over next 12 bars. Consider exiting longs or reducing exposure.
### Regime Detection
**Strong Regime (Reliable Signals):**
- Avg |Corr| > 0.3
- Multiple assets weighted > 0
- Fair value line tracking price reasonably well
**Weak Regime (Unreliable Signals):**
- Avg |Corr| < 0.2
- Most weights = 0 (grayed out)
- Fair value line diverging wildly from price
- **Action:** Ignore signals until correlations strengthen
ROC & Momentum FusionROC & Momentum Fusion
(by HabibiTrades ©)
Purpose:
“ROC & Momentum Fusion” combines the Rate of Change (ROC) with a MACD-style signal engine to identify early momentum reversals, confirmed trend shifts, and low-volatility choppy zones.
It’s built for traders who want early momentum detection with the clarity of trend persistence — adaptable to any instrument and timeframe.
⚙️ How It Works
Rate of Change (ROC):
Measures the percentage speed of price change over time, showing the raw momentum strength.
Signal Line (EMA):
A short EMA of the ROC — responds faster to new directional shifts, similar to a MACD signal line.
Histogram:
Displays acceleration and deceleration between the ROC and its signal line.
Persistent Trend States:
When the ROC crosses the signal line or zero, the indicator enters a new momentum regime
(bullish or bearish) and stays in that color until another flip occurs.
Dynamic Choppy Zone:
When ROC momentum fades within the zero buffer zone, the indicator turns orange, signaling a sideways or indecisive market.
🟢 Visual Regimes
Regime Description Color
Bullish Momentum ROC above zero or signal line 🟢 Neon Green
Bearish Momentum ROC below zero or signal line 🔴 Neon Red
Choppy / Neutral ROC hovering within ±threshold range 🟠 Neon Orange
This color system makes it visually effortless to see whether the market is trending, reversing, or consolidating.
🧭 Adaptive Intelligence
The script automatically adjusts to market type and session for consistent accuracy:
Session Adaptive: Adjusts smoothing based on global sessions (Asian, London, New York, Sydney).
Instrument Adaptive: Fine-tunes sensitivity automatically for major assets — NASDAQ (NQ), S&P 500 (ES), Gold (GC), Oil (CL), Bitcoin (BTC).
Volatility Normalization: Optionally divides ROC by its own standard deviation to stabilize noisy assets and maintain consistent scaling.
🔔 Signals & Alerts
Bullish Reversal:
ROC crosses above its signal or zero line — early momentum flip.
Bearish Reversal:
ROC crosses below its signal or zero line — downward momentum flip.
Alerts:
Both reversal conditions include built-in alert triggers for automation and notifications.
🎨 Visual Features
Main ROC Line: Adaptive EMA of ROC, color-coded by trend regime.
Signal Line: Optional white EMA overlay for MACD-style crossovers.
Histogram: Visual burst display of acceleration (green/red).
Reversal Markers: Optional triangles marking exact crossover points.
Threshold Lines: Highlight the zero and buffer zones for visual clarity.
🧩 Best Use Cases
Identify early momentum shifts before price confirms them.
Confirm trend continuation or exhaustion with color persistence.
Detect choppy / low-volatility periods instantly.
Works across all timeframes — from 1-minute scalping to weekly swings.
Combine with structure, EMAs, or volume for confirmation.
⚙️ Recommended Settings
Setting Default Description
ROC Period 6 Core momentum length (lower = faster response).
Signal EMA Length 3 MACD-style responsiveness (lower = more reactive).
Zero Buffer Threshold 0.15 Defines the width of the neutral zone around zero.
Choppy Zone Multiplier 1.0 Expands or tightens the orange zone sensitivity.
These defaults have been optimized through real-market testing to balance responsiveness and smoothness across different asset classes.
⚠️ Notes
The color regime is persistent, meaning once the line turns bullish or bearish, it remains in that state until momentum structurally flips.
The orange zone represents momentum uncertainty and helps avoid false entries in range-bound markets.
Works seamlessly on any timeframe and with any asset.
davidqqq//@version=5
indicator('CD', overlay=false, max_bars_back=500)
// 输入参数
S = input(12, title='Short EMA Period')
P = input(26, title='Long EMA Period')
M = input(9, title='Signal Line Period')
// 计算DIFF, DEA和MACD值
fastEMA = ta.ema(close, S)
slowEMA = ta.ema(close, P)
DIFF = fastEMA - slowEMA
DEA = ta.ema(DIFF, M)
MACD = (DIFF - DEA) * 2
// 计算N1和MM1
N1 = ta.barssince(ta.crossunder(MACD, 0))
MM1 = ta.barssince(ta.crossover(MACD, 0))
// 确保长度参数大于0
N1_safe = na(N1) ? 1 : math.max(N1 + 1, 1)
MM1_safe = na(MM1) ? 1 : math.max(MM1 + 1, 1)
// 计算CC和DIFL系列值
CC1 = ta.lowest(close, N1_safe)
CC2 = nz(CC1 , CC1)
CC3 = nz(CC2 , CC2)
DIFL1 = ta.lowest(DIFF, N1_safe)
DIFL2 = nz(DIFL1 , DIFL1)
DIFL3 = nz(DIFL2 , DIFL2)
// 计算CH和DIFH系列值
CH1 = ta.highest(close, MM1_safe)
CH2 = nz(CH1 , CH1)
CH3 = nz(CH2 , CH2)
DIFH1 = ta.highest(DIFF, MM1_safe)
DIFH2 = nz(DIFH1 , DIFH1)
DIFH3 = nz(DIFH2 , DIFH2)
// 判断买入条件
AAA = CC1 < CC2 and DIFL1 > DIFL2 and MACD < 0 and DIFF < 0
BBB = CC1 < CC3 and DIFL1 < DIFL2 and DIFL1 > DIFL3 and MACD < 0 and DIFF < 0
CCC = (AAA or BBB) and DIFF < 0
LLL = not CCC and CCC
XXX = AAA and DIFL1 <= DIFL2 and DIFF < DEA or BBB and DIFL1 <= DIFL3 and DIFF < DEA
JJJ = CCC and math.abs(DIFF ) >= math.abs(DIFF) * 1.01
BLBL = JJJ and CCC and math.abs(DIFF ) * 1.01 <= math.abs(DIFF)
DXDX = not JJJ and JJJ
DJGXX = (close < CC2 or close < CC1) and (JJJ or JJJ ) and not LLL and math.sum(JJJ ? 1 : 0, 24) >= 1
DJXX = not(math.sum(DJGXX ? 1 : 0, 2) >= 1) and DJGXX
DXX = (XXX or DJXX) and not CCC
// 判断卖出条件
ZJDBL = CH1 > CH2 and DIFH1 < DIFH2 and MACD > 0 and DIFF > 0
GXDBL = CH1 > CH3 and DIFH1 > DIFH2 and DIFH1 < DIFH3 and MACD > 0 and DIFF > 0
DBBL = (ZJDBL or GXDBL) and DIFF > 0
DBL = not DBBL and DBBL and DIFF > DEA
DBLXS = ZJDBL and DIFH1 >= DIFH2 and DIFF > DEA or GXDBL and DIFH1 >= DIFH3 and DIFF > DEA
DBJG = DBBL and DIFF >= DIFF * 1.01
DBJGXC = not DBJG and DBJG
DBJGBL = DBJG and DBBL and DIFF * 1.01 <= DIFF
ZZZZZ = (close > CH2 or close > CH1) and (DBJG or DBJG ) and not DBL and math.sum(DBJG ? 1 : 0, 23) >= 1
YYYYY = not(math.sum(ZZZZZ ? 1 : 0, 2) >= 1) and ZZZZZ
WWWWW = (DBLXS or YYYYY) and not DBBL
// plot买入和卖出信号
if DXDX
label.new(bar_index, low, text='抄底', style=label.style_label_up, color=color.red, textcolor=color.white, size=size.small)
if DBJGXC
label.new(bar_index, high, text='卖出', style=label.style_label_down, color=color.green, textcolor=color.white, size=size.small)
Hindenburg OmenThe Hindenburg Omen highlights periods of internal market stress — when both new 52-week highs and new lows expand while the NYSE remains in an uptrend.
This condition often precedes major corrections or volatility spikes by revealing divergence beneath the surface of an advancing market.
The indicator triggers when four classic breadth rules align: elevated highs and lows, a positive trend, a negative McClellan Oscillator, and a highs-to-lows ratio under 2:1.
Use it on broad indices (NYSE, S&P 500) as an early-warning context tool, NOT a standalone sell signal.
Henry's MA & RSProviding 10 21 50 200 MA and RS rating based on S&P 500, basically for US stocks. Enjoy!
Market Structure Trailing Stop MTF [Inspired by LuxAlgo]# Market Structure Trailing Stop MTF
**OPEN-SOURCE SCRIPT**
*208k+ views on original · Modified for MTF Support*
This indicator is a direct adaptation of the renowned **Market Structure Trailing Stop** by **LuxAlgo** (original script: [Market Structure Trailing Stop ]()). The core logic remains untouched, providing dynamic trailing stops based on market structure breaks (CHoCH/BOS). The **only modification** is the addition of **Multi-Timeframe (MTF) support**, allowing users to apply the trailing stops and structures from **higher timeframes (HTF)** directly on their current chart. This enhances usability for traders analyzing cross-timeframe confluence without switching charts.
**Special thanks to LuxAlgo** for releasing this powerful open-source tool under CC BY-NC-SA 4.0. Your contributions to the TradingView community have inspired countless traders—grateful for the solid foundation!
## 🔶 How the Script Works: A Deep Dive
At its heart, this indicator detects **market structure shifts** (bullish or bearish breaks of swing highs/lows) and uses them to generate **adaptive trailing stops**. These stops trail the price while protecting profits and acting as dynamic support/resistance levels. The MTF enhancement pulls this logic from user-specified higher timeframes, overlaying HTF structures and stops on the lower timeframe chart for seamless multi-timeframe analysis.
### Core Logic (Unchanged from LuxAlgo's Original)
1. **Pivot Detection**:
- Uses `ta.pivothigh()` and `ta.pivotlow()` with a user-defined lookback (`length`) to identify swing highs (PH) and lows (PL).
- Coordinates (price `y` and bar index/time `x`) are stored in persistent variables (`var`) for tracking recent pivots.
2. **Market Structure Detection**:
- **Bullish Structure (BOS/CHoCH)**: Triggers when `close > recent PH` (break above swing high).
- If `resetOn = 'CHoCH'`, resets only on major shifts (Change of Character); otherwise, on all breaks.
- Sets trend state `os = 1` (bullish) and highlights the break with a horizontal line (dashed for CHoCH, dotted for BOS).
- Initializes trailing stop at the local minimum (lowest low since the pivot) using a backward loop: `btm = math.min(low , btm)`.
- **Bearish Structure**: Triggers when `close < recent PL`, mirroring the bullish logic (`os = -1`, local maximum for stop).
- Structure state `ms` tracks the break type (1 for bull, -1 for bear, 0 neutral), resetting based on user settings.
3. **Trailing Stop Calculation**:
- Tracks **trailing max/min**:
- On new bull structure: Reset `max = close`.
- On new bear: Reset `min = close`.
- Otherwise: `max = math.max(close, max)` / `min = math.min(close, min)`.
- **Stop Adjustment** (the "trailing" magic):
- On fresh structure: `ts = btm` (bull) or `top` (bear).
- In ongoing trend: Increment/decrement by a percentage of the max/min change:
- Bull: `ts += (max - max ) * (incr / 100)`
- Bear: `ts += (min - min ) * (incr / 100)`
- This creates a **ratcheting effect**: Stops move favorably with the trend but never against it, converging toward price at a controlled rate.
- **Visuals**:
- Plots `ts` line colored by trend (teal for bull, red for bear).
- Fills area between `close` and `ts` (orange on retracements).
- Draws structure lines from pivot to break point.
4. **Edge Cases**:
- Variables like `ph_cross`/`pl_cross` prevent multiple triggers on the same pivot.
- Neutral state (`ms = 0`) preserves prior `max/min` until a new structure.
### MTF Enhancement (Our Addition)
- **request.security() Integration**:
- Wraps the entire core function `f()` in a security call for each timeframe (`tf1`, `tf2`).
- Returns HTF values (e.g., `ts1`, `os1`, structure times/prices) to the chart's context.
- Uses `lookahead=barmerge.lookahead_off` for accurate historical repainting-free data.
- Structures are drawn using `xloc.bar_time` to align HTF lines precisely on the LTF chart.
- **Multi-Output Handling**:
- Separate plots/fills/lines for each TF (e.g., `plot_ts1`, `plot_ts2`).
- Colors and toggles per TF to distinguish HTF1 (e.g., teal/red) from HTF2 (e.g., blue/maroon).
- **Benefits**: Spot HTF bias on LTF entries, e.g., enter longs only if both TF1 (1H) and TF2 (4H) show bullish `os=1`.
This keeps the script lightweight—**no repainting, max 500 lines**, and fully compatible with LuxAlgo's original behavior when TFs are set to the chart's timeframe.
## 🔶 SETTINGS
### Core Parameters
- **Pivot Lookback** (`length = 14`): Bars left/right for pivot detection. Higher = smoother structures, fewer signals; lower = more noise.
- **Increment Factor %** (`incr = 100`): Speed of stop convergence (0-∞). 100% = full ratchet (mirrors max/min exactly); <100% = slower trail, reduces whipsaws.
- **Reset Stop On** (`'CHoCH'`): `'CHoCH'` = Reset only on major reversals (dashed lines); `'All'` = Reset on every BOS/CHoCH (tighter stops).
### MTF Support
- **Timeframe 1** (`tf1 = ""`): HTF for first set (e.g., "1H"). Empty = current chart.
- **Timeframe 2** (`tf2 = ""`): Second HTF (e.g., "4H"). Enables dual confluence.
### Display Toggles
- **Show Structures** (`true`): Draws horizontal lines for breaks (per TF colors).
- **Show Trailing Stop TF1/TF2** (`true`): Plots the stop line.
- **Show Fill TF1/TF2** (`true`): Area fill between close and stop.
### Candle Coloring (Optional)
- **Color Candles** (`false`): Enables custom `plotcandle` for body/wick/border.
- **Candle Color Based On TF** (`"None"`): `"TF1"`, `"TF2"`, or none. Colors bull trend green, bear red.
- **Candle Colors**: Separate inputs for bull/bear body, wick, border (e.g., solid green body, transparent wick).
### Alerts
- **Enable MS Break Alerts** (`false`): Notifies on structure breaks (bull/bear per TF) **only on bar close** (`barstate.isconfirmed` + `alert.freq_once_per_bar_close`).
- **Enable Stop Hit Alerts** (`false`): Triggers on stop breaches (long/short per TF), using `ta.crossunder/crossover`.
### Colors
- **TF1 Colors**: Bullish (teal), Bearish (red), Retracement (orange).
- **TF2 Colors**: Bullish (blue), Bearish (maroon), Retracement (orange).
- **Area Transparency** (`80`): Fill opacity (0-100).
## 🔶 USAGE
Trailing stops shine in **trend-following strategies**:
- **Entries**: Use structure breaks as signals (e.g., long on bullish BOS from HTF1).
- **Exits**: Trail stops for profit-locking; alert on hits for automation.
- **Confluence**: Overlay HTF1 (e.g., 1H) for bias, HTF2 (e.g., Daily) for major levels—enter LTF only on alignment.
- **Risk Management**: Lower `incr` avoids early stops in chop; reset on `'All'` for aggressive trailing.
! (i.imgur.com)
*HTF1 shows bullish structure (teal line), trailing stop ratchets up—long entry confirmed on LTF pullback.*
! (i.imgur.com)
*TF1 (blue) bearish, TF2 (red) neutral—avoid shorts until alignment.*
! (i.imgur.com)
*Colored based on TF1 trend: Green bodies on bull `os=1`.*
Pro Tip: Test on demo—pair with LuxAlgo's other tools like Smart Money Concepts for full structure ecosystem.
## 🔶 DETAILS: Mathematical Breakdown
On bullish break:
- Local min: `btm = ta.lowest(n - ph_x)` (optimized loop equivalent).
- Stop init: `ts = btm`.
- Update: `Δmax = max - max `, `ts_new = ts + Δmax * (incr/100)`.
Bearish mirrors with `Δmin` (negative, so decrements `ts`).
In MTF: HTF `time` aligns lines via `line.new(htf_time, level, current_time, level, xloc.bar_time)`.
No logs/math libs needed—pure Pine v5 efficiency.
## Disclaimer
This is for educational purposes. Not financial advice. Backtest thoroughly. Original by LuxAlgo—modify at your risk. See TradingView's (www.tradingview.com). Licensed under CC BY-NC-SA 4.0 (attribution to LuxAlgo required).
X Tail that Wagsintraday session-framework and ETH-anchored VWAP tool for TradingView. It draws today’s OVN (ETH) high/mid/low, today’s RTH-day open, previous day open/high/low, and a carried ETH VWAP handle (yesterday’s 4:00 PM NY VWAP, projected forward) to give you a clean, non-repainting scaffold for bias, structure, and execution. All timestamps are New York–local with DST handled explicitly, so historical sessions align correctly across time changes.
Key Capabilities
ETH OVN Range (18:00 → 09:30 NY)
Captures the rolling overnight high/low and computes the mid; at 09:30 NY it locks those levels and extends them to 16:00 NY (same day).
Optional labels (size/color configurable) placed slightly to the right of the 4 PM timestamp for readability.
Daily Handles (Today & Previous Day)
Today’s open line starts at the ETH open (anchor preserved) and extends toward 4 PM NY (or up to the “current bar + 5 bars” cap), with label control.
Previous day open/high/low plotted as discrete reference lines for carry-over structure.
ETH-Anchored VWAP (Live) + Bands
ETH-anchored VWAP runs only during the active ETH session (DST-aware).
Optional VWAP bands (0.5×, 1.0×, 2.0× multipliers) plotted as line-break series.
Carried ETH VWAP Handle (PD 4 PM Snapshot)
At 16:00 NY, the script snapshots the final ETH VWAP value.
On the next ETH open, it projects that value as a static dashed line through the session (non-mutating, non-repainting), with optional label.
Labeling & Styling
Single-toggle label system with color and five sizes.
Per-line color/width controls for quick visual hierarchy.
Internal “tail” logic keeps right endpoints near price (open-anchored lines extend to min(4 PM, now + 5 bars)), avoiding chart-wide overdraw.
Robust Session Logic
All session boundaries computed in NY local time; DST rules applied for historical bars.
Cross-midnight windows handled safely (no gaps or misalignment around day rolls).
Primary Use Cases
Session Bias & Context
Use OVN H/M/L and today’s open to define structural bias zones before RTH begins. A break-and-hold above OVN mid, for example, can filter long ideas; conversely, rejection at OVN high can warn of mean reversion.
Carry-Forward Mean/Value Reference
The carried ETH VWAP (PD 4 PM) acts as a “value memory” line for the next day. Traders can:
Fade tests away from it in balanced conditions,
Use it as a pullback/acceptance gauge during trends,
Track liquidity grabs when price spikes through and reclaims.
Execution Planning & Risk
Anchor stops/targets around PD H/L and OVN H/M/L for well-defined invalidation.
Combine with your entry model (order-flow, momentum, or pattern) to time fades at range extremes or momentum breaks from OVN mid.
Confluence Mapping
Layer the tool with opening range tools, HTF zones, or profile/VWAPs (weekly/daily) to spot high-quality confluence where multiple references cluster.
Regime & Day-Type Read
Quickly see whether RTH accepts/rejects the OVN range or gravitates to PD VWAP handle, helping classify the day (trend, balanced, double-distribution, etc.).
Quick Start
Apply to your intraday chart (any instrument supported by TradingView; best on ≤15m for live intraday context).
In Current Day group, keep Open and OVN HL on; optionally display the mid.
In Previous Day group, enable PD Open/HL for carry-over levels.
Enable AVWAP if you want live ETH-anchored VWAP and its Bands for distance context.
Keep PD VWAP on to project yesterday’s 4 PM ETH VWAP as a static dashed line into today.
Use the Label group to size/color the on-chart tags.
Settings Overview (Plain-English)
Label: Toggle labels on/off; choose label text color and size.
Current Day:
Open (color/width) — daily open line anchored at ETH open.
OVN HL (and Mid) — overnight high/low and midpoint, locked at 09:30 and extended to 16:00.
AVWAP + Bands — ETH-anchored VWAP with optional 0.5×/1×/2× bands.
Previous Day:
PD Open/HL — yesterday’s daily handles.
PD VWAP — the carried snapshot of yesterday’s 4 PM ETH VWAP projected forward (dashed).
Notes & Best Practices
Time Zone: All session logic is hard-coded to America/New_York and DST-robust. No manual DST tweaks required.
Non-Repainting: The carried PD VWAP line is a snapshot; once drawn, it does not back-fill or mutate.
Intraday Use: Designed for intraday execution. It will display on higher TFs, but the session granularity is most informative at ≤15m.
Performance: Script caps lines/labels (500) and uses short “tails” to keep charts responsive.
Compatibility: Uses request.security(..., "D", series, lookahead_on) intentionally to lock daily handles early for planning; this is by design.
Typical Playbook Examples
Fade Extremes in Balance: As RTH opens inside OVN, look for rejection wicks at OVN High with confluence from PD VWAP handle overhead; risk above OVN High.
Trend Continuation: In directional sessions, acceptances above OVN Mid with price pulling back to the live ETH VWAP can offer continuation entries.
Reversion to Value: Sharp extensions away from the carried PD VWAP that quickly stall often revert to that handle; use it as a target or as an acceptance test.
Risk & Position DashboardRisk & Position Dashboard
Overview
The Risk & Position Dashboard is a comprehensive trading tool designed to help traders calculate optimal position sizes, manage risk, and visualize potential profit/loss scenarios before entering trades. This indicator provides real-time calculations for position sizing based on account size, risk percentage, and stop-loss levels, while displaying multiple take-profit targets with customizable risk-reward ratios.
Key Features
Position Sizing & Risk Management:
Automatic position size calculation based on account size and risk percentage
Support for leveraged trading with maximum leverage limits
Fractional shares support for brokers that allow partial share trading
Real-time fee calculation including entry, stop-loss, and take-profit fees
Break-even price calculation including trading fees
Multi-Target Profit Management:
Support for up to 3 take-profit levels with individual portion allocations
Customizable risk-reward ratios for each take-profit target
Visual profit/loss zones displayed as colored boxes on the chart
Individual profit calculations for each take-profit level
Visual Dashboard:
Clean, customizable table display showing all key metrics
Configurable label positioning and styling options
Real-time tracking of whether stop-loss or take-profit levels have been reached
Color-coded visual zones for easy identification of risk and reward areas
Advanced Configuration:
Comprehensive input validation and error handling
Support for different chart timeframes and symbols
Customizable colors, fonts, and display options
Hide/show individual data fields for personalized dashboard views
How to Use
Set Account Parameters: Configure your account size, maximum risk percentage per trade, and trading fees in the "Account Settings" section.
Define Trade Setup: Use the "Entry" time picker to select your entry point on the chart, then input your entry price and stop-loss level.
Configure Take Profits: Set your desired risk-reward ratios and portion allocations for each take-profit level. The script supports 1-3 take-profit targets.
Analyze Results: The dashboard will automatically calculate and display position size, number of shares, potential profits/losses, fees, and break-even levels.
Visual Confirmation: Colored boxes on the chart show profit zones (green) and loss zones (red), with lines extending to current price levels.
Reset Entry and SL:
You can easily reset the entry and stop-loss by clicking the "Reset points..." button from the script's "More" menu.
This is useful if you want to quickly clear your current trade setup and start fresh without manually adjusting the points on the chart.
Calculations
The script performs sophisticated calculations including:
Position size based on risk amount and price difference between entry and stop-loss
Leverage requirements and position amount calculations
Fee-adjusted risk-reward ratios for realistic profit expectations
Break-even price including all trading costs
Individual profit calculations for partial position closures
Detailed Take-Profit Calculation Formula:
The take-profit prices are calculated using the following mathematical formula:
// Core variables:
// risk_amount = account_size * (risk_percentage / 100)
// total_risk_per_share = |entry_price - sl_price| + (entry_price * fee%) + (sl_price * fee%)
// shares = risk_amount / total_risk_per_share
// direction_factor = 1 for long positions, -1 for short positions
// Take-profit calculation:
net_win = total_risk_per_share * shares * RR_ratio
tp_price = (net_win + (direction_factor * entry_price * shares) + (entry_price * fee% * shares)) / (direction_factor * shares - fee% * shares)
Step-by-step example for a long position (based on screenshot):
Account Size: 2,000 USDT, Risk: 2% = 40 USDT
Entry: 102,062.9 USDT, Stop Loss: 102,178.4 USDT, Fee: 0.06%
Risk per share: |102,062.9 - 102,178.4| + (102,062.9 × 0.0006) + (102,178.4 × 0.0006) = 115.5 + 61.24 + 61.31 = 238.05 USDT
Shares: 40 ÷ 238.05 = 0.168 shares (rounded to 0.17 in display)
Position Size: 0.17 × 102,062.9 = 17,350.69 USDT
Position Amount (with 9x leverage): 17,350.69 ÷ 9 = 1,927.85 USDT
For 2:1 RR: Net win = 238.05 × 0.17 × 2 = 80.94 USDT
TP1 price = (80.94 + (1 × 102,062.9 × 0.17) + (102,062.9 × 0.0006 × 0.17)) ÷ (1 × 0.17 - 0.0006 × 0.17) = 101,464.7 USDT
For 3:1 RR: TP2 price = 101,226.7 USDT (following same formula with RR=3)
This ensures that after accounting for all fees, the actual risk-reward ratio matches the specified target ratio.
Risk Management Features
Maximum Trade Amount: Optional setting to limit position size regardless of account size
Leverage Limits: Built-in maximum leverage protection
Fee Integration: All calculations include realistic trading fees for accurate expectations
Validation: Automatic checking that take-profit portions sum to 100%
Historical Tracking: Visual indication when stop-loss or take-profit levels are reached (within last 5000 bars)
Understanding Max Trade Amount - Multiple Simultaneous Trades:
The "Max Trade Amount" feature is designed for traders who want to open multiple positions simultaneously while maintaining proper risk management. Here's how it works:
Key Concept:
- Risk percentage (2%) always applies to your full Account Size
- Max Trade Amount limits the capital allocated per individual trade
- This allows multiple trades with full risk on each trade
Example from Screenshot:
Account Size: 2,000 USDT
Max Trade Amount: 500 USDT
Risk per Trade: 2% × 2,000 = 40 USDT per trade
Stop Loss Distance: 0.11% from entry
Result: Position Size = 17,350.69 USDT with 35x leverage
Total Risk (including fees): 40.46 USDT
Multiple Trades Strategy:
With this setup, you can open:
Trade 1: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 2: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 3: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 4: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Total Portfolio Exposure:
- 4 simultaneous trades = 4 × 495.73 = 1,982.92 USDT position amount
- Total risk exposure = 4 × 40 = 160 USDT (8% of account)






















