Exponential Moving Average (Set of 3) [Krypt] + 13/34 EMAsI took Krypt's script and essentially added on to it.
the 20/50/100/200 EMAs should be used together as support and resistance as normal.
Wait for price to break 200 EMA
Wait for 50 EMA to cross 200 EMA
Wait for pullback to 50 EMA to open position
20 and 100 EMAs are for extra information about moving support and resistance
and 13/34 EMAs should be used in conjunction
When 13 EMA crosses 34 EMA, open position
When price gets far from 13/34, close position (because price will attempt to revert back to mean)
This is better for scalping and swing trades than the 20/50/100/200 setup.
Twitter: @AzorAhai06
Поиск скриптов по запросу "马斯克+100万"
Ichimoku Cloud Score v1.0This script calculates a simple Ichimoku Score based on the signals documented here , with a few additions. Each of the score components can be individually weighted via the script inputs . The output is a plot of the normalized Ichimoku score, in the range of -100 to 100.
This script has been heavily modified from 'Ichimoku Cloud Signal Score v2.0.0 '. Credit to user 'dashed' for the initial implementation.
This has been modified with several refinements:
Clean/Organized Code
Simplified Inputs
Improved Style
Scores normalized to a range (-100, 100)
Bugfixes and Improvements
Script Inputs: i.imgur.com
Volume RatioDefinition:
Volume ratio can be obtained in a similar way to RSI.
Volume Ratio (%) = 100 - 100/(1+vr)
The parameter "vr" is defined as
vr=(A+U/2)/(D+U/2)
A=Total volume of the periods when the price advanced
D=Total volume of the periods when the price declined
U=Total volume of the periods when the price unchanged
After substitution, following expression can be derived and the denominator represents total volume of all periods.
Volume Ratio (%) = 100 x (A+U/2)/(A+D+U)
Notes:
A similar method to interpret RSI can be employed.
1) Overbought level over 70% and oversold level under 30%. These levels need to be adjusted according to the periods, time frames and issues.
2) Bullish picture over 50% line and bearish picture under 50% line.
3) Crossing oversold level to the upside can be taken as a confirmation of bullish reversal. - and vice versa for a bearish reversal.
4) After a long-term bearish market, the increase of volume can happen in the early stage of a bullish market.
5) Buying opportunity can be suggested when the volume ratio is declining and the price is either advancing or leveling off.
CCI with Volume Weighted EMA Here is an attempt to improve on the CCI using a volume weighted ema which is then plugged into the CCI formula.
Use:
The CCI with VW EMA is an oscillator that gives readings between -100 and +100. The usual use is to 'go long' with values over +100 and short on values less than -100.
Another use of this oscillator is a countertrend indicator where one sells at crosses under +100 and buys on crosses over -100.
Multi-Functional Fisher Transform MTF with MACDL TRIGGERWhat this indicator gives you is a true signal when price is exhausted and ready for a fast turnaround. Fisher Transform is set for multi-time frame and also allows the user to change the length. This way a user can compare two or more time spans and lengths to look for these MACDL divergent triggers after a Fisher exhaustion. With so many indicators, it's probably best to merge these indicators and change the Fisher and Trigger colors so you can still have a look at price action (remember to scale right after merger). I've noticed from time to time when you have Fisher 34 100 and 300 up and running on two different time frames such as 5 and 15 min charts, with MACDL triggers on the 100/300 or 34/100 you get a high probability trade trigger. However, there are rare exceptions such as when price moves in a parabolic state up or down for a long period where this indication does not work. Ideally this indicator works best in a sideways market or slow rising/descending moving market.
This indicator was worked on by Glaz, nmike and myself
LazyBear also introduced the MACDL indicator
CCI Crossover AlertThis very simple indicator will give you a blue background where the CCI crossed from below -100 to above -100, and a red background where it crossed from above 100 to below 100.
Smart Money Volume Matrix [Ata]Smart Money Volume Matrix
The Smart Money Volume Matrix (SMV Matrix) is an advanced volume-spread analysis (VSA) dashboard and charting tool designed to identify significant market anomalies by analyzing the relationship between price extremes and volume flow.
Unlike traditional indicators that rely solely on moving averages or oscillators, this tool performs a "Snapshot Analysis" of a defined lookback period (default: 100 bars) to rank price action based on Order Flow Dominance. It isolates the Top 10 Highest and Lowest Close prices and scrutinizes the volume behind them to categorize market sentiment into four distinct phases: Distribution, No Demand, Absorption, and Exhaustion.
Core Logic & Methodology
The script operates on a Zero-Lag Snapshot Engine. It does not print historical signals bar-by-bar; instead, it evaluates the current market structure relative to the recent history (Lookback Period).
1. Ranking Engine: The script scans the lookback period to find the Top 10 Highest Closes and Top 10 Lowest Closes.
2. Volume Classification: For each ranked bar, it calculates the "Intrabar Buy/Sell Volume" (or approximates it using candle geometry if Intrabar data is unavailable).
3. Dominance Detection: It compares Buying Volume vs. Selling Volume to determine who is in control at critical price levels.
Signal Classifications (VSA Logic)
The indicator generates labels on the chart and updates the dashboard table based on the following logic:
1. At Price Tops (Resistance Areas):
- Distribution (Supply): High Price + High Total Volume + Sellers Dominant.
Interpretation: Indicates heavy institutional selling into rising prices. Often precedes a reversal.
- Buy Climax: High Price + High Total Volume + Buyers Dominant.
Interpretation: Extreme buying frenzy. While bullish, it often marks a "trap" or temporary top due to exhaustion.
- No Demand: High Price + Low Volume.
Interpretation: Prices drifted higher but lack institutional participation. A sign of weakness.
2. At Price Bottoms (Support Areas):
- Absorption: Low Price + High Total Volume + Buyers Dominant.
Interpretation: Institutional money is absorbing selling pressure (passive buying). A strong sign of accumulation.
- Panic Sell: Low Price + High Total Volume + Sellers Dominant.
Interpretation: Extreme fear. High volume at lows typically indicates capitulation and potential hands-changing.
- Exhaustion: Low Price + Low Volume.
Interpretation: Selling pressure has dried up. The market may float upward due to lack of sellers.
Key Features
- Dashboard Matrix Table:
Displays the exact Close Price, Buy/Sell Volume, and Market State (Group) for the Top 10 ranking bars.
Smart Footer: Automatically detects the active "Resistance Zone" (derived from G1 Distribution levels) and "Support Zone" (derived from G3 Absorption levels) and reports the current price status relative to these zones (e.g., "Testing Resistance", "Breakout", "At Support").
- Smart Zones (Auto S/R):
Automatically draws Support and Resistance boxes extending into the future based on the most significant volume clusters found in the rankings. Includes logic to detect "Flips" (e.g., when Support breaks, it is labeled as a flip to Resistance).
- Average Trend Channels:
Calculates a Linear Regression trend line based specifically on the coordinates of the Top 10 Highs and Top 10 Lows, providing a "Best Fit" channel for the current market structure.
- Visual Clarity:
Labels utilize a "Smart Stacking" algorithm to prevent overlap on the chart. Guide lines connect labels to their respective candles for precise identification.
Settings & Configuration
- Matrix Settings: Lookback Period (default 100 bars) and Top Rank Count.
- Volume Engine: Choose between "Intrabar (Precise)" for accurate order flow or "Geometry (Approx)" for standard volume estimation.
- Visuals: Toggle Table, Labels, Lines, Zones, and Trend Lines. Adjust transparency and font sizes.
IMPORTANT NOTE ON SNAPSHOT LOGIC
This indicator is designed as a Real-Time Dashboard. It continuously updates the "Top 10" list as new candles form. Therefore, a label that appears on a candle may disappear if that candle falls out of the Top 10 ranking or leaves the lookback window. This is intended behavior to ensure the chart always reflects the current most critical levels, rather than a historical record of past signals. It is best used for live market analysis rather than historical back testing.
Disclaimer: This tool is for educational and analytical purposes only. Volume analysis is subjective and should be used in conjunction with other methods of technical analysis.
ATH대비 지정하락률에 도착 시 매수 - 장기홀딩 선물 전략(ATH Drawdown Re-Buy Long Only)본 스크립트는 과거 하락 데이터를 이용하여, 정해진 하락 %가 발생하는 경우 자기 자본의 정해진 %만큼을 진입하게 설계되어진 스트레티지입니다.
레버리지를 사용할 수 있으며 기본적으로 셋팅해둔 값이 내장되어있습니다.(자유롭게 바꿔서 쓰시면 됩니다.) 추가적으로 2번의 진입 외에도 다른 진입 기준, 진입 %를 설정하실 수 있으며 - ChatGPT에게 요청하면 수정해줄 것입니다.
실제 사용용도로는 KillSwitch 기능을 꺼주세요. 바 돋보기 기능을 켜주세요.
ATH Drawdown Re-Buy Long Only 전략 설명
1. 전략 개요
ATH Drawdown Re-Buy Long Only 전략은 자산의 역대 최고가(ATH, All-Time High)를 기준으로 한 하락폭(드로우다운)을 활용하여,
특정 구간마다 단계적으로 롱 포지션을 구축하는 자동 재매수(Long Only) 전략입니다.
본 전략은 다음과 같은 목적을 가지고 설계되었습니다.
급격한 조정 구간에서 체계적인 분할 매수 및 레버리지 활용
ATH를 기준으로 한 명확한 진입 규칙 제공
실시간으로
평단가
레버리지
청산가 추정
계좌 MDD
수익률
등을 시각적으로 제공하여 리스크와 포지션 상태를 직관적으로 확인할 수 있도록 지원
※ 본 전략은 교육·연구·백테스트 용도로 제공되며,
어떠한 형태의 투자 권유 또는 수익을 보장하지 않습니다.
2. 전략의 핵심 개념
2-1. ATH(역대 최고가) 기준 드로우다운
전략은 차트 상에서 항상 가장 높은 고가(High)를 ATH로 기록합니다.
새로운 고점이 형성될 때마다 ATH를 갱신하고, 해당 ATH를 기준으로 다음을 계산합니다.
현재 바의 저가(Low)가 ATH에서 몇 % 하락했는지
현재 바의 종가(Close)가 ATH에서 몇 % 하락했는지
그리고 사전에 설정한 두 개의 드로우다운 구간에서 매수를 수행합니다.
1차 진입 구간: ATH 대비 X% 하락 시
2차 진입 구간: ATH 대비 Y% 하락 시
각 구간은 ATH가 새로 갱신될 때마다 한 번씩만 작동하며,
새로운 ATH가 생성되면 다시 “1차 / 2차 진입 가능 상태”로 초기화됩니다.
2-2. 첫 포지션 100% / 300% 특수 규칙
이 전략의 중요한 특징은 **“첫 포지션 진입 시의 예외 규칙”**입니다.
전략이 현재 어떠한 포지션도 들고 있지 않은 상태에서
최초로 롱 포지션을 진입하는 시점(첫 포지션)에 대해:
기본적으로는 **자산의 100%**를 기준으로 포지션을 구축하지만,
만약 그 순간의 가격이 ATH 대비 설정값 이상(예: 약 –72.5% 이상 하락한 상황) 이라면
→ 자산의 300% 규모로 첫 포지션을 진입하도록 설계되어 있습니다.
이 규칙은 다음과 같이 동작합니다.
첫 진입이 1차 드로우다운 구간에서 발생하든,
첫 진입이 2차 드로우다운 구간에서 발생하든,
현재 하락폭이 설정된 기준 이상(예: –72.5% 이상) 이라면
→ “이 정도 하락이면 첫 진입부터 더 공격적으로 들어간다”는 의미로 300% 규모로 진입
그 이하의 하락폭이라면
→ 첫 진입은 100% 규모로 제한
즉, 전략은 다음 두 가지 모드로 동작합니다.
일반적인 상황의 첫 진입: 자산의 100%
심각한 드로우다운 구간에서의 첫 진입: 자산의 300%
이 특수 규칙은 깊은 하락에서는 공격적으로, 평소에는 상대적으로 보수적으로 진입하도록 설계된 것입니다.
3. 전략 동작 구조
3-1. 매수 조건
차트 상 High 기준으로 ATH를 추적합니다.
각 바마다 해당 ATH에서의 하락률을 계산합니다.
사용자가 설정한 두 개의 드로우다운 구간(예시):
1차 구간: 예를 들어 ATH – 50%
2차 구간: 예를 들어 ATH – 72.5%
각 구간에 대해 다음과 같은 조건을 확인합니다.
“이번 ATH 구간에서 아직 해당 구간 매수를 한 적이 없는 상태”이고,
현재 바의 저가(Low)가 해당 구간 가격 이하를 찍는 순간
→ 해당 바에서 매수 조건 충족으로 간주
실제 주문은:
해당 구간 가격에 맞춰 롱 포지션 진입(리밋/시장가 기반 시뮬레이션) 으로 처리됩니다.
3-2. ATH 갱신과 진입 기회 리셋
차트 상에서 새로운 고점(High)이 기존 ATH를 넘어서는 순간,
ATH가 갱신되고,
1차 / 2차 진입 여부를 나타내는 내부 플래그가 초기화됩니다.
이를 통해, 시장이 새로운 고점을 돌파해 나갈 때마다,
해당 구간에서 다시 한 번씩 1차·2차 드로우다운 진입 기회를 갖게 됩니다.
4. 포지션 사이징 및 레버리지
4-1. 계좌 자산(Equity) 기준 포지션 크기 결정
전략은 현재 계좌 자산을 다음과 같이 정의하여 사용합니다.
현재 자산 = 초기 자본 + 실현 손익 + 미실현 손익
각 진입 구간에서의 포지션 가치는 다음과 같이 결정됩니다.
1차 진입 구간:
“자산의 몇 %를 사용할지”를 설정값으로 입력
설정된 퍼센트를 계좌 자산에 곱한 뒤,
다시 전략 내 레버리지 배수(Leverage) 를 곱하여 실제 포지션 가치를 계산
2차 진입 구간:
동일한 방식으로, 독립된 퍼센트 설정값을 사용
즉, 포지션 가치는 다음과 같이 계산됩니다.
포지션 가치 = 현재 자산 × (해당 구간 설정 % / 100) × 레버리지 배수
그리고 이를 해당 구간의 진입 가격으로 나누어 실제 수량(토큰 단위) 를 산출합니다.
4-2. 첫 포지션의 예외 처리 (100% / 300%)
첫 포지션에 대해서는 위의 일반적인 퍼센트 설정 대신,
다음과 같은 고정 비율이 사용됩니다.
기본: 자산의 100% 규모로 첫 포지션 진입
단, 진입 시점의 ATH 대비 하락률이 설정값 이상(예: –72.5% 이상) 일 경우
→ 자산의 300% 규모로 첫 포지션 진입
이때 역시 다음 공식을 사용합니다.
포지션 가치 = 현재 자산 × (100% 또는 300%) × 레버리지
그리고 이를 가격으로 나누어 실제 진입 수량을 계산합니다.
이 규칙은:
첫 진입이 1차 구간이든 2차 구간이든 동일하게 적용되며,
“충분히 깊은 하락 구간에서는 첫 진입부터 더 크게,
평소에는 비교적 보수적으로” 라는 운용 철학을 반영합니다.
4-3. 실레버리지(Real Leverage)의 추적
전략은 각 바 단위로 다음을 추적합니다.
바가 시작할 때의 기존 포지션 크기
해당 바에서 새로 진입한 수량
이를 바탕으로, 진입이 발생한 시점에 다음을 계산합니다.
실제 레버리지 = (포지션 가치 / 현재 자산)
그리고 차트 상에 예를 들어:
Lev 2.53x 와 같은 형식의 레이블로 표시합니다.
이를 통해, 매수 시점마다 실제 계좌 레버리지가 어느 정도였는지를 직관적으로 확인할 수 있습니다.
5. 시각화 및 모니터링 요소
5-1. 차트 상 시각 요소
전략은 차트 위에 다음과 같은 정보를 직접 표시합니다.
ATH 라인
High 기준으로 계산된 역대 최고가를 주황색 선으로 표시
평단가(평균 진입가) 라인
현재 보유 포지션이 있을 때,
해당 포지션의 평균 진입가를 노란색 선으로 표시
추정 청산가(고정형 청산가) 라인
포지션 수량이 변화하는 시점을 감지하여,
당시의 평단가와 실제 레버리지를 이용해 근사적인 청산가를 계산
이를 빨간색 선으로 차트에 고정 표시
포지션이 없거나 레버리지가 1배 이하인 경우에는 청산가 라인을 제거
매수 마커 및 레이블
1차/2차 매수 조건이 충족될 때마다 해당 지점에 매수 마커를 표시
"Buy XX% @ 가격", "Lev XXx" 형태의 라벨로
진입 비율과 당시 레버리지를 함께 시각화
레이블의 위치는 설정에서 선택 가능:
바 아래 (Below Bar)
바 위 (Above Bar)
실제 가격 위치 (At Price)
5-2. 우측 상단 정보 테이블
차트 우측 상단에는 현재 계좌·포지션 상태를 요약한 정보 테이블이 표시됩니다.
대표적으로 다음 항목들이 포함됩니다.
Pos Qty (Token)
현재 보유 중인 포지션 수량(토큰 기준, 절대값 기준)
Pos Value (USDT)
현재 포지션의 시장 가치 (수량 × 현재 가격)
Leverage (Now)
현재 실레버리지 (포지션 가치 / 현재 자산)
DD from ATH (%)
현재 가격 기준, 최근 ATH에서의 하락률(%)
Avg Entry
현재 포지션의 평균 진입 가격
PnL (%)
현재 포지션 기준 미실현 손익률(%)
Max DD (Equity %)
전략 전체 기간 동안 기록된 계좌 기준 최대 손실(MDD, Max Drawdown)
Last Entry Price
가장 최근에 포지션을 추가로 진입한 직후의 평균 진입 가격
Last Entry Lev
위 “Last Entry Price” 시점에서의 실레버리지
Liq Price (Fixed)
위에서 설명한 고정형 추정 청산가
Return from Start (%)
전략 시작 시점(초기 자본) 대비 현재 계좌 자산의 총 수익률(%)
이 테이블을 통해 사용자는:
현재 계좌와 포지션의 상태
리스크 수준
누적 성과
를 직관적으로 파악할 수 있습니다.
6. 시간 필터 및 라벨 옵션
6-1. 전략 동작 기간 설정
전략은 옵션으로 특정 기간에만 전략을 동작시키는 시간 필터를 제공합니다.
“Use Date Range” 옵션을 활성화하면:
시작 시각과 종료 시각을 지정하여
해당 구간에 한해서만 매매가 발생하도록 제한
옵션을 비활성화하면:
전략은 전체 차트 구간에서 자유롭게 동작
6-2. 진입 라벨 위치 설정
사용자는 매수/레버리지 라벨의 위치를 선택할 수 있습니다.
바 아래 (Below Bar)
바 위 (Above Bar)
실제 가격 위치 (At Price)
이를 통해 개인 취향 및 차트 가독성에 맞추어
시각화 방식을 유연하게 조정할 수 있습니다.
7. 활용 대상 및 사용 예시
본 전략은 다음과 같은 목적에 적합합니다.
현물 또는 선물 롱 포지션 기준 장기·스윙 관점 추매 전략 백테스트
“고점 대비 하락률”을 기준으로 한 규칙 기반 운용 아이디어 검증
레버리지 사용 시
계좌 레버리지·청산가·MDD를 동시에 모니터링하고자 하는 경우
특정 자산에 대해
“새로운 고점이 형성될 때마다
일정한 규칙으로 깊은 조정 구간에서만 분할 진입하고자 할 때”
실거래에 그대로 적용하기보다는,
전략 아이디어 검증 및 리스크 프로파일 분석,
자신의 성향에 맞는 파라미터 탐색 용도로 사용하는 것을 권장합니다.
8. 한계 및 유의사항
백테스트 결과는 미래 성과를 보장하지 않습니다.
과거 데이터에 기반한 시뮬레이션일 뿐이며,
실제 시장에서는
유동성
슬리피지
수수료 체계
강제청산 규칙
등 다양한 변수가 존재합니다.
청산가는 단순화된 공식에 따른 추정치입니다.
거래소별 실제 청산 규칙, 유지 증거금, 수수료, 펀딩비 등은
본 전략의 계산과 다를 수 있으며,
청산가 추정 라인은 참고용 지표일 뿐입니다.
레버리지 및 진입 비율 설정에 따라 손실 폭이 매우 커질 수 있습니다.
특히 **“첫 포지션 300% 진입”**과 같이 매우 공격적인 설정은
시장 급락 시 계좌 손실과 청산 리스크를 크게 증가시킬 수 있으므로
신중한 검토가 필요합니다.
실거래 연동 시에는 별도의 리스크 관리가 필수입니다.
개별 손절 기준
포지션 상한선
전체 포트폴리오 내 비중 관리 등
본 전략 외부에서 추가적인 안전장치가 필요합니다.
9. 결론
ATH Drawdown Re-Buy Long Only 전략은 단순한 “저가 매수”를 넘어서,
ATH 기준으로 드로우다운을 구조적으로 활용하고,
첫 포지션에 대한 **특수 규칙(100% / 300%)**을 적용하며,
레버리지·청산가·MDD·수익률을 통합적으로 시각화함으로써,
하락 구간에서의 규칙 기반 롱 포지션 구축과
리스크 모니터링을 동시에 지원하는 전략입니다.
사용자는 본 전략을 통해:
자신의 시장 관점과 리스크 허용 범위에 맞는
드로우다운 구간
진입 비율
레버리지 설정
다양한 시나리오에 대한 백테스트와 분석
을 수행할 수 있습니다.
다시 한 번 강조하지만,
본 전략은 연구·학습·백테스트를 위한 도구이며,
실제 투자 판단과 책임은 전적으로 사용자 본인에게 있습니다.
/ENG Version.
This script is designed to use historical drawdown data and automatically enter positions when a predefined percentage drop from the all-time high occurs, using a predefined percentage of your account equity.
You can use leverage, and default parameter values are provided out of the box (you can freely change them to suit your style).
In addition to the two main entry levels, you can add more entry conditions and custom entry percentages – just ask ChatGPT to modify the script.
For actual/live usage, please turn OFF the KillSwitch function and turn ON the Bar Magnifier feature.
ATH Drawdown Re-Buy Long Only Strategy
1. Strategy Overview
The ATH Drawdown Re-Buy Long Only strategy is an automatic re-buy (Long Only) system that builds long positions step-by-step at specific drawdown levels, based on the asset’s all-time high (ATH) and its subsequent drawdown.
This strategy is designed with the following goals:
Systematic scaled buying and leverage usage during sharp correction periods
Clear, rule-based entry logic using drawdowns from ATH
Real-time visualization of:
Average entry price
Leverage
Estimated liquidation price
Account MDD (Max Drawdown)
Return / performance
This allows traders to intuitively monitor both risk and position status.
※ This strategy is provided for educational, research, and backtesting purposes only.
It does not constitute investment advice and does not guarantee any profits.
2. Core Concepts
2-1. Drawdown from ATH (All-Time High)
On the chart, the strategy always tracks the highest high as the ATH.
Whenever a new high is made, ATH is updated, and based on that ATH the following are calculated:
How many percent the current bar’s Low is below the ATH
How many percent the current bar’s Close is below the ATH
Using these, the strategy executes buys at two predefined drawdown zones:
1st entry zone: When price drops X% from ATH
2nd entry zone: When price drops Y% from ATH
Each zone is allowed to trigger only once per ATH cycle.
When a new ATH is created, the “1st / 2nd entry possible” flags are reset, and new opportunities open up for that ATH leg.
2-2. Special Rule for the First Position (100% / 300%)
A key feature of this strategy is the special rule for the very first position.
When the strategy currently holds no position and is about to open the first long position:
Under normal conditions, it builds the position using 100% of account equity.
However, if at that moment the price has dropped by at least a predefined threshold from ATH (e.g. around –72.5% or more),
→ the strategy will open the first position using 300% of account equity.
This rule works as follows:
Whether the first entry happens at the 1st drawdown zone or at the 2nd drawdown zone,
If the current drawdown from ATH is at or below the threshold (e.g. –72.5% or worse),
→ the strategy interprets this as “a sufficiently deep crash” and opens the initial position with 300% of equity.
If the drawdown is less severe than the threshold,
→ the first entry is capped at 100% of equity.
So the strategy has two modes for the first entry:
Normal market conditions: 100% of equity
Deep drawdown conditions: 300% of equity
This special rule is intended to be aggressive in extremely deep crashes while staying more conservative in normal corrections.
3. Strategy Logic & Execution
3-1. Entry Conditions
The strategy tracks the ATH using the High price.
For each bar, it calculates the drawdown from ATH.
The user defines two drawdown zones, for example:
1st zone: ATH – 50%
2nd zone: ATH – 72.5%
For each zone, the strategy checks:
If no buy has been executed yet for that zone in the current ATH leg, and
If the current bar’s Low touches or falls below that zone’s price level,
→ That bar is considered to have triggered a buy condition.
Order simulation:
The strategy simulates entering a long position at that zone’s price level
(using a limit/market-like approximation for backtesting).
3-2. ATH Reset & Entry Opportunity Reset
When a new High goes above the previous ATH:
The ATH is updated to this new high.
Internal flags that track whether the 1st and 2nd entries have been used are reset.
This means:
Each time the market makes a new ATH,
The strategy once again has a fresh opportunity to execute 1st and 2nd drawdown entries for that new ATH leg.
4. Position Sizing & Leverage
4-1. Position Size Based on Account Equity
The strategy defines current equity as:
Current Equity = Initial Capital + Realized PnL + Unrealized PnL
For each entry zone, the position value is calculated as follows:
The user inputs:
“What % of equity to use at this zone”
The strategy:
Multiplies current equity by that percentage
Then multiplies by the strategy’s leverage factor
Thus:
Position Value = Current Equity × (Zone % / 100) × Leverage
Finally, this position value is divided by the entry price to determine the actual position size in tokens.
4-2. Exception for the First Position (100% / 300%)
For the very first position (when there is no open position),
the strategy does not use the zone % parameters. Instead, it uses fixed ratios:
Default: Enter the first position with 100% of equity.
If the drawdown from ATH at that moment is greater than or equal to a predefined threshold (e.g. –72.5% or more)
→ Enter the first position with 300% of equity.
The position value is computed as:
Position Value = Current Equity × (100% or 300%) × Leverage
Then it is divided by the entry price to obtain the token quantity.
This rule:
Applies regardless of whether the first entry occurs at the 1st zone or 2nd zone.
Embeds the philosophy:
“In very deep crashes, go much larger on the first entry; otherwise, stay more conservative.”
4-3. Tracking Real Leverage
On each bar, the strategy tracks:
The existing position size at the start of the bar
The newly added size (if any) on that bar
When a new entry occurs, it calculates the real leverage at that moment:
Real Leverage = (Position Value / Current Equity)
This is then displayed on the chart as a label, for example:
Lev 2.53x
This makes it easy to see the actual leverage level at each entry point.
5. Visualization & Monitoring
5-1. On-Chart Visual Elements
The strategy plots the following directly on the chart:
ATH Line
The all-time high (based on High) is plotted as an orange line.
Average Entry Price Line
When a position is open, the average entry price of that position is plotted as a yellow line.
Estimated Liquidation Price (Fixed) Line
The strategy detects when the position size changes.
At each size change, it uses the current average entry price and real leverage to compute an approximate liquidation price.
This “fixed liquidation price” is then plotted as a red line on the chart.
If there is no position, or if leverage is 1x or lower, the liquidation line is removed.
Entry Markers & Labels
When 1st/2nd entry conditions are met, the strategy:
Marks the entry point on the chart.
Displays labels such as "Buy XX% @ Price" and "Lev XXx",
showing both entry percentage and real leverage at that time.
The label placement is configurable:
Below Bar
Above Bar
At Price
5-2. Information Table (Top-Right Panel)
In the top-right corner of the chart, the strategy displays a summary table of the current account and position status. It typically includes:
Pos Qty (Token)
Absolute size of the current position (in tokens)
Pos Value (USDT)
Market value of the current position (qty × current price)
Leverage (Now)
Current real leverage (position value / current equity)
DD from ATH (%)
Current drawdown (%) from the latest ATH, based on current price
Avg Entry
Average entry price of the current position
PnL (%)
Unrealized profit/loss (%) of the current position
Max DD (Equity %)
The maximum equity drawdown (MDD) recorded over the entire backtest period
Last Entry Price
Average entry price immediately after the most recent add-on entry
Last Entry Lev
Real leverage at the time of the most recent entry
Liq Price (Fixed)
The fixed estimated liquidation price described above
Return from Start (%)
Total return (%) of equity compared to the initial capital
Through this table, users can quickly grasp:
Current account and position status
Current risk level
Cumulative performance
6. Time Filters & Label Options
6-1. Strategy Date Range Filter
The strategy provides an option to restrict trading to a specific time range.
When “Use Date Range” is enabled:
You can specify start and end timestamps.
The strategy will only execute trades within that range.
When this option is disabled:
The strategy operates over the entire chart history.
6-2. Entry Label Placement
Users can customize where entry/leverage labels are drawn:
Below Bar (Below Bar)
Above Bar (Above Bar)
At the actual price level (At Price)
This allows you to adjust visualization according to personal preference and chart readability.
7. Use Cases & Applications
This strategy is suitable for the following purposes:
Long-term / swing-style re-buy strategies for spot or futures long positions
Testing rule-based strategies that rely on “drawdown from ATH” as a main signal
Monitoring account leverage, liquidation price, and MDD when using leverage
Handling situations where, for a given asset:
“Every time a new ATH is formed,
you want to wait for deep corrections and enter only at specific drawdown zones”
It is generally recommended to use this strategy not as a direct plug-and-play live system, but as a tool for:
Strategy idea validation
Risk profile analysis
Parameter exploration to match your personal risk tolerance and style
8. Limitations & Warnings
Backtest results do not guarantee future performance.
They are based on historical data only.
In live markets, additional factors exist:
Liquidity
Slippage
Fee structures
Exchange-specific liquidation rules
Funding fees, etc.
The liquidation price is only an approximate estimate, derived from a simplified formula.
Actual liquidation rules, maintenance margin requirements, fees, and other details differ by exchange.
The liquidation line should be treated as a reference indicator, not an exact guarantee.
Depending on the configured leverage and entry percentages, losses can be very large.
In particular, extremely aggressive settings such as “first position 300% of equity” can greatly increase the risk of large account drawdowns and liquidation during sharp market crashes.
Use such settings with extreme caution.
For live trading, additional risk management is essential:
Your own stop-loss rules
Maximum position size limits
Portfolio-level exposure controls
And other external safety mechanisms beyond this strategy
9. Conclusion
The ATH Drawdown Re-Buy Long Only strategy goes beyond simple “buy the dip” logic. It:
Systematically utilizes drawdowns from ATH as a structural signal
Applies a special first-position rule (100% / 300%)
Integrates visualization of leverage, liquidation price, MDD, and returns
All of this supports rule-based long position building in drawdown phases and comprehensive risk monitoring.
With this strategy, users can:
Explore different:
Drawdown zones
Entry percentages
Leverage levels
Run various backtests and scenario analyses
Better understand the risk/return profile that fits their own market view and risk tolerance
Once again, this strategy is intended for research, learning, and backtesting only.
All real trading decisions and their consequences are solely the responsibility of the user.
LiquidityPulse — RSI + Candle Strength Momentum Reversal SuiteLiquidityPulse — RSI + Candle Strength Momentum Reversal Suite description:
Non-repainting indicator.
⚙️ First-time Setup – Make the Candles Visible
To see the custom candle colours correctly you must disable the chart’s own candle borders and wicks:
Right-click anywhere on your chart (or click the ⚙ gear icon) and choose Settings.
Open the Appearance tab → Candles section.
Untick both Body Borders and Wicks (or set their colours to 100 % transparent).
Click OK.
Without this step the platform’s default candle styling can hide the indicator’s dynamic candle fills.
Overview
This script merges price-action strength with momentum extremes to highlight potentially significant market turning points:
Candle Strength 1–10 – Every candle is graded on a ten-point scale based on body size and volume relative to recent averages. Strong bullish or bearish candles are colour-coded with one of five optional themes (Classic, Cool, Neon, Pastel or Abyss).
RSI Extremes Filter – A standard 14-period RSI monitors overbought and oversold levels.
Only when both a high-grade candle and an RSI extreme occur together does the script optionally plot an arrow to mark a potential reversal area.
How It Works
Each candle receives a bull or bear strength score (1–10) using an internal candle-strength scoring formula.
RSI is checked across a user-defined look-back window (default 2 bars).
Bull Arrow Marker – printed below the bar only when
Bull strength ≥ Min candle strength (default 8), and
RSI dips below the oversold level (default 30) within the look-back window.
Bear Arrow Marker – printed above the bar only when
Bear strength ≥ Min candle strength (default 8), and
RSI rises above the overbought level (default 70) within the look-back window.
These dual conditions make the arrows intentionally rare depending on the settings used, and are designed to highlight momentum conditions associated with potential turning points
How to Use It in Your Own Trading
Market Context First – Apply the indicator only after you have identified the broader trend or key support/resistance areas on higher time-frames.
Confirmation, Not Prediction – Use the arrows as a confirmation of potential exhaustion or reversal; they are not intended as stand-alone entry triggers.
Adjust to Your Style –
Short-term traders might reduce the “RSI look-back bars” to 1 for quicker but more frequent alerts.
Swing traders may raise the “Min candle strength” to 9 or 10 to focus only on the strongest setups.
Combine with Risk Management – Always confirm with your own stop-loss and position-sizing rules.
Why this indicator is useful:
Confluence – It joins price-action strength (candle/volume) with a classic momentum oscillator (RSI), reducing noise from using either method alone.
Visual Clarity – Dynamic candle colouring makes market strength visible at a glance; depending on the settings used, rare arrows can highlight potential reversal areas based on momentum conditions.
Flexibility – All parameters adapt to any market or timeframe.
Educational Value – It helps traders learn how momentum extremes and candle strength interact—valuable for both beginners and experienced traders.
Inputs – Default Values
Min candle strength: 8
RSI look-back bars: 2
Overbought level: 70
Oversold level: 30
Candle-Strength engine: look-back 50 bars, ATR length 14, Body ≥ 0.5×ATR, Volume floor 10 000, Sensitivity 2
Optional features: five colour themes, strength number labels, label background at 42 % opacity.
All settings can be modified to suit different markets and trading styles.
Alerts
Two built-in alert conditions:
Bull Candle-RSI Condition
Bear Candle-RSI Condition
These can trigger alerts when the conditions are met.
If you have any questions about the indicator just pop me a message, happy trading!
Disclaimer
This script is 100 % my own original work.
Trading and investing involve substantial risk and are not suitable for every investor.
This indicator is provided for educational and informational purposes only to assist individuals with their own market analysis.
It is not a buy or sell signal and should not be considered financial advice.
Use it only in conjunction with your own analysis and trade at your own risk.
Scout Regiment - Bias# Scout Regiment - Bias Indicator
## English Documentation
### Overview
Scout Regiment - Bias is a technical indicator that measures the deviation (bias) between the current price and exponential moving averages (EMAs). It helps traders identify overbought/oversold conditions, trend strength, and potential reversal points through divergence detection.
### What is Bias?
Bias measures how far the price has moved away from a moving average, expressed as a percentage:
- **Positive Bias**: Price is above the EMA (potential overbought)
- **Negative Bias**: Price is below the EMA (potential oversold)
- **Formula**: Bias = (Price - EMA) / EMA × 100
### Key Features
#### 1. **Triple EMA Bias Lines**
The indicator calculates bias from three different EMAs:
- **EMA 55 Bias** (Default: Green/Red, 1px line)
- Short-term bias measurement
- Quick response to price changes
- Best for intraday and swing trading
- **EMA 144 Bias** (Pink, 2px line)
- Medium-term bias measurement
- Balanced response to price movements
- Ideal for swing trading
- **EMA 233 Bias** (White, 2px line)
- Long-term bias measurement
- Slower response, more stable
- Best for position trading
**Color Coding:**
- Green: Price above EMA (bullish)
- Red: Price below EMA (bearish)
#### 2. **Visual Components**
**Histogram Display**
- Shows EMA 55 bias as a histogram for easy visualization
- Green bars: Price above EMA 55
- Red bars: Price below EMA 55
- Can be toggled on/off
**Background Color**
- Light green background: Bullish bias (price above EMA 55)
- Light red background: Bearish bias (price below EMA 55)
- Optional display for cleaner charts
**Zero Line**
- White horizontal line at 0%
- Reference point for positive/negative bias
- Crossovers indicate trend changes
**Crossover Labels**
- "突破" (Breakout): When bias crosses above zero
- "跌破" (Breakdown): When bias crosses below zero
- Can be enabled/disabled for clarity
#### 3. **Divergence Detection**
The indicator automatically detects regular divergences for all three bias lines:
**Bullish Divergence (Yellow Labels)**
- Price makes lower lows
- Bias makes higher lows
- Suggests potential upward reversal
- Labels: "55涨", "144涨", "233涨"
**Bearish Divergence (Blue Labels)**
- Price makes higher highs
- Bias makes lower highs
- Suggests potential downward reversal
- Labels: "55跌", "144跌", "233跌"
**Divergence Parameters** (Customizable for each EMA):
- Left Lookback: Bars to the left of pivot (default: 5)
- Right Lookback: Bars to the right of pivot (default: 1)
- Max Lookback Range: Maximum distance between pivots (default: 60)
- Min Lookback Range: Minimum distance between pivots (default: 5)
### Configuration Settings
#### Bias Settings
- **EMA Periods**: Customize lengths for EMA 55, 144, and 233
- **Price Source**: Choose calculation source (default: close)
- **Enable/Disable**: Toggle each bias line independently
#### Display Settings
- **Show Histogram**: Toggle histogram display
- **Show Background Color**: Toggle background coloring
- **Show Crossover Labels**: Toggle breakout/breakdown labels
#### Divergence Settings (Per EMA)
- Individual controls for EMA 55, 144, and 233 divergences
- Customizable lookback parameters for precision tuning
- Adjustable range settings for different market conditions
### How to Use
#### For Trend Trading
1. **Identify Trend Direction**
- Price above zero = Uptrend
- Price below zero = Downtrend
2. **Confirm with Multiple Timeframes**
- EMA 55: Short-term trend
- EMA 144: Medium-term trend
- EMA 233: Long-term trend
3. **Trade in Direction of Bias**
- All three lines positive = Strong uptrend
- All three lines negative = Strong downtrend
#### For Mean Reversion Trading
1. **Identify Extremes**
- High positive bias (>5-10%) = Overbought
- High negative bias (<-5 to -10%) = Oversold
2. **Wait for Confirmation**
- Look for bias to turn back toward zero
- Watch for crossover labels
3. **Enter on Reversal**
- Enter long when extreme negative bias starts rising
- Enter short when extreme positive bias starts falling
#### For Divergence Trading
1. **Spot Divergence Labels**
- Yellow labels = Bullish divergence (potential buy)
- Blue labels = Bearish divergence (potential sell)
2. **Confirm with Price Action**
- Wait for price to confirm with structure break
- Look for support/resistance reactions
3. **Use Multiple EMAs**
- EMA 55 divergence: Quick reversals
- EMA 144 divergence: Reliable signals
- EMA 233 divergence: Major trend changes
#### For Multi-Timeframe Analysis
1. **Check Long-term Bias** (EMA 233)
- Determines overall market direction
2. **Find Medium-term Entry** (EMA 144)
- Look for pullbacks in long-term trend
3. **Time Short-term Entry** (EMA 55)
- Enter when short-term aligns with longer timeframes
### Trading Strategies
#### Strategy 1: Triple Confirmation
- Wait for all three bias lines to be positive (or negative)
- Enter in direction of unanimous bias
- Exit when any line crosses zero
- Best for: Strong trending markets
#### Strategy 2: Divergence Trading
- Enable all divergence detection
- Take trades only when divergence appears
- Confirm with price structure
- Best for: Range-bound and reversal setups
#### Strategy 3: Zero Line Crossover
- Enable crossover labels
- Enter long on "突破" labels
- Enter short on "跌破" labels
- Use stop loss at recent swing points
- Best for: Trend following
#### Strategy 4: Extreme Reversion
- Wait for bias to reach extremes (>10% or <-10%)
- Enter counter-trend when bias reverses
- Exit at zero line
- Best for: Ranging markets
### Best Practices
1. **Combine with Price Action**
- Don't trade bias alone
- Confirm with support/resistance
- Look for candlestick patterns
2. **Use Multiple Timeframes**
- Check higher timeframe bias
- Trade in direction of larger trend
- Use lower timeframe for entry timing
3. **Manage Risk**
- Set stop losses beyond recent swings
- Don't fight extreme bias in strong trends
- Reduce position size at extremes
4. **Customize for Your Market**
- Volatile assets: Use wider ranges
- Stable assets: Use tighter ranges
- Adjust EMA periods for your timeframe
5. **Watch for False Signals**
- Multiple small divergences = Less reliable
- Divergences at extremes = More reliable
- Confirm with other indicators
### Indicator Combinations
**With Volume:**
- High bias + Low volume = Weak move
- High bias + High volume = Strong move
**With Moving Averages:**
- Check if price is above/below key EMAs
- Bias confirms EMA trend strength
**With RSI/MACD:**
- Multiple indicator divergence = Stronger signal
- Use bias for overbought/oversold confirmation
### Performance Tips
- Disable unused features for faster loading
- Use histogram for quick visual reference
- Enable background color for trend clarity
- Use divergence detection selectively
### Common Patterns
1. **Bias Expansion**: Bias increasing = Strong trend
2. **Bias Contraction**: Bias decreasing = Trend weakening
3. **Zero Line Bounce**: Price respects EMA as support/resistance
4. **Extreme Bias**: Over-extension, watch for reversal
5. **Divergence Cluster**: Multiple EMAs diverging = High probability reversal
### Alert Conditions
You can set alerts for:
- Bias crossing above/below zero
- Extreme bias levels
- Divergence detection
- All three bias lines aligned
---
## 中文说明文档
### 概述
Scout Regiment - Bias 是一个技术指标,用于测量当前价格与指数移动平均线(EMA)之间的偏离程度(乖离率)。它帮助交易者识别超买超卖状况、趋势强度,以及通过背离检测发现潜在的反转点。
### 什么是乖离率?
乖离率衡量价格偏离移动平均线的程度,以百分比表示:
- **正乖离**:价格高于EMA(可能超买)
- **负乖离**:价格低于EMA(可能超卖)
- **计算公式**:乖离率 = (价格 - EMA) / EMA × 100
### 核心功能
#### 1. **三重EMA乖离率线**
指标计算三条不同EMA的乖离率:
- **EMA 55 乖离率**(默认:绿色/红色,1像素线)
- 短期乖离测量
- 对价格变化反应快速
- 适合日内和波段交易
- **EMA 144 乖离率**(粉色,2像素线)
- 中期乖离测量
- 对价格波动反应平衡
- 最适合波段交易
- **EMA 233 乖离率**(白色,2像素线)
- 长期乖离测量
- 反应较慢,更稳定
- 适合仓位交易
**颜色编码:**
- 绿色:价格高于EMA(看涨)
- 红色:价格低于EMA(看跌)
#### 2. **视觉组件**
**柱状图显示**
- 以柱状图形式显示EMA 55乖离率,便于可视化
- 绿色柱:价格高于EMA 55
- 红色柱:价格低于EMA 55
- 可开关显示
**背景颜色**
- 浅绿色背景:看涨乖离(价格高于EMA 55)
- 浅红色背景:看跌乖离(价格低于EMA 55)
- 可选显示,图表更清爽
**零轴**
- 零点位置的白色横线
- 正负乖离的参考点
- 穿越表示趋势变化
**穿越标签**
- "突破":乖离率向上穿越零轴
- "跌破":乖离率向下穿越零轴
- 可启用/禁用以保持清晰
#### 3. **背离检测**
指标自动检测所有三条乖离率线的常规背离:
**看涨背离(黄色标签)**
- 价格创新低
- 乖离率创更高的低点
- 暗示潜在向上反转
- 标签:"55涨"、"144涨"、"233涨"
**看跌背离(蓝色标签)**
- 价格创新高
- 乖离率创更低的高点
- 暗示潜在向下反转
- 标签:"55跌"、"144跌"、"233跌"
**背离参数**(每个EMA可自定义):
- 左侧回溯:枢轴点左侧K线数(默认:5)
- 右侧回溯:枢轴点右侧K线数(默认:1)
- 最大回溯范围:枢轴点之间最大距离(默认:60)
- 最小回溯范围:枢轴点之间最小距离(默认:5)
### 配置设置
#### Bias设置
- **EMA周期**:自定义EMA 55、144和233的长度
- **价格源**:选择计算源(默认:收盘价)
- **启用/禁用**:独立切换每条乖离率线
#### 显示设置
- **显示柱状图**:切换柱状图显示
- **显示背景颜色**:切换背景着色
- **显示突破标签**:切换突破/跌破标签
#### 背离设置(按EMA)
- EMA 55、144和233背离的独立控制
- 可自定义回溯参数用于精确调整
- 可调整范围设置以适应不同市场状况
### 使用方法
#### 趋势交易
1. **识别趋势方向**
- 价格高于零 = 上升趋势
- 价格低于零 = 下降趋势
2. **多时间框架确认**
- EMA 55:短期趋势
- EMA 144:中期趋势
- EMA 233:长期趋势
3. **顺乖离方向交易**
- 三条线全部为正 = 强劲上升趋势
- 三条线全部为负 = 强劲下降趋势
#### 均值回归交易
1. **识别极值**
- 高正乖离(>5-10%)= 超买
- 高负乖离(<-5至-10%)= 超卖
2. **等待确认**
- 等待乖离率回归零轴
- 观察穿越标签
3. **在反转时进场**
- 极端负乖离开始上升时做多
- 极端正乖离开始下降时做空
#### 背离交易
1. **发现背离标签**
- 黄色标签 = 看涨背离(潜在买入)
- 蓝色标签 = 看跌背离(潜在卖出)
2. **用价格行为确认**
- 等待价格通过结构突破确认
- 观察支撑/阻力反应
3. **使用多个EMA**
- EMA 55背离:快速反转
- EMA 144背离:可靠信号
- EMA 233背离:重大趋势变化
#### 多时间框架分析
1. **检查长期乖离**(EMA 233)
- 确定整体市场方向
2. **寻找中期入场**(EMA 144)
- 在长期趋势中寻找回调
3. **把握短期入场时机**(EMA 55)
- 短期与长期时间框架一致时进场
### 交易策略
#### 策略1:三重确认
- 等待三条乖离率线全部为正(或负)
- 顺一致乖离方向入场
- 任一线穿越零轴时离场
- 适合:强趋势市场
#### 策略2:背离交易
- 启用所有背离检测
- 仅在出现背离时交易
- 用价格结构确认
- 适合:震荡和反转设置
#### 策略3:零轴穿越
- 启用穿越标签
- 在"突破"标签时做多
- 在"跌破"标签时做空
- 在近期波动点设置止损
- 适合:趋势跟随
#### 策略4:极值回归
- 等待乖离率达到极值(>10%或<-10%)
- 乖离率反转时逆趋势入场
- 在零轴离场
- 适合:震荡市场
### 最佳实践
1. **结合价格行为**
- 不要单独使用乖离率交易
- 用支撑/阻力确认
- 寻找K线形态
2. **使用多时间框架**
- 检查更高时间框架的乖离
- 顺大趋势方向交易
- 用低时间框架把握入场时机
3. **风险管理**
- 在近期波动之外设置止损
- 不要在强趋势中对抗极端乖离
- 在极值处减少仓位
4. **针对您的市场定制**
- 波动大的资产:使用更宽的范围
- 稳定的资产:使用更紧的范围
- 根据时间框架调整EMA周期
5. **警惕假信号**
- 多个小背离 = 可靠性较低
- 极值处的背离 = 更可靠
- 用其他指标确认
### 指标组合
**与成交量配合:**
- 高乖离 + 低成交量 = 弱势波动
- 高乖离 + 高成交量 = 强势波动
**与移动平均线配合:**
- 检查价格是否在关键EMA上方/下方
- 乖离率确认EMA趋势强度
**与RSI/MACD配合:**
- 多指标背离 = 更强信号
- 使用乖离率确认超买超卖
### 性能提示
- 禁用未使用的功能以加快加载
- 使用柱状图快速视觉参考
- 启用背景颜色以清晰显示趋势
- 有选择地使用背离检测
### 常见形态
1. **乖离扩张**:乖离率增大 = 强趋势
2. **乖离收缩**:乖离率减小 = 趋势减弱
3. **零轴反弹**:价格将EMA作为支撑/阻力
4. **极端乖离**:过度延伸,注意反转
5. **背离集群**:多个EMA背离 = 高概率反转
### 警报条件
您可以为以下情况设置警报:
- 乖离率向上/向下穿越零轴
- 极端乖离水平
- 背离检测
- 三条乖离率线对齐
---
## Technical Support
For questions or issues, please refer to the TradingView community or contact the indicator creator.
## 技术支持
如有问题,请参考TradingView社区或联系指标创建者。
CNN Fear and Greed StrategyAdaptation of the CNN Fear and Greed Index Indicator (Original by EdgeTools)
The following changes have been implemented:
Put/Call Ratio Data Source: The data source for the Put/Call Ratio has been updated.
Bond Data Source: The data sources for the bond components (Safe Haven Demand and Junk Bond Demand) have been updated.
Normalization Adjustment: The normalization method has been adjusted to allow the CNN Fear and Greed Index to display over a longer historical period, optimizing it for backtesting purposes.
Style Modification: The display style has been modified for a simpler and cleaner appearance.
Strategy Logic Addition: Added a new strategy entry condition: index >= 25 AND index crosses over its 5-period Simple Moving Average (SMA), and a corresponding exit condition of holding the position for 252 bars (days).
CNN Fear & Greed Backtest Strategy (Adapted)
This script is an adaptation of the popular CNN Fear & Greed Index, originally created by EdgeTools, with significant modifications to optimize it for long-term backtesting on the TradingView platform.
The core function of the Fear & Greed Index is to measure the current emotional state of the stock market, ranging from 0 (Extreme Fear) to 100 (Extreme Greed). It operates on the principle that excessive fear drives prices too low (a potential buying opportunity), and excessive greed drives them too high (a potential selling opportunity).
Key Components of the Index (7 Factors)
The composite index is calculated as a weighted average of seven market indicators, each normalized to a score between 0 and 100:
Market Momentum: S&P 500's current level vs. its 125-day Moving Average.
Stock Price Strength: Stocks hitting 52-week highs vs. those hitting 52-week lows.
Stock Price Breadth: Measured by the McClellan Volume Summation Index (or similar volume/breadth metric).
Put/Call Ratio: The relationship between volume of put options (bearish bets) and call options (bullish bets).
Market Volatility: The CBOE VIX Index relative to its 50-day Moving Average.
Safe Haven Demand: The relative performance of stocks (S&P 500) vs. bonds.
Junk Bond Demand: The spread between high-yield (junk) bonds and U.S. Treasury yields.
Critical Adaptations for Backtesting
To improve the index's utility for quantitative analysis, the following changes were made:
Long-Term Normalization: The original normalization method (ta.stdev over a short LENGTH) has been replaced or adjusted to use longer historical data. This change ensures the index generates consistent and comparable sentiment scores across decades of market history, which is crucial for reliable backtesting results.
Updated Data Sources: Specific ticker requests for the Put/Call Ratio and Bond components (Safe Haven and Junk Bond Demand) have been updated to use the most reliable and long-running data available on TradingView, reducing data gaps and improving chart continuity.
Simplified Visuals: The chart display is streamlined, focusing only on the final Fear & Greed Index line and key threshold levels (25, 50, 75) for quick visual assessment.
Integrated Trading Strategy
This script also includes a simple, rules-based strategy designed to test the counter-trend philosophy of the index:
Entry Logic (Long Position): A long position is initiated when the market shows increasing fear, specifically when the index score is less than or equal to the configurable FEAR_LEVEL (default 25) and the index crosses above its own short-term 5-period Simple Moving Average (SMA). This crossover acts as a confirmation that sentiment may be starting to turn around from peak fear.
Exit Logic (Time-Based): All positions are subject to a time-based exit after holding for 252 trading days (approximately one year). This fixed holding period aims to capture the typical duration of a cyclical market recovery following a major panic event.
VIX Counter-Trend StrategyVIX Panic Index VOO Bottom-Fishing Strategy
📊 Strategy Overview
This strategy utilizes the VIX (Volatility Index) as a market sentiment indicator to help investors rationally enter positions during periods of extreme market panic, using objective technical signals to avoid emotional decision-making. It is designed to capture rebound opportunities in VOO (or other US equity ETFs) following panic-driven selloffs.
🎯 Entry and Exit Conditions
Entry Conditions (both must be met):
VIX reaches or exceeds the set threshold (default 25, adjustable)
VIX death crosses below its moving average (default 5-day MA), confirming panic sentiment is beginning to recede
Exit Conditions (three modes available):
Holding Period Mode: Exit after holding for the set number of days (default 100 days)
VIX Decline Mode: Exit when VIX falls below the set threshold (default 20)
Either Condition Mode: Exit when either condition is met
⚠️ Important Warnings
Not Suitable for Leveraged ETF Bottom-Fishing: VIX reflects market volatility. Using leveraged ETFs (such as TQQQ, SOXL) increases risk due to decay effects and greater volatility, potentially causing larger losses during panic periods.
Bear Market Inaccuracy Risk: This strategy assumes markets will rebound from panic. However, during prolonged bear markets or systemic risks (such as the 2008 financial crisis or 2022 rate hike cycle), VIX may remain elevated for extended periods, triggering multiple buy signals while prices continue declining, rendering the strategy ineffective.
Recommended to Combine with Market Trend Analysis: Works better in bull market conditions. In bear markets, consider raising VIX thresholds or suspending use.
For Reference Only, Not Investment Advice: Historical performance does not guarantee future results. Please use cautiously according to your personal risk tolerance.
VIX 恐慌指數 VOO 抄底策略
📊 策略目的
本策略利用 VIX 恐慌指數作為市場情緒指標,幫助投資人在市場極度恐慌時理性進場抄底,並透過客觀的技術訊號避免情緒化操作。適合用於捕捉 VOO(或其他美股 ETF)在恐慌性下跌後的反彈機會。
🎯 進出場條件
進場條件(同時滿足):
VIX 指數達到設定門檻以上(預設 25,可調整)
VIX 死亡交叉其均線(預設 5 日均線),確認恐慌情緒開始回落
出場條件(三種模式可選):
持有天數模式:持有達到設定天數後出場(預設 100 天)
VIX 回落模式:VIX 降至設定門檻以下時出場(預設 20)
兩者皆可模式:任一條件滿足即出場
⚠️ 重要警語
不適合槓桿型 ETF 抄底:VIX 反映的是市場波動度,使用槓桿 ETF(如 TQQQ、SOXL)會因為衰減效應和更大波動而增加風險,可能在恐慌期間造成更大虧損。
空頭市場失準風險:本策略假設市場會從恐慌中反彈,但在長期空頭或系統性風險(如 2008 金融危機、2022 升息循環)中,VIX 可能長期處於高檔,多次觸發買入訊號卻持續下跌,導致策略失效。
建議搭配大盤趨勢判斷:在多頭格局中使用效果較佳,空頭格局建議提高 VIX 門檻或暫停使用。
僅供參考,非投資建議:歷史績效不代表未來表現,請依個人風險承受度謹慎使用。
RSI VWAP EMA ON CHART1. Understand the components
VWAP (Volume Weighted Average Price)
Green: price is above VWAP → bullish trend
Red: price is below VWAP → bearish trend
Blue: price exactly at VWAP → neutral
Acts as a dynamic trend line and support/resistance.
4 Moving Averages (MA1–MA4)
Customizable lengths and type (SMA or EMA).
Useful for trend confirmation and dynamic support/resistance.
Typically:
MA1 = fastest (short-term)
MA4 = slowest (long-term)
When price is above multiple MAs → strong bullish trend; below → bearish trend.
RSI Overlay with VWAP Alignment
RSI line normalized to price scale.
Background shading indicates momentum aligned with VWAP trend:
Green shading: RSI > 50 and price above VWAP → bullish momentum
Red shading: RSI < 50 and price below VWAP → bearish momentum
Gray areas: neutral or momentum does not align with VWAP.
2. Basic usage workflow
Trend Confirmation
Look at VWAP color: price above → bullish, below → bearish.
Check RSI + VWAP shading: green confirms bullish momentum, red confirms bearish momentum.
Check MA alignment: shorter MAs above longer MAs = stronger bullish trend; vice versa for bearish.
Entry Signals (Scalping)
Long (Buy) Setup
Price above VWAP (green)
RSI green shading (RSI > 50)
Shorter MAs above longer MAs (trend support)
Short (Sell) Setup
Price below VWAP (red)
RSI red shading (RSI < 50)
Shorter MAs below longer MAs
Exits / Stops
Exit if price closes against VWAP trend (e.g., price drops below VWAP during a bullish trade).
Use nearest MA support/resistance as stop-loss or take-profit zones.
3. Optional adjustments for scalping
RSI length / thresholds
Shorter RSI (7–10) → faster response for scalping.
Standard RSI (14) → smoother, fewer false signals.
MA lengths
Short-term: 20–50
Medium-term: 50–100
Long-term: 100–200
Can tweak for the timeframe you trade (1m, 5m, 15m).
Timeframe
VWAP works best on intraday charts (1m, 5m, 15m).
Use higher timeframe (e.g., 15m or 1h) for trend direction and lower timeframe (1m–5m) for entries.
4. Example Scalping Setup
Bullish setup (buy):
Price above VWAP → VWAP green
RSI > 50 and green shading
Shorter MAs above longer MAs
Enter on small pullback or breakout
Stop: below nearest MA or VWAP
Bearish setup (sell):
Price below VWAP → VWAP red
RSI < 50 and red shading
Shorter MAs below longer MAs
Enter on minor bounce or breakdown
Stop: above nearest MA or VWAP
5. Visual cues summary
Element Interpretation
VWAP Green Price above VWAP → bullish trend
VWAP Red Price below VWAP → bearish trend
RSI Green Shading Bullish momentum aligns with VWAP
RSI Red Shading Bearish momentum aligns with VWAP
MA Alignment Trend strength (short above long = bullish, short below long = bearish)
VWAP + 4 MAs with RSI Overlay & VWAP Alignment1. Understand the components
VWAP (Volume Weighted Average Price)
Green: price is above VWAP → bullish trend
Red: price is below VWAP → bearish trend
Blue: price exactly at VWAP → neutral
Acts as a dynamic trend line and support/resistance.
4 Moving Averages (MA1–MA4)
Customizable lengths and type (SMA or EMA).
Useful for trend confirmation and dynamic support/resistance.
Typically:
MA1 = fastest (short-term)
MA4 = slowest (long-term)
When price is above multiple MAs → strong bullish trend; below → bearish trend.
RSI Overlay with VWAP Alignment
RSI line normalized to price scale.
Background shading indicates momentum aligned with VWAP trend:
Green shading: RSI > 50 and price above VWAP → bullish momentum
Red shading: RSI < 50 and price below VWAP → bearish momentum
Gray areas: neutral or momentum does not align with VWAP.
2. Basic usage workflow
Trend Confirmation
Look at VWAP color: price above → bullish, below → bearish.
Check RSI + VWAP shading: green confirms bullish momentum, red confirms bearish momentum.
Check MA alignment: shorter MAs above longer MAs = stronger bullish trend; vice versa for bearish.
Entry Signals (Scalping)
Long (Buy) Setup
Price above VWAP (green)
RSI green shading (RSI > 50)
Shorter MAs above longer MAs (trend support)
Short (Sell) Setup
Price below VWAP (red)
RSI red shading (RSI < 50)
Shorter MAs below longer MAs
Exits / Stops
Exit if price closes against VWAP trend (e.g., price drops below VWAP during a bullish trade).
Use nearest MA support/resistance as stop-loss or take-profit zones.
3. Optional adjustments for scalping
RSI length / thresholds
Shorter RSI (7–10) → faster response for scalping.
Standard RSI (14) → smoother, fewer false signals.
MA lengths
Short-term: 20–50
Medium-term: 50–100
Long-term: 100–200
Can tweak for the timeframe you trade (1m, 5m, 15m).
Timeframe
VWAP works best on intraday charts (1m, 5m, 15m).
Use higher timeframe (e.g., 15m or 1h) for trend direction and lower timeframe (1m–5m) for entries.
4. Example Scalping Setup
Bullish setup (buy):
Price above VWAP → VWAP green
RSI > 50 and green shading
Shorter MAs above longer MAs
Enter on small pullback or breakout
Stop: below nearest MA or VWAP
Bearish setup (sell):
Price below VWAP → VWAP red
RSI < 50 and red shading
Shorter MAs below longer MAs
Enter on minor bounce or breakdown
Stop: above nearest MA or VWAP
5. Visual cues summary
Element Interpretation
VWAP Green Price above VWAP → bullish trend
VWAP Red Price below VWAP → bearish trend
RSI Green Shading Bullish momentum aligns with VWAP
RSI Red Shading Bearish momentum aligns with VWAP
MA Alignment Trend strength (short above long = bullish, short below long = bearish)
HH/HL/LH/LL - Bigger Letter MArkingAlam's Money
//@version=6
indicator("HH/HL/LH/LL - Clean Letters Only", overlay = true, max_labels_count = 500)
// Pivot confirmation bars (fixed)
L = 2
R = 2
// Confirmed pivots (appear R bars after turn)
sh = ta.pivothigh(high, L, R)
sl = ta.pivotlow(low, L, R)
// Keep last confirmed swing values
var float lastHigh = na
var float lastLow = na
// Swing highs → HH / LH
if not na(sh)
if na(lastHigh)
lastHigh := sh
else
string txtH = sh > lastHigh ? "HH" : "LH"
label.new(bar_index - R, sh, txtH, xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_down, color.red, size.large)
lastHigh := sh
// Swing lows → HL / LL
if not na(sl)
if na(lastLow)
lastLow := sl
else
string txtL = sl > lastLow ? "HL" : "LL"
label.new(bar_index - R, sl, txtL, xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_up, color.green, size.large)
lastLow := sl
Smart Margin Zone
SMART MARGIN ZONE - CME-BASED SUPPORT & RESISTANCE INDICATOR
TITLE FOR PUBLICATION:
Smart Margin Zone - CME Margin-Based Support and Resistance
CATEGORY:
Support and Resistance
SHORT DESCRIPTION (for preview):
Automatically plots margin zones based on CME Group requirements. These zones represent critical price levels where leveraged traders face margin calls, creating natural support and resistance through forced liquidations.
═══════════════════════════════════════════════════════════════
FULL DESCRIPTION FOR TRADINGVIEW:
═══════════════════════════════════════════════════════════════
📊 Smart Margin Zone - Professional Trading Zones Based on CME Data
This indicator automatically calculates and displays margin zones derived from official CME Group margin requirements. These zones represent critical price levels where traders using leverage receive margin calls, triggering forced position closures that create natural support and resistance levels.
═══════════════════════════════════════════════════════════════
🎯 CORE CONCEPT
═══════════════════════════════════════════════════════════════
When price reaches calculated margin zones, traders using 2:1 or 4:1 leverage on CME futures receive margin calls. Brokers automatically liquidate these positions, creating waves of buying or selling pressure that form strong support and resistance levels.
This is not theoretical - it's based on actual margin requirements from CME Group, the world's largest derivatives marketplace.
═══════════════════════════════════════════════════════════════
📐 CALCULATION METHODOLOGY
═══════════════════════════════════════════════════════════════
The indicator uses the following formula to calculate zone sizes:
Zone Size = (Margin Requirement / Tick Value) × Tick Size × 1.10
Where:
• Margin Requirement = Official CME initial margin (updated November 2024)
• Tick Value = Dollar value of minimum price movement
• Tick Size = Minimum price increment
• 1.10 = 10% buffer for realistic zone width
SUPPORTED INSTRUMENTS WITH CME DATA:
Currency Pairs:
• EURUSD: $2,100 margin → 0.0168 zone size
• GBPUSD: $1,800 margin → 0.0144 zone size
• AUDUSD: $1,300 margin → 0.0065 zone size
• NZDUSD: $1,100 margin → 0.0055 zone size
• USDJPY: $3,200 margin → custom calculation
• USDCAD: $950 margin → calculated
• USDCHF: $1,650 margin → calculated
Commodities:
• Gold (XAUUSD): $8,000 margin → 80 points zone size
• Silver (XAGUSD): $6,500 margin → calculated
• WTI Crude Oil: $4,500 margin → calculated
═══════════════════════════════════════════════════════════════
🔍 HOW IT WORKS
═══════════════════════════════════════════════════════════════
1. SWING POINT DETECTION
The indicator automatically identifies swing highs and swing lows using a configurable lookback period (default 10 bars). These become anchor points for zone calculations.
2. FIVE ZONE LEVELS
From each swing point, five zone levels are calculated:
• Zone 1/4 (25%) - First correction level
• Zone 1/2 (50%) - KEY ZONE for trend determination
• Zone 3/4 (75%) - Intermediate level
• Zone 1/1 (100%) - Full margin zone (strongest level)
• Zone 5/4 (125%) - Extended zone
3. TREND IDENTIFICATION
• Close above Zone 1/2 resistance = Bullish trend
• Close below Zone 1/2 support = Bearish trend
• Between zones = Range/consolidation
4. HISTORICAL CONTEXT
Current zones are displayed prominently with fills and labels. Historical zones appear as thin, semi-transparent lines for context without cluttering the chart.
═══════════════════════════════════════════════════════════════
⚙️ FEATURES
═══════════════════════════════════════════════════════════════
AUTOMATED CALCULATION:
✅ Auto-detection of swing highs and lows
✅ Real-time zone updates as new swings form
✅ CME margin data built-in for major instruments
✅ Manual override option for custom calculations
VISUAL CLARITY:
✅ Color-coded zones (red=resistance, green=support)
✅ Adjustable transparency for fills and lines
✅ Current zones bold with fills and price labels
✅ Historical zones thin and transparent
✅ Swing point markers show calculation origins
CUSTOMIZATION:
✅ Show/hide individual zone levels (1/4, 1/2, 3/4, 1/1, 5/4)
✅ Toggle historical zones on/off
✅ Adjustable lookback period (5-50 bars)
✅ Customizable colors for all elements
✅ Line width and transparency controls
✅ Zone extension options (none/right/both)
TREND ANALYSIS:
✅ Optional trend background coloring
✅ Customizable trend colors and transparency
✅ Real-time trend identification display
STATISTICS:
✅ Live statistics table showing:
- Current instrument
- Active zone size
- Calculation mode
- Current trend direction
- Number of zones displayed
ALERTS:
✅ Zone 1/2 breakout (up/down)
✅ Full margin zone 1/1 reached
✅ Customizable alert messages
═══════════════════════════════════════════════════════════════
📈 TRADING APPLICATIONS
═══════════════════════════════════════════════════════════════
ENTRY SIGNALS:
• Bounces from zone levels = potential entry points
• Zone 1/2 breakouts = trend continuation entries
• Zone rejections = reversal opportunities
RISK MANAGEMENT:
• Zone levels = logical stop-loss placement
• Zone 1/1 = maximum risk level
• Zone spacing = position sizing guide
PROFIT TARGETS:
• Next zone level = first target
• Zone 1/1 = full profit target
• Zone breakouts = extended targets
TREND CONFIRMATION:
• Price above Zone 1/2 resistance = confirmed uptrend
• Price below Zone 1/2 support = confirmed downtrend
• Consolidation between zones = wait for breakout
═══════════════════════════════════════════════════════════════
📚 USAGE INSTRUCTIONS
═══════════════════════════════════════════════════════════════
GETTING STARTED:
1. Add indicator to chart of any supported instrument
2. Zones automatically calculate and display
3. Adjust swing detection period if needed (default 10 works well)
4. Customize colors and visibility to your preference
OPTIMAL SETTINGS:
• Best timeframes: H1, H4, Daily, Weekly
• Default swing length (10) suitable for most markets
• Show 2-3 historical zones for context
• Enable swing point markers to see calculation origins
INTERPRETATION:
• Watch for price reactions at zone boundaries
• Strong bounces = respect for margin level
• Clean breaks = momentum continuation
• Multiple touches = zone strength confirmation
SET ALERTS:
• Zone 1/2 breakouts for trend entries
• Zone 1/1 reaches for profit-taking
• Custom alerts for your specific strategy
═══════════════════════════════════════════════════════════════
⚠️ IMPORTANT NOTES
═══════════════════════════════════════════════════════════════
DATA ACCURACY:
• CME margin requirements updated November 2024
• Margins change periodically - check CME Group website
• Manual mode available for latest margin data
• Indicator provides analysis tool, not financial advice
STATISTICAL PERFORMANCE:
• Historical data shows >60% probability of continued movement after Zone 1/2 breakout
• Zone effectiveness varies by market conditions
• Best results in trending markets with clear swings
LIMITATIONS:
• Margin requirements change - monitor CME updates
• Works best on liquid instruments with clear swings
• Not a standalone trading system
• Should be combined with additional analysis
═══════════════════════════════════════════════════════════════
🔧 METHODOLOGY CREDIT
═══════════════════════════════════════════════════════════════
This indicator is based on the margin zones concept developed by Alexander Bazylev (BTrade indicator for MetaTrader platforms).
The TradingView implementation has been completely rewritten with original enhancements:
• Multiple zone levels instead of single level
• Automatic swing point detection algorithm
• Direct CME data integration
• Historical zone visualization
• Advanced customization options
• Comprehensive statistics and alerts
All code is original and specifically designed for TradingView's Pine Script v5 environment.
═══════════════════════════════════════════════════════════════
💡 BEST PRACTICES
═══════════════════════════════════════════════════════════════
COMBINE WITH:
• Volume analysis for confirmation
• Trend indicators for direction bias
• Price action patterns at zones
• Higher timeframe analysis
AVOID:
• Trading against strong trends at minor zones
• Over-leveraging based solely on zone placement
• Ignoring broader market context
• Expecting perfect bounces every time
OPTIMIZE:
• Adjust swing length for different timeframes
• Shorter period (5-7) for intraday trading
• Longer period (15-20) for swing trading
• Test historical effectiveness on your instruments
═══════════════════════════════════════════════════════════════
📖 EDUCATIONAL VALUE
═══════════════════════════════════════════════════════════════
This indicator helps traders understand:
• How institutional margin requirements affect price
• Where forced liquidations create pressure
• Natural support and resistance formation
• Relationship between leverage and price levels
• Market structure and key technical levels
═══════════════════════════════════════════════════════════════
🔄 VERSION HISTORY
═══════════════════════════════════════════════════════════════
Version 1.0 (Initial Release):
• CME-based zone calculation for 10 instruments
• Automatic swing high/low detection
• 5 zone levels with customizable display
• Historical zones with transparency control
• Swing point markers
• Trend background indicator
• Live statistics table
• Multiple alert conditions
• Fully customizable colors and styles
• English language interface
═══════════════════════════════════════════════════════════════
📞 SUPPORT & FEEDBACK
═══════════════════════════════════════════════════════════════
Questions or suggestions? Leave a comment below!
If you find this indicator useful:
⭐ Please leave a like
💬 Share your experience in comments
🔔 Follow for updates and new indicators
═══════════════════════════════════════════════════════════════
⚖️ DISCLAIMER
═══════════════════════════════════════════════════════════════
This indicator is provided for educational and analytical purposes only. It is not financial advice and should not be the sole basis for trading decisions.
• Past performance does not guarantee future results
• Trading involves substantial risk of loss
• CME margin requirements subject to change
• Always do your own research and risk management
• Consult a financial advisor for investment advice
The creator is not responsible for any trading losses incurred through use of this indicator.
Dresteghamat-Multi timeframe Regime & Exhaustion**Dresteghamat-Multi timeframe Regime & Exhaustion**
This script is a custom decision-support dashboard that aggregates volatility, momentum, and structural data across multiple timeframes to filter market noise. It addresses the problem of "Analysis Paralysis" by automating the correlation between lower timeframe momentum and higher timeframe structure using a weighted scoring algorithm.
### 🔧 Methodology & Calculation Logic
The core engine does not simply overlay indicators; it normalizes their outputs into a unified score (-100 to +100). The logic is hidden (Protected) to preserve the proprietary weighting algorithm, but the underlying concepts are as follows:
**1. Adaptive Timeframe Selection (Context Engine)**
Instead of static monitoring, the script detects the user's current chart timeframe (`timeframe.multiplier`) and dynamically assigns two relevant Higher Timeframes (HTF) as anchors.
* *Logic:* If Current TF < 5min, the script analyzes 15m and 1H data. If Current TF < 1H, it shifts to 4H and Daily data. This ensures the analysis is contextually relevant.
**2. Regime & Volatility Filter (ATR Based)**
We use the Average True Range (ATR) to determine the market regime (Trend vs. Range).
* **Calculation:** We compare the current Swing Range (High-Low lookback) against a smoothed ATR. A high Ratio (> 2.0) indicates a Trend Regime, activating Trend-Following logic. A low ratio dampens the signals.
**3. Directional Bias (Structure + Flow)**
Direction is not determined by a single crossover. It is a fusion of:
* **Swing Structure:** Using `ta.pivothigh/low` to identify Higher Highs/Lower Lows.
* **Volume Flow:** Calculating the cumulative delta of candle bodies over a lookback period.
* **Micro-Bias:** A short-term (default 5-bar) momentum filter to detect immediate order flow changes.
**4. Exhaustion Logic (Mean Reversion Warning)**
To prevent buying at tops, the script calculates an "Exhaustion Score" based on:
* **RSI Divergence:** Detecting discrepancies between price peaks and momentum.
* **Volatility Extension:** Identifying when price has deviated significantly from its volatility mean (VRSD logic).
* **Volume Anomalies:** Detecting low volume on new highs (Supply absorption).
### 📊 How to Read the Dashboard
The table displays the raw status of each timeframe. The **"MODE"** row is the output of the algorithmic decision tree:
* **BUY/SELL ONLY:** Generated when the Current TF momentum aligns with the dynamically selected HTF structure AND the Exhaustion Score is below the threshold (default 70).
* **PULLBACK:** Triggered when the HTF Structure is bullish, but Current Momentum is bearish (indicating a corrective phase).
* **HTF EXHAUST:** A safety warning triggered when the HTF Volatility or RSI metrics hit extreme levels, overriding any entry signals.
* **WAIT:** Default state when volatility is low (Range Regime) or signals conflict.
### ⚠️ Disclaimer
This tool provides algorithmic analysis based on historical price action and volatility metrics. It does not guarantee future results.
NormalizedIndicatorsNormalizedIndicators - Comprehensive Trend Normalization Library
Overview
This Pine Script™ library provides an extensive collection of normalized trend-following indicators and calculation functions for technical analysis. The main advantage of this library lies in its unified signal output: All trend indicators are normalized to a standardized format where 1 represents a bullish signal, -1 represents a bearish signal, and 0 (where applicable) represents a neutral signal.
This normalization enables traders to seamlessly combine different indicators, create consensus signals, and develop complex multi-indicator strategies without worrying about different scales and interpretations.
📊 Categories
The library is divided into two main categories:
1. Trend-Following Indicators
2. Calculation Indicators
🔄 Trend-Following Indicators
Stationary Indicators
These oscillate around a fixed value and are not bound to price.
BBPct() - Bollinger Bands Percent
Source: Algoalpha X Sushiboi77
Parameters:
Length: Period for Bollinger Bands
Factor: Standard deviation multiplier
Source: Price source (typical: close)
Logic: Calculates the position of price within the Bollinger Bands as a percentage
Signal:
1 (bullish): when positionBetweenBands > 50
-1 (bearish): when positionBetweenBands ≤ 50
Special Feature: Uses an array to store historical standard deviations for additional analysis
RSI() - Relative Strength Index
Source: TradingView
Parameters:
len: RSI period
src: Price source
smaLen: Smoothing period for RSI
Logic: Classic RSI with additional SMA smoothing
Signal:
1 (bullish): RSI-SMA > 50
-1 (bearish): RSI-SMA < 50
0 (neutral): RSI-SMA = 50
Non-Stationary Indicators
These follow price movement and have no fixed boundaries.
NorosTrendRibbonSMA() & NorosTrendRibbonEMA()
Source: ROBO_Trading
Parameters:
Length: Moving average and channel period
Source: Price source
Logic: Creates a price channel based on the highest/lowest MA value over a specified period
Signal:
1 (bullish): Price breaks above upper band
-1 (bearish): Price breaks below lower band
0 (neutral): Price within channel (maintains last state)
Difference: SMA version uses simple moving averages, EMA version uses exponential
TrendBands()
Source: starlord_xrp
Parameters: src (price source)
Logic: Uses 12 EMAs (9-30 period) and checks if all are rising or falling simultaneously
Signal:
1 (bullish): All 12 EMAs are rising
-1 (bearish): All 12 EMAs are falling
0 (neutral): Mixed signals
Special Feature: Very strict conditions - extremely strong trend filter
Vidya() - Variable Index Dynamic Average
Source: loxx
Parameters:
source: Price source
length: Main period
histLength: Historical period for volatility calculation
Logic: Adaptive moving average that adjusts to volatility
Signal:
1 (bullish): VIDYA is rising
-1 (bearish): VIDYA is falling
VZO() - Volume Zone Oscillator
Parameters:
source: Price source
length: Smoothing period
volumesource: Volume data source
Logic: Combines price and volume direction, calculates the ratio of directional volume to total volume
Signal:
1 (bullish): VZO > 14.9
-1 (bearish): VZO < -14.9
0 (neutral): VZO between -14.9 and 14.9
TrendContinuation()
Source: AlgoAlpha
Parameters:
malen: First HMA period
malen1: Second HMA period
theclose: Price source
Logic: Uses two Hull Moving Averages for trend assessment with neutrality detection
Signal:
1 (bullish): Uptrend without divergence
-1 (bearish): Downtrend without divergence
0 (neutral): Trend and longer MA diverge
LeonidasTrendFollowingSystem()
Source: LeonidasCrypto
Parameters:
src: Price source
shortlen: Short EMA period
keylen: Long EMA period
Logic: Simple dual EMA crossover system
Signal:
1 (bullish): Short EMA < Key EMA
-1 (bearish): Short EMA ≥ Key EMA
ysanturtrendfollower()
Source: ysantur
Parameters:
src: Price source
depth: Depth of Fibonacci weighting
smooth: Smoothing period
bias: Percentage bias adjustment
Logic: Complex system with Fibonacci-weighted moving averages and bias bands
Signal:
1 (bullish): Weighted MA > smoothed MA (with upward bias)
-1 (bearish): Weighted MA < smoothed MA (with downward bias)
0 (neutral): Within bias zone
TRAMA() - Trend Regularity Adaptive Moving Average
Source: LuxAlgo
Parameters:
src: Price source
length: Adaptation period
Logic: Adapts to trend regularity - accelerates in stable trends, slows in consolidations
Signal:
1 (bullish): Price > TRAMA
-1 (bearish): Price < TRAMA
0 (neutral): Price = TRAMA
HullSuite()
Source: InSilico
Parameters:
_length: Base period
src: Price source
_lengthMult: Length multiplier
Logic: Uses Hull Moving Average with lagged comparisons for trend determination
Signal:
1 (bullish): Current Hull > Hull 2 bars ago
-1 (bearish): Current Hull < Hull 2 bars ago
0 (neutral): No change
STC() - Schaff Trend Cycle
Source: shayankm (described as "Better MACD")
Parameters:
length: Cycle period
fastLength: Fast MACD period
slowLength: Slow MACD period
src: Price source
Logic: Combines MACD concepts with stochastic normalization for early trend signals
Signal:
1 (bullish): STC is rising
-1 (bearish): STC is falling
🧮 Calculation Indicators
These functions provide specialized mathematical calculations for advanced analysis.
LCorrelation() - Long-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (30, 60, 90, 120, 150, 180)
Returns: Correlation value between -1 and 1
Application: Long-term relationship analysis between assets, markets, or indicators
MCorrelation() - Medium-term Correlation
Creator: unicorpusstocks
Parameters:
Input: First time series
Compare: Second time series
Logic: Calculates the average of correlations across 6 different periods (15, 30, 45, 60, 75, 90)
Returns: Correlation value between -1 and 1
Application: Medium-term relationship analysis with higher sensitivity
assetBeta() - Beta Coefficient
Creator: unicorpusstocks
Parameters:
measuredSymbol: The asset to be measured
baseSymbol: The reference asset (e.g., market index)
Logic:
Calculates Beta across 4 different time horizons (50, 100, 150, 200 periods)
Beta = Correlation × (Asset Standard Deviation / Market Standard Deviation)
Returns the average of all 4 Beta values
Returns: Beta value (typically 0-2, can be higher/lower)
Interpretation:
Beta = 1: Asset moves in sync with the market
Beta > 1: Asset more volatile than market
Beta < 1: Asset less volatile than market
Beta < 0: Asset moves inversely to the market
💡 Usage Examples
Example 1: Multi-Indicator Consensus
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
// Combine multiple indicators
signal1 = lib.BBPct(20, 2.0, close)
signal2 = lib.RSI(14, close, 5)
signal3 = lib.TRAMA(close, 50)
// Consensus signal: At least 2 of 3 must agree
consensus = (signal1 + signal2 + signal3)
strongBuy = consensus >= 2
strongSell = consensus <= -2
Example 2: Correlation-Filtered Trading
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
// Only trade when strong correlation with market exists
spy = request.security("SPY", timeframe.period, close)
correlation = lib.MCorrelation(close, spy)
trendSignal = lib.NorosTrendRibbonEMA(50, close)
// Only bullish signals with positive correlation
tradeBuy = trendSignal == 1 and correlation > 0.5
tradeSell = trendSignal == -1 and correlation > 0.5
Example 3: Beta-Adjusted Position Sizing
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1 as lib
spy = request.security("SPY", timeframe.period, close)
beta = lib.assetBeta(close, spy)
// Adjust position size based on Beta
basePositionSize = 100
adjustedSize = basePositionSize / beta // Less size with high Beta
⚙️ Technical Details
Normalization Standard
Bullish: 1
Bearish: -1
Neutral: 0 (only for selected indicators)
Advantages of Normalization
Simple Aggregation: Signals can be added/averaged
Consistent Interpretation: No confusion about different scales
Strategy Development: Simplified logic for backtesting
Combinability: Seamlessly mix different indicator types
Performance Considerations
All functions are optimized for Pine Script v5
Proper use of var for state management
Efficient array operations where needed
Minimal recursive calls
📋 License
This code is subject to the Mozilla Public License 2.0. More details at: mozilla.org
🎯 Use Cases
This library is ideal for:
Quantitative Traders: Systematic strategy development with unified signals
Multi-Timeframe Analysis: Consensus across different timeframes
Portfolio Managers: Beta and correlation analysis for diversification
Algo Traders: Machine learning with standardized features
Retail Traders: Simplified signal interpretation without deep technical knowledge
🔧 Installation
pinescriptimport unicorpusstocks/MyIndicatorLibrary/1
Then use the functions with your chosen alias:
pinescriptlib.BBPct(20, 2.0, close)
lib.RSI(14, close, 5)
// etc.
⚠️ Important Notes
All indicators are lagging, as is typical for trend-following indicators
Signals should be combined with additional analysis (volume, support/resistance, etc.)
Backtesting is recommended before starting live trading with these signals
Different assets and timeframes may require different parameter optimizations
This library provides a solid foundation for professional trading system design with the flexibility to develop your own complex strategies while abstracting away technical complexity.
Sentiment Heatmap with EMA Sentiment Heatmap with EMA Let’s build a script mini-LuxAlgo-style sentiment heatmap Enhanced Simple Sentiment Heatmap + Right-Side Legend Automatic legend on the right side
Just like professional indicators:
MAX GREED
GREED
NEUTRAL
FEAR
MAX FEAR
✔ Legend stays updated on the last bar
It moves automatically as price moves.
✔ Trend EMA included (optional) 9 EMA → White
20 EMA → Red
50 EMA → Yellow
100 EMA → Blue
200 EMA → Purple Alerts (e.g., “Max Fear – Buy Zone”)
✔ Liquidity line / support-resistance auto zones Full sentiment heatmap (Greed → Fear)
✔ Right-side legend like LuxAlgo
✔ All 5 EMAs added (my colors): EMA trend cloud (9/20, 20/50, 50/200)
Buy/Sell circles based on sentiment reversals Right-side legend: MAX GREED / GREED / NEUTRAL / FEAR / MAX FEAR
5 EMAs:
9 → White
20 → Red
50 → Yellow
100 → Blue
200 → Purple
Sav Fx Dynamic P & D°//@version=5
indicator("Sav Fx Dynamic P & D°", overlay = true, max_boxes_count = 50, max_labels_count = 2, max_lines_count = 10)
// Global Settings (visible)
customLineColor = input.color(#000000, "True Open", group = "Global Settings")
// Input for custom sessionTypeText size and width
sessionTypeTextSize = input.string("small", "Session Type Text Size", options= , group="Text Settings")
// On/Off switches for each open line
show90MinuteCycleOpen = input.bool(true, "90 Minute Cycle Open", group="Open Lines")
showTrueNewYorkOpen = input.bool(true, "True New York Open", group="Open Lines")
showTrueDayOpen = input.bool(true, "True Day Open", group="Open Lines")
showTrueWeekOpen = input.bool(true, "True Week Open", group="Open Lines")
showTrueMonthOpen = input.bool(false, "True Month Open", group="Open Lines")
IsTime(h, m, timezone) =>
not na(time) and hour(time, timezone) == h and minute(time, timezone) == m
IsSession(sess, timezone) =>
not na(time(timeframe.period, sess, timezone))
is6_00Session = IsSession("0600-0730", "America/New_York")
is7_30Session = IsSession("0730-0900", "America/New_York")
is9_00Session = IsSession("0900-1030", "America/New_York")
is10_30Session = IsSession("1030-1200", "America/New_York")
var MOPLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var MOPLabel = label.new(na, na, text = "True Day Open", color = color.rgb(120, 123, 134, 100), textcolor = customLineColor, size = size.small, style = label.style_label_left)
var float trueDayOpen = na
if showTrueDayOpen
if IsTime(0, 0, "America/New_York")
line.set_xy1(MOPLine, bar_index, open)
line.set_xy2(MOPLine, bar_index, open)
label.set_xy(MOPLabel, bar_index, open)
trueDayOpen := open
if barstate.islast
line.set_x2(MOPLine, bar_index + 20)
label.set_x(MOPLabel, bar_index + 20)
else
line.delete(MOPLine)
label.delete(MOPLabel)
var NYTrueOpenLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var NYTrueOpenLabel = label.new(na, na, text = "True New York Open", color = color.rgb(105, 130, 218, 100), textcolor = customLineColor, size = size.small, style = label.style_label_left)
var float NYTrueOpen = na
if showTrueNewYorkOpen
if IsTime(1, 30, "America/New_York") or IsTime(7, 30, "America/New_York") or IsTime(13, 30, "America/New_York")
line.set_xy1(NYTrueOpenLine, bar_index, open)
line.set_xy2(NYTrueOpenLine, bar_index, open)
label.set_xy(NYTrueOpenLabel, bar_index, open)
NYTrueOpen := open
if IsTime(1, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True London Open")
if IsTime(7, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True New York Open")
if IsTime(13, 30, "America/New_York")
label.set_text(NYTrueOpenLabel, "True PM Session Open")
if barstate.islast
line.set_x2(NYTrueOpenLine, bar_index + 20)
label.set_x(NYTrueOpenLabel, bar_index + 20)
else
line.delete(NYTrueOpenLine)
label.delete(NYTrueOpenLabel)
var lookahead_bars = 20
var MondayLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var MondayLabel = label.new(na, na, text = timeframe.isintraday and timeframe.multiplier >= 5 ? "True week Open" : "", color = #9b27b000, textcolor = customLineColor, size = size.small, style = label.style_label_left)
if showTrueWeekOpen
if dayofweek == dayofweek.monday and IsTime(18, 0, "America/New_York")
line.set_xy1(MondayLine, bar_index, close)
line.set_xy2(MondayLine, bar_index, close)
label.set_xy(MondayLabel, bar_index, close)
if barstate.islast
line.set_x2(MondayLine, bar_index + lookahead_bars)
label.set_x(MondayLabel, bar_index + lookahead_bars)
else
line.delete(MondayLine)
label.delete(MondayLabel)
var ninetyMinuteCycleLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var ninetyMinuteCycleLabel = label.new(na, na, text = "90 Minute Cycle True Open", color = #4caf4f00, textcolor = customLineColor, size = size.small, style = label.style_label_left)
if show90MinuteCycleOpen
if IsTime(3, 23, "America/New_York") or IsTime(9, 23, "America/New_York") or IsTime(15, 23, "America/New_York")
line.set_xy1(ninetyMinuteCycleLine, bar_index, open)
line.set_xy2(ninetyMinuteCycleLine, bar_index, open)
label.set_xy(ninetyMinuteCycleLabel, bar_index, open)
if IsTime(3, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "03:23 Cycle True Open")
if IsTime(9, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "09:23 Cycle True Open")
if IsTime(15, 23, "America/New_York")
label.set_text(ninetyMinuteCycleLabel, "15:23 Cycle True Open")
if barstate.islast
line.set_x2(ninetyMinuteCycleLine, bar_index + lookahead_bars)
label.set_x(ninetyMinuteCycleLabel, bar_index + lookahead_bars)
else
line.delete(ninetyMinuteCycleLine)
label.delete(ninetyMinuteCycleLabel)
var monthOpenLine = line.new(na, na, na, na, color = customLineColor, width = 1, style = line.style_dashed)
var monthOpenLabel = label.new(na, na, text = "True Month Open", color = #ff990000, textcolor = customLineColor, size = size.small, style = label.style_label_left)
isSecondWeekSunday = dayofweek == dayofweek.sunday and (dayofmonth >= 8 and dayofmonth <= 14)
if showTrueMonthOpen
if isSecondWeekSunday and IsTime(18,0, "America/New_York")
line.set_xy1(monthOpenLine, bar_index, close)
line.set_xy2(monthOpenLine, bar_index + lookahead_bars, close)
label.set_xy(monthOpenLabel, bar_index, close)
if barstate.islast
line.set_x2(monthOpenLine, bar_index + lookahead_bars)
label.set_x(monthOpenLabel, bar_index + lookahead_bars)
else
line.delete(monthOpenLine)
label.delete(monthOpenLabel)
directionalBias = "N/A"
if is6_00Session or is7_30Session or is9_00Session or is10_30Session
directionalBias := open > NYTrueOpen ? "Bullish" : "Bearish"
var directionalBiasLabel = label.new(na, na, text = "Directional Bias: " + directionalBias, color = na, textcolor = customLineColor, size = size.normal, style = label.style_label_left)
if barstate.islast
label.set_x(directionalBiasLabel, bar_index + lookahead_bars)
label.set_text(directionalBiasLabel, "Directional Bias: " + directionalBias)
var float WeekOpen = na
if dayofweek == dayofweek.monday and IsTime(18, 0, "America/New_York")
WeekOpen := close
if showTrueWeekOpen
line.set_xy1(MondayLine, bar_index, close)
line.set_xy2(MondayLine, bar_index, close)
label.set_xy(MondayLabel, bar_index, close)
// New table for static session type display
var sessionTable = table.new(position.bottom_right, 1, 1, bgcolor = #b9b9bab8)
// Update the table.cell function call
if barstate.islast and not na(trueDayOpen) and not na(NYTrueOpen) and not na(WeekOpen)
var string sessionTypeText = syminfo.ticker + " Dead Zone"
var color sessionColor = color.rgb(126, 126, 126, 65)
// Check conditions and set session type text and color accordingly
if close < trueDayOpen and close < NYTrueOpen and close < WeekOpen
sessionTypeText := syminfo.ticker + " Week Discount"
sessionColor := #ba4b4b59
else if close > trueDayOpen and close > NYTrueOpen and close > WeekOpen
sessionTypeText := syminfo.ticker + " Week Premium"
sessionColor := #4b56ba5a
else if close < trueDayOpen and close < NYTrueOpen and close > WeekOpen
sessionTypeText := syminfo.ticker + " Day Discount & Week Dead Zone"
sessionColor := #ba4b4b59
else if close > trueDayOpen and close > NYTrueOpen and close < WeekOpen
sessionTypeText := syminfo.ticker + " Day premium & Week Dead Zone"
sessionColor := #4b56ba5a
// Using only size input for session type text
table.cell(sessionTable, 0, 0, sessionTypeText, bgcolor = sessionColor, text_color = color.black, text_size = sessionTypeTextSize)
SP500 Session Gap Fade StrategySummary in one paragraph
SPX Session Gap Fade is an intraday gap fade strategy for index futures, designed around regular cash sessions on five minute charts. It helps you participate only when there is a full overnight or pre session gap and a valid intraday session window, instead of trading every open. The original part is the gap distance engine which anchors both stop and optional target to the previous session reference close at a configurable flat time, so every trade’s risk scales with the actual gap size rather than a fixed tick stop.
Scope and intent
• Markets. Primarily index futures such as ES, NQ, YM, and liquid index CFDs that exhibit overnight gaps and regular cash hours.
• Timeframes. Intraday timeframes from one minute to fifteen minutes. Default usage is five minute bars.
• Default demo used in the publication. Symbol CME:ES1! on a five minute chart.
• Purpose. Provide a simple, transparent way to trade opening gaps with a session anchored risk model and forced flat exit so you are not holding into the last part of the session.
• Limits. This is a strategy. Orders are simulated on standard candles only.
Originality and usefulness
• Unique concept or fusion. The core novelty is the combination of a strict “full gap” entry condition with a session anchored reference close and a gap distance based TP and SL engine. The stop and optional target are symmetric multiples of the actual gap distance from the previous session’s flat close, rather than fixed ticks.
• Failure mode it addresses. Fixed sized stops do not scale when gaps are unusually small or unusually large, which can either under risk or over risk the account. The session flat logic also reduces the chance of holding residual positions into late session liquidity and news.
• Testability. All key pieces are explicit in the Inputs: session window, minutes before session end, whether to use gap exits, whether TP or SL are active, and whether to allow candle based closes and forced flat. You can toggle each component and see how it changes entries and exits.
• Portable yardstick. The main unit is the absolute price gap between the entry bar open and the previous session reference close. tp_mult and sl_mult are multiples of that gap, which makes the risk model portable across contracts and volatility regimes.
Method overview in plain language
The strategy first defines a trading session using exchange time, for example 08:30 to 15:30 for ES day hours. It also defines a “flat” time a fixed number of minutes before session end. At the flat bar, any open position is closed and the bar’s close price is stored as the reference close for the next session. Inside the session, the strategy looks for a full gap bar relative to the prior bar: a gap down where today’s high is below yesterday’s low, or a gap up where today’s low is above yesterday’s high. A full gap down generates a long entry; a full gap up generates a short entry. If the gap risk engine is enabled and a valid reference close exists, the strategy measures the distance between the entry bar open and that reference close. It then sets a stop and optional target as configurable multiples of that gap distance and manages them with strategy.exit. Additional exits can be triggered by a candle color flip or by the forced flat time.
Base measures
• Range basis. The main unit is the absolute difference between the current entry bar open and the stored reference close from the previous session flat bar. That value is used as a “gap unit” and scaled by tp_mult and sl_mult to build the target and stop.
Components
• Component one: Gap Direction. Detects full gap up or full gap down by comparing the current high and low to the previous bar’s high and low. Gap down signals a long fade, gap up signals a short fade. There is no smoothing; it is a strict structural condition.
• Component two: Session Window. Only allows entries when the current time is within the configured session window. It also defines a flat time before the session end where positions are forced flat and the reference close is updated.
• Component three: Gap Distance Risk Engine. Computes the absolute distance between the entry open and the stored reference close. The stop and optional target are placed as entry ± gap_distance × multiplier so that risk scales with gap size.
• Optional component: Candle Exit. If enabled, a bullish bar closes short positions and a bearish bar closes long positions, which can shorten holding time when price reverses quickly inside the session.
• Session windows. Session logic uses the exchange time of the chart symbol. When changing symbols or venues, verify that the session time string still matches the new instrument’s cash hours.
Fusion rule
All gates are hard conditions rather than weighted scores. A trade can only open if the session window is active and the full gap condition is true. The gap distance engine only activates if a valid reference close exists and use_gap_risk is on. TP and SL are controlled by separate booleans so you can use SL only, TP only, or both. Long and short are symmetric by construction: long trades fade full gap downs, short trades fade full gap ups with mirrored TP and SL logic.
Signal rule
• Long entry. Inside the active session, when the current bar shows a full gap down relative to the previous bar (current high below prior low), the strategy opens a long position. If the gap risk engine is active, it places a gap based stop below the entry and an optional target above it.
• Short entry. Inside the active session, when the current bar shows a full gap up relative to the previous bar (current low above prior high), the strategy opens a short position. If the gap risk engine is active, it places a gap based stop above the entry and an optional target below it.
• Forced flat. At the configured flat time before session end, any open position is closed and the close price of that bar becomes the new reference close for the following session.
• Candle based exit. If enabled, a bearish bar closes longs, and a bullish bar closes shorts, regardless of where TP or SL sit, as long as a position is open.
What you will see on the chart
• Markers on entry bars. Standard strategy entry markers labeled “long” and “short” on the gap bars where trades open.
• Exit markers. Standard exit markers on bars where either the gap stop or target are hit, or where a candle exit or forced flat close occurs. Exit IDs “long_gap” and “short_gap” label gap based exits.
• Reference levels. Horizontal lines for the current long TP, long SL, short TP, and short SL while a position is open and the gap engine is enabled. They update when a new trade opens and disappear when flat.
• Session background. This version does not add background shading for the session; session logic runs internally based on time.
• No on chart table. All decisions are visible through orders and exit levels. Use the Strategy Tester for performance metrics.
Inputs with guidance
Session Settings
• Trading session (sess). Session window in exchange time. Typical value uses the regular cash session for each contract, for example “0830-1530” for ES. Adjust if your broker or symbol uses different hours.
• Minutes before session end to force exit (flat_before_min). Minutes before the session end where positions are forced flat and the reference close is stored. Typical range is 15 to 120. Raising it closes trades earlier in the day; lowering it allows trades later in the session.
Gap Risk
• Enable gap based TP/SL (use_gap_risk). Master switch for the gap distance exit engine. Turning it off keeps entries and forced flat logic but removes automatic TP and SL placement.
• Use TP limit from gap (use_gap_tp). Enables gap based profit targets. Typical values are true for structured exits or false if you want to manage exits manually and only keep a stop.
• Use SL stop from gap (use_gap_sl). Enables gap based stop losses. This should normally remain true so that each trade has a defined initial risk in ticks.
• TP multiplier of gap distance (tp_mult). Multiplier applied to the gap distance for the target. Typical range is 0.5 to 2.0. Raising it places the target further away and reduces hit frequency.
• SL multiplier of gap distance (sl_mult). Multiplier applied to the gap distance for the stop. Typical range is 0.5 to 2.0. Raising it widens the stop and increases risk per trade; lowering it tightens the stop and may increase the number of small losses.
Exit Controls
• Exit with candle logic (use_candle_exit). If true, closes shorts on bullish candles and longs on bearish candles. Useful when you want to react to intraday reversal bars even if TP or SL have not been reached.
• Force flat before session end (use_forced_flat). If true, guarantees you are flat by the configured flat time and updates the reference close. Turn this off only if you understand the impact on overnight risk.
Filters
There is no separate trend or volatility filter in this version. All trades depend on the presence of a full gap bar inside the session. If you need extra filtering such as ATR, volume, or higher timeframe bias, they should be added explicitly and documented in your own fork.
Usage recipes
Intraday conservative gap fade
• Timeframe. Five minute chart on ES regular session.
• Gap risk. use_gap_risk = true, use_gap_tp = true, use_gap_sl = true.
• Multipliers. tp_mult around 0.7 to 1.0 and sl_mult around 1.0.
• Exits. use_candle_exit = false, use_forced_flat = true. Focus on the structured TP and SL around the gap.
Intraday aggressive gap fade
• Timeframe. Five minute chart.
• Gap risk. use_gap_risk = true, use_gap_tp = false, use_gap_sl = true.
• Multipliers. sl_mult around 0.7 to 1.0.
• Exits. use_candle_exit = true, use_forced_flat = true. Entries fade full gaps, stops are tight, and candle color flips flatten trades early.
Higher timeframe gap tests
• Timeframe. Fifteen minute or sixty minute charts on instruments with regular gaps.
• Gap risk. Keep use_gap_risk = true. Consider slightly higher sl_mult if gaps are structurally wider on the higher timeframe.
• Note. Expect fewer trades and be careful with sample size; multi year data is recommended.
Properties visible in this publication
• On average our risk for each position over the last 200 trades is 0.4% with a max intraday loss of 1.5% of the total equity in this case of 100k $ with 1 contract ES. For other assets, recalculations and customizations has to be applied.
• Initial capital. 100 000.
• Base currency. USD.
• Default order size method. Fixed with size 1 contract.
• Pyramiding. 0.
• Commission. Flat 2 USD per order in the Strategy Tester Properties. (2$ buying + 2$selling)
• Slippage. One tick in the Strategy Tester Properties.
• Process orders on close. ON.
Realism and responsible publication
• No performance claims are made. Past results do not guarantee future outcomes.
• Costs use a realistic flat commission and one tick of slippage per trade for ES class futures.
• Default sizing with one contract on a 100 000 reference account targets modest per trade risk. In practice, extreme slippage or gap through events can exceed this, so treat the one and a half percent risk target as a design goal, not a guarantee.
• All orders are simulated on standard candles. Shapes can move while a bar is forming and settle on bar close.
Honest limitations and failure modes
• Economic releases, thin liquidity, and limit conditions can break the assumptions behind the simple gap model and lead to slippage or skipped fills.
• Symbols with very frequent or very large gaps may require adjusted multipliers or alternative risk handling, especially in high volatility regimes.
• Very quiet periods without clean gaps will produce few or no trades. This is expected behavior, not a bug.
• Session windows follow the exchange time of the chart. Always confirm that the configured session matches the symbol.
• When both the stop and target lie inside the same bar’s range, the TradingView engine decides which is hit first based on its internal intrabar assumptions. Without bar magnifier, tie handling is approximate.
Legal
Education and research only. This strategy is not investment advice. You remain responsible for all trading decisions. Always test on historical data and in simulation with realistic costs before considering any live use.
Multi EMA + Golden Trio Crossover (Bullish & Bearish) by SKL📌 Multi EMA + Golden Trio Crossover (Bullish & Bearish) — by SKL
This indicator plots six key Exponential Moving Averages (EMA 5, 13, 26, 50, 100, 200) and highlights powerful momentum shift signals through the Golden Trio Crossover — a unique setup where EMA 5 crosses both EMA 13 and EMA 26 in the same candle .
It works for both bullish and bearish conditions, making it suitable for intraday, swing, and positional trading.
🔍 What is the Golden Trio Crossover?
A Golden Trio Crossover occurs when:
Bullish: EMA 5 crosses ** above ** EMA 13 *and* EMA 26 in the same candle
Bearish: EMA 5 crosses ** below ** EMA 13 *and* EMA 26 in the same candle
This triple-confirmation crossover often signals:
Early trend reversals
Strong continuation breakouts
Momentum shift points
📈 What This Indicator Includes
1. Six EMA Lines
EMA 5 – Blue
EMA 13 – Green
EMA 26 – Orange
EMA 50 – Black
EMA 100 – Gray
EMA 200 – Red
These EMAs help traders track trend direction, strength, and structure.
🌟 Visual Highlights
Green background → Bullish Golden Trio
Red background → Bearish Golden Trio
Label markers on each signal
“BULL GCO”
“BEAR GCO”
🔔 Alerts Included
You can enable alerts for:
Bullish Golden Trio Crossover
Bearish Golden Trio Crossover
Useful for breakout traders, scalpers, and swing traders.
🎯 How Traders Use This Indicator
Identify early trend shifts
Spot high-probability breakout candles
Confirm entries with multi-EMA confluence
Combine with volume, price action, or RSI for even stronger setups
📌 Notes
Works on all timeframes
Works on all asset classes (Stocks, Indices, Crypto, Forex, Commodities)
Fully automatic signal detection
Frequency Momentum Oscillator [QuantAlgo]🟢 Overview
The Frequency Momentum Oscillator applies Fourier-based spectral analysis principles to price action to identify regime shifts and directional momentum. It calculates Fourier coefficients for selected harmonic frequencies on detrended price data, then measures the distribution of power across low, mid, and high frequency bands to distinguish between persistent directional trends and transient market noise. This approach provides traders with a quantitative framework for assessing whether current price action represents meaningful momentum or merely random fluctuations, enabling more informed entry and exit decisions across various asset classes and timeframes.
🟢 How It Works
The calculation process removes the dominant trend from price data by subtracting a simple moving average, isolating cyclical components for frequency analysis:
detrendedPrice = close - ta.sma(close , frequencyPeriod)
The detrended price series undergoes frequency decomposition through Fourier coefficient calculation across the first 8 harmonics. For each harmonic frequency, the algorithm computes sine and cosine components across the lookback window, then derives power as the sum of squared coefficients:
for k = 1 to 8
cosSum = 0.0
sinSum = 0.0
for n = 0 to frequencyPeriod - 1
angle = 2 * math.pi * k * n / frequencyPeriod
cosSum := cosSum + detrendedPrice * math.cos(angle)
sinSum := sinSum + detrendedPrice * math.sin(angle)
power = (cosSum * cosSum + sinSum * sinSum) / frequencyPeriod
Power measurements are aggregated into three frequency bands: low frequencies (harmonics 1-2) capturing persistent cycles, mid frequencies (harmonics 3-4), and high frequencies (harmonics 5-8) representing noise. Each band's power normalizes against total spectral power to create percentage distributions:
lowFreqNorm = totalPower > 0 ? (lowFreqPower / totalPower) * 100 : 33.33
highFreqNorm = totalPower > 0 ? (highFreqPower / totalPower) * 100 : 33.33
The normalized frequency components undergo exponential smoothing before calculating spectral balance as the difference between low and high frequency power:
smoothLow = ta.ema(lowFreqNorm, smoothingPeriod)
smoothHigh = ta.ema(highFreqNorm, smoothingPeriod)
spectralBalance = smoothLow - smoothHigh
Spectral balance combines with price momentum through directional multiplication, producing a composite signal that integrates frequency characteristics with price direction:
momentum = ta.change(close , frequencyPeriod/2)
compositeSignal = spectralBalance * math.sign(momentum)
finalSignal = ta.ema(compositeSignal, smoothingPeriod)
The final signal oscillates around zero, with positive values indicating low-frequency dominance coupled with upward momentum (trending up), and negative values indicating either high-frequency dominance (choppy market) or downward momentum (trending down).
🟢 How to Use This Indicator
→ Long/Short Signals: the indicator generates long signals when the smoothed composite signal crosses above zero (indicating low-frequency directional strength dominates) and short signals when it crosses below zero (indicating bearish momentum persistence).
→ Upper and Lower Reference Lines: the +25 and -25 reference lines serve as threshold markers for momentum strength. Readings beyond these levels indicate strong directional conviction, while oscillations between them suggest consolidation or weakening momentum. These references help traders distinguish between strong trending regimes and choppy transitional periods.
→ Preconfigured Presets: three optimized configurations are available with Default (32, 3) offering balanced responsiveness, Fast Response (24, 2) designed for scalping and intraday trading, and Smooth Trend (40, 5) calibrated for swing trading and position trading with enhanced noise filtration.
→ Built-in Alerts: the indicator includes three alert conditions for automated monitoring - Long Signal (momentum shifts bullish), Short Signal (momentum shifts bearish), and Signal Change (any directional transition). These alerts enable traders to receive real-time notifications without continuous chart monitoring.
→ Color Customization: four visual themes (Classic green/red, Aqua blue/orange, Cosmic aqua/purple, Custom) allow chart customization for different display environments and personal preferences.






















