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.
Portfolio Management
Kill Zone GridCaca Poo-Poo Kill Zone (12pm–4pm) — Avoid the Death Hours
This indicator highlights the worst trading window of the day — the midday chop zone where liquidity dies, algo volume disappears, spreads widen, and your account slowly bleeds out from boredom and paper cuts.
From 12pm to 4pm (New York Time) the script:
• Shades the background with a bold kill-zone color
• Adds red gridline stripes to visually scream “STOP TRADING, YOU DONKEY”
• Makes the entire chart look hostile so you avoid revenge trading, boredom trading, and all forms of midday stupidity
Perfect for scalpers and trend traders who only want the clean morning moves and want a visual reminder to step away, go outside, touch grass, eat lunch, or hit the gym instead of forcing trades in garbage hours.
If you trade futures, options, or zero-day anything — this script will save you money, sanity, and years off your life.
Mini Checklist (Left-side, static)It's a mini checklist on the left side of the chart serving as a note for when you trade.
Pretty simple
calculator contracts MNQ PIPEGAVTRADESThis is a Risk Management indicator that calculates the exact contracts to trade based on your defined Max Risk ($) and Stop Loss Ticks.
It displays all key Position Sizing metrics (including Account Capital and Risk %) in a fixed table on the chart.
Troll Dominance (TROLL.d)For all the trolls. The most famous og meme to exist 5UUH9RTDiSpq6HKS6bp4NdU9PNJpXRXuiw6ShBTBhgH2
This Chart shows you Trolls market cap relative to the top 100 memecoins.
Golden Cross 50/200 EMATrend-following systems are characterized by having a low win rate, yet in the right circumstances (trending markets and higher timeframes) they can deliver returns that even surpass those of systems with a high win rate.
Below, I show you a simple bullish trend-following system with clear execution rules:
System Rules
-Long entries when the 50-period EMA crosses above the 200-period EMA.
-Stop Loss (SL) placed at the lowest low of the 15 candles prior to the entry candle.
-Take Profit (TP) triggered when the 50-period EMA crosses below the 200-period EMA.
Risk Management
-Initial capital: $10,000
-Position size: 10% of capital per trade
-Commissions: 0.1% per trade
Important Note:
In the code, the stop loss is defined using the swing low (15 candles), but the position size is not adjusted based on the distance to the stop loss. In other words, 10% of the equity is risked on each trade, but the actual loss on the trade is not controlled by a maximum fixed percentage of the account — it depends entirely on the stop loss level. This means the loss on a single trade could be significantly higher or lower than 10% of the account equity, depending on volatility.
Implementing leverage or reducing position size based on volatility is something I haven’t been able to include in the code, but it would dramatically improve the system’s performance. It would fix a consistent percentage loss per trade, preventing losses from fluctuating wildly with changes in volatility.
For example, we can maintain a fixed loss percentage when volatility is low by using the following formula:
Leverage = % of SL you’re willing to risk / % volatility from entry point to stop loss
And when volatility is high and would exceed the fixed percentage we want to expose per trade (if the SL is hit), we could reduce the position size accordingly.
Practical example:
Imagine we only want to risk 15% of the position value if the stop loss is triggered on Tesla (which has high volatility), but the distance to the SL represents a potential 23.57% drop. In this case, we subtract the desired risk (15%) from the actual volatility-based loss (23.57%):
23.57% − 15% = 8.57%
Now suppose we normally use $200 per trade.
To calculate 8.57% of $200:
200 × (8.57 / 100) = $17.14
Then subtract that amount from the original position size:
$200 − $17.14 = $182.86
In summary:
If we reduce the position size to $182.86 (instead of the usual $200), even if Tesla moves 23.57% against us and hits the stop loss, we would still only lose approximately 15% of the original $200 position — exactly the risk level we defined. This way, we strictly respect our risk management rules regardless of volatility swings.
I hope this clearly explains the importance of capping losses at a fixed percentage per trade. This keeps risk under control while maintaining a consistent percentage of capital invested per trade — preventing both statistical distortion of the system and the potential destruction of the account.
About the code:
Strategy declaration:
The strategy is named 'Golden Cross 50/200 EMA'.
overlay=true means it will be drawn directly on the price chart.
initial_capital=10000 sets the initial capital to $10,000.
default_qty_type=strategy.percent_of_equity and default_qty_value=10 means each trade uses 10% of available equity.
margin_long=0 indicates no margin is used for long positions (this is likely for simulation purposes only; in real trading, margin would be required).
commission_type=strategy.commission.percent and commission_value=0.1 sets a 0.1% commission per trade.
Indicators:
Calculates two EMAs: a 50-period EMA (ema50) and a 200-period EMA (ema200).
Crossover detection:
bullCross is triggered when the 50-period EMA crosses above the 200-period EMA (Golden Cross).
bearCross is triggered when the 50-period EMA crosses below the 200-period EMA (Death Cross).
Recent swing:
swingLow calculates the lowest low of the previous 15 periods.
Stop Loss:
entryStopLoss is a variable initialized as na (not available) and is updated to the current swingLow value whenever a bullCross occurs.
Entry and exit conditions:
Entry: When a bullCross occurs, the initial stop loss is set to the current swingLow and a long position is opened.
Exit on opposite signal: When a bearCross occurs, the long position is closed.
Exit on stop loss: If the price falls below entryStopLoss while a position is open, the position is closed.
Visualization:
Both EMAs are plotted (50-period in blue, 200-period in red).
Green triangles are plotted below the bar on a bullCross, and red triangles above the bar on a bearCross.
A horizontal orange line is drawn that shows the stop loss level whenever a position is open.
Alerts:
Alerts are created for:Long entry
Exit on bearish crossover (Death Cross)
Exit triggered by stop loss
Favorable Conditions:
Tesla (45-minute timeframe)
June 29, 2010 – November 17, 2025
Total net profit: $12,458.73 or +124.59%
Maximum drawdown: $1,210.40 or 8.29%
Total trades: 107
Winning trades: 27.10% (29/107)
Profit factor: 3.141
Tesla (1-hour timeframe)
June 29, 2010 – November 17, 2025
Total net profit: $7,681.83 or +76.82%
Maximum drawdown: $993.36 or 7.30%
Total trades: 75
Winning trades: 29.33% (22/75)
Profit factor: 3.157
Netflix (45-minute timeframe)
May 23, 2002 – November 17, 2025
Total net profit: $11,380.73 or +113.81%
Maximum drawdown: $699.45 or 5.98%
Total trades: 134
Winning trades: 36.57% (49/134)
Profit factor: 2.885
Netflix (1-hour timeframe)
May 23, 2002 – November 17, 2025
Total net profit: $11,689.05 or +116.89%
Maximum drawdown: $844.55 or 7.24%
Total trades: 107
Winning trades: 37.38% (40/107)
Profit factor: 2.915
Netflix (2-hour timeframe)
May 23, 2002 – November 17, 2025
Total net profit: $12,807.71 or +128.10%
Maximum drawdown: $866.52 or 6.03%
Total trades: 56
Winning trades: 41.07% (23/56)
Profit factor: 3.891
Meta (45-minute timeframe)
May 18, 2012 – November 17, 2025
Total net profit: $2,370.02 or +23.70%
Maximum drawdown: $365.27 or 3.50%
Total trades: 83
Winning trades: 31.33% (26/83)
Profit factor: 2.419
Apple (45-minute timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $8,232.55 or +80.59%
Maximum drawdown: $581.11 or 3.16%
Total trades: 140
Winning trades: 34.29% (48/140)
Profit factor: 3.009
Apple (1-hour timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $9,685.89 or +94.93%
Maximum drawdown: $374.69 or 2.26%
Total trades: 118
Winning trades: 35.59% (42/118)
Profit factor: 3.463
Apple (2-hour timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $8,001.28 or +77.99%
Maximum drawdown: $755.84 or 7.56%
Total trades: 67
Winning trades: 41.79% (28/67)
Profit factor: 3.825
NVDA (15-minute timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $11,828.56 or +118.29%
Maximum drawdown: $1,275.43 or 8.06%
Total trades: 466
Winning trades: 28.11% (131/466)
Profit factor: 2.033
NVDA (30-minute timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $12,203.21 or +122.03%
Maximum drawdown: $1,661.86 or 10.35%
Total trades: 245
Winning trades: 28.98% (71/245)
Profit factor: 2.291
NVDA (45-minute timeframe)
January 3, 2000 – November 17, 2025
Total net profit: $16,793.48 or +167.93%
Maximum drawdown: $1,458.81 or 8.40%
Total trades: 172
Winning trades: 33.14% (57/172)
Profit factor: 2.927
Price Drop CounterThe Price Drop Counter is a very basic statistical indicator.
See it as an analytical tool that tracks how many times an asset's price has dropped by a specified percentage from its recent peak within a defined date range.
The indicator monitors the highest price reached and counts each occurrence when the price falls by your chosen threshold, then resets its peak tracking point after each drop is registered.
Uses
Volatility Assessment: Measure how frequently significant price corrections occur during specific periods
Market Behavior Analysis: Compare drop frequency across different timeframes or market conditions
Risk Evaluation: Identify assets or periods with higher downside volatility
Historical Pattern Recognition: Study how often major pullbacks happened during bull or bear markets
Backtesting Support: Analyze how your strategy would perform based on the frequency of drawdowns
How to use it
Add the indicator to your TradingView chart
Configure the Percent Drop (%) to define your threshold (default: 10%). The indicator will count each time price falls by this percentage from the most recent high
IMPORTANT Set your Start Date and End Date to analyze a specific period of interest
The blue step-line plot shows the cumulative count of drops within your date range
Adjust the percentage threshold based on your analysis needs - use smaller values (2-5%) for more frequent signals or larger values (15-20%) for major corrections only
The counter resets its high-water mark after each qualifying drop, allowing it to track multiple sequential drops within the same period.
Rendement périodes (finary compass)Rendement sur une période donnée,
Outil de décision pour stratégie Momentum
Net Liquidity (WALCL - TGA - ON RRP)//@version=5
indicator("Net Liquidity (WALCL - TGA - ON RRP)", overlay=false, timeframe="W")
a = request.security("FRED:WALCL", "W", close) // Fed total assets (millions)
b = request.security("FRED:WTREGEN", "W", close) // TGA (millions)
c = request.security("FRED:RRPONTSYD","W", close) // ON RRP (millions)
netliq = (a - b - c) / 1000.0 // billions
plot(netliq, color=color.new(color.blue, 0), linewidth=2)
ATR Risk Display - Multi FuturesWhat This Does
I got tired of manually calculating my ATR stops and risk for different futures contracts, especially when switching between ES, NQ, and their micro versions. This indicator automatically detects what futures symbol you're trading and shows you the exact tick count and dollar risk for your stop loss.
The Problem It Solves
If you trade futures with ATR-based stops, you know the hassle:
Different contracts have different tick values
You need to calculate position risk in dollars
Switching between symbols means redoing all the math
Renko charts make it even more confusing since ATR needs to come from regular candles
This handles all of that automatically.
Key Features
Auto-detects futures symbols - ES, NQ, YM, RTY, GC, CL, and all the micros (MES, MNQ, etc.)
Shows everything you need in one line: ATR(timeframe) × multiplier = X ticks ($XXX)
Works on Renko charts - pulls ATR from regular timeframe charts (super important if you use Renko)
Adjustable position sizing - set your contract count and see total risk instantly
Clean, minimal display - just the info you need, no clutter
How to Use
Add it to any futures chart
Set your preferred ATR timeframe (I use 5-minute)
Set your ATR multiplier (I use 1.5x for my stops)
Set your contract size
That's it - the indicator handles the rest
The display will show something like: "ES ATR(5) × 1.5 = 12 ticks ($150)"
Settings Explained
ATR Timeframe: What timeframe to calculate ATR from (always uses regular candles, even on Renko)
ATR Multiplier: How many ATRs for your stop (1.5 is common, 2.0 for wider stops)
Number of Contracts: Your position size for risk calculation
Auto-Detect Symbol: Leave on unless you want to manually override
Supported Futures
Full size: ES, NQ, YM, RTY, GC, CL, ZB, ZN, 6E, 6J
Micros: MES, MNQ, MYM, M2K, MGC, MCL
Notes
Made this primarily for my own ES trading but figured others might find it useful
The tick values are based on standard CME specs
If you trade other futures, you can modify the code to add them
Works great alongside level indicators for risk management
Why This Exists
I use ATR trailing stops on all my trades and got tired of doing mental math every time I switched between charts or contracts. Especially useful if you trade both full-size and micro contracts - the risk difference is huge and easy to mess up.
Hope this helps your trading! Feel free to suggest improvements.
BEMFUNDING MAX LOT CALCULATION (Sakince)You can use this indicator to ensure you don't exceed the "Maximum Lot" limit. Because the required data varies from pair to pair, you should obtain the latest information from the BEM Funding platform.
Checklist (D1 / H4 / M15/30 BoS / VP / Fibo / S/R) This is a simple, visual checklist indicator that allows you to quickly assess how many of your strategy conditions are met, without affecting the chart itself. It is ideal for multi-timeframe strategies and point-by-point setup monitoring.
Tactical Holding [SwissAlgo]Tactical Holding
A visual framework for managing long-term positions across market cycles
--------------------------------------------------------------
Purpose
Instead of holding a fixed position through all market conditions , you can use this framework to adjust your exposure tactically . By reducing positions during distribution phases and accumulating during favorable accumulation zones, you may end up holding more units of the asset over complete market cycles - even if you temporarily exit or reduce exposure during unfavorable periods. This approach aims to help you compound your holdings by taking advantage of market volatility rather than simply enduring it.
--------------------------------------------------------------
Recommended Settings
Timeframe : Weekly (1W) chart
Chart Type : Standard candlesticks (select 'Bar' type Candles)
This indicator is designed for higher timeframe analysis. While it can be applied to other timeframes, the logic and signal generation are optimized for weekly charts to filter out short-term noise and focus on major market cycles.
--------------------------------------------------------------
Key Features
♦ Market State Classification
The indicator aims to categorize potential market conditions into five color-coded states based on technical confluences:
* Bull (bright green): Multiple bullish indicators align
* Bull Retrace (teal): Bullish structure with temporary weakness
* Bull ⇆ Bear Reversal (yellow): Transitional phase between trends
* Bear (bright red): Multiple bearish indicators align
* Bear Retrace (Pale Red/Maroon): Bearish structure with temporary strength
♦ Visual Elements
* Candles change color based on the current market state
* A 50-period EMA tracks with the same color coding, providing visual trend context
* Small arrow markers appear when specific pattern conditions are met (zones for potential distribution or accumulation)
* A legend table (toggle on/off) explains the color system
* A label shows the current state name on the chart
♦ Pattern Recognition
The system monitors for two types of potential entry/exit zones:
1. State transition patterns after periods of market regime consistency
2. RSI divergence patterns (when price and momentum move in opposite directions)
♦ Customization
* Toggle the legend table visibility through settings
* All calculations are transparent and use standard technical analysis methods
--------------------------------------------------------------
How It Works
Think of this indicator as a traffic light system for your portfolio:
♦ Green zones suggest the asset might be in an environment where long-term holders historically have remained invested
Bright green (Bull) : Multiple technical indicators align in a potentially strong bullish phase
Pale green (Bull Retrace) : Bullish structure remains intact, but momentum shows temporary weakness - often a pullback within an uptrend
♦ Red zones suggest conditions where long-term holders might consider reducing exposure or waiting for better entry points
Dark red (Bear) : Multiple technical indicators align in a potentially strong bearish phase
Pale red (Bear Retrace) : Bearish structure remains intact but shows temporary strength - often a bounce within a downtrend
♦ Yellow zones indicate the market is in transition between bull and bear regimes - a time for increased attention as the trend direction becomes uncertain
The system doesn't predict future prices. Instead, it helps you understand the current technical environment by doing the heavy lifting of analyzing multiple indicators at once and presenting them in a simple visual format.
Example: During the 2022 crypto bear market, the indicator would have displayed extended red periods, signaling defensive conditions for holders. When accumulation arrows appeared in late 2022-early 2023, it highlighted potential re-entry zones as the technical regime transitioned back toward green, before the 2024 recovery.
--------------------------------------------------------------
Who This Is For
♦ Long-term investors who want to hold assets through cycles but prefer a systematic approach to position sizing and timing rather than buying and never selling .
♦ Portfolio managers looking for a visual tool to help determine when to increase or decrease exposure to specific assets based on technical regime changes.
♦ Swing traders on higher timeframes who want to align their positions with the broader market structure rather than fighting the trend.
This is not designed for:
* Day traders or scalpers
* Those seeking exact entry/exit prices
* Automated trading systems (this is a visual decision-support tool)
--------------------------------------------------------------
Understanding the Visuals
When you apply Tactical Holding to a chart, you'll see:
1. Colored candles - Instantly see what market regime the asset is in
2. Colored EMA line (thick line) - Provides a dynamic support/resistance reference that changes color with market conditions
3. Small arrows (↑ ↓) - Mark bars where specific technical patterns complete
4. State label - Shows current market classification
5. Legend table (top right) - Quick reference guide for the color system
6. Warning banner (top center) - Reminds you to use weekly charts
The visual design prioritizes clarity over complexity. You should be able to glance at a chart and immediately understand the current technical environment.
--------------------------------------------------------------
Important Limitations
This indicator cannot:
* Predict future price movements
* Guarantee profitable trades
* Work equally well on all assets or timeframes
* Replace your own research and risk management
Technical considerations:
* Divergence detection has a 3-bar confirmation lag (by design, to avoid false signals)
* State transitions require multiple technical confirmations, which may cause delayed reactions to rapid market changes
* The system is reactive, not predictive - it responds to price action after it occurs
* Performance varies significantly between trending assets (like Solana) and stable assets (like Apple)
--------------------------------------------------------------
Practical Application
Consider using this indicator as one component of a broader investment framework:
♦ Understanding Position Context:
The color-coded states can help frame your thinking about current holdings:
Bull: Technical conditions that have historically been associated with sustained uptrends
Bull Retrace: Pullbacks within an overall bullish structure- these periods may offer opportunities to evaluate entry points or reassess existing positions
Reversal (Yellow): Transitional phases where the trend direction is unclear - periods that may warrant closer monitoring
Bear Retrace: Temporary strength within an overall bearish structure - rallies that historically have often faded
Bear: Technical conditions that have historically been associated with sustained downtrends
♦ Interpreting Signal Arrows:
Arrow markers indicate when specific technical pattern conditions have been met. These are observation points, not instructions:
A signal appearing doesn't mean immediate action is required
Treat arrows as prompts for further analysis rather than automatic triggers
Consider the broader context: fundamentals, your investment timeline, risk tolerance, and overall market conditions
Signals show when historical technical patterns have formed - not whether those patterns will lead to the same outcomes as in the past
The framework is designed to organize information visually, not to tell you what to do. Your investment decisions should incorporate this technical perspective alongside other factors relevant to your situation.
--------------------------------------------------------------
Technical Methodology
For transparency, the indicator uses:
* RSI (14) with a 14-period SMA to assess momentum direction
* MACD (12,26,9) to confirm trend strength and histogram momentum
* Stochastic RSI with K and D line crossovers for additional confirmation
* 50-period EMA as the primary trend filter
* Linear regression-based slope analysis to detect flat/transitional periods
* Pivot-based divergence detection following standard technical analysis principles
All calculations use publicly available technical analysis formulas. Nothing is hidden or proprietary beyond the specific combination and weighting of these standard tools.
--------------------------------------------------------------
Disclaimer
This indicator is an educational and analytical tool only. It is not financial advice.
* Trading and investing involve substantial risk of loss
* Past performance of any technical system does not indicate future results
* No indicator can predict market movements with certainty
* Always conduct your own research and consult with qualified financial professionals
* Never invest more than you can afford to lose
* The creators of this indicator are not responsible for any trading losses
* This tool is not affiliated with, endorsed by, or connected to TradingView, 3Commas, or any other trading platform
* Use of this indicator is at your own risk
Risk Management: Regardless of what any indicator shows, always use proper position sizing, stop losses, and risk management appropriate to your personal financial situation.
This indicator provides a framework for analysis. Your decisions, research, and risk management determine your results.
BTC CME Gaps Detector [SwissAlgo]BTC CME Gaps Detector
Track Unfilled Gaps & Identify Price Magnets
------------------------------------------------------
Overview
The BTC CME Gap Detector identifies and tracks unfilled price gaps on any timeframe (1-minute recommended for scalping) to gauge potential trading bias.
Verify Gap Behavior Yourself : Use TradingView's Replay Mode on the 1-Minute chart to observe how the price interacts with gaps. Load the BTC1! ticker (Bitcoin CME Futures), enable Replay Mode, and play forward through time (for example: go back 15 days). You may observe patterns such as price frequently returning to fill gaps, nearest gaps acting as near-term targets, and gaps serving as potential support/resistance zones. Some gaps may fill quickly, while others may remain open for longer periods. This hands-on analysis lets you independently assess how gaps may influence price movement in real market conditions and whether you may use this indicator as a complement to your trading analysis.
------------------------------------------------------
Purpose
Price gaps occur when there is a discontinuity between consecutive candles - when the current candle's low is above the previous candle's high (gap up), or when the current candle's high is below the previous candle's low (gap down).
This indicator identifies and tracks these gaps on any timeframe to help traders:
Identify gap zones that may attract price (potential "price magnets")
Monitor gap fill progression
Assess potential directional bias based on nearest unfilled gaps (long, short)
Analyze market structure and liquidity imbalances
------------------------------------------------------
Why Use This Indicator?
Universal Gap Detection : Identifies all gaps on any timeframe (1-minute, hourly, daily, etc.)
Multi-Candle Mitigation Tracking : Detects gap fills that occur across multiple candles
Distance Analysis : Shows percentage distance to nearest bullish and bearish gaps
Visual Representation : Color-coded boxes indicate gap status (active vs. mitigated)
Age Filtering : Option to display only gaps within specified time periods (3/6/12/24 months), as older gaps may lose relevance
ATR-Based Sizing : Minimum gap size adjusts to instrument volatility to filter noise (i.e. small gaps)
------------------------------------------------------
Trading Concept
Gaps represent price zones where no trading occurred. Historical market behavior suggests that unfilled gaps may attract price action as markets tend to revisit areas of incomplete price discovery. This phenomenon creates potential trading opportunities:
Bullish gaps (above current price) may act as upside targets where the price could move to fill the gap
Bearish gaps (below current price) may act as downside targets where price could move to fill the gap
The nearest gap often provides directional bias, as closer gaps may have a higher probability of being filled in the near term
This indicator helps quantify gap proximity and provides a visual reference for these potential target zones.
EXAMPLE
Step 1: Bearish Gaps Appear Below Price
Step 2: Price Getting Close to Fill Gap
Step 3: Gap Mitigated Gap
------------------------------------------------------
Recommended Setup
Timeframe: 1-minute chart recommended for maximum gap detection frequency. Works on all timeframes (higher timeframes will show fewer, larger gaps).
Symbol: Any tradable instrument. Originally designed for BTC1! (CME Bitcoin Futures) but compatible with all symbols.
Settings:
ATR Length: 14 (default)
Min Gap Size: 0.5x ATR (adjust based on timeframe and noise level)
Gap Age Limit: 3 months (configurable)
Max Historical Gaps: 300 (adjustable 1-500)
------------------------------------------------------
How It Works
Gap Detection : Identifies price discontinuities on every candle where:
Gap up: current candle low > previous candle high
Gap down: current candle high < previous candle low
Minimum gap size filter (ATR-based) eliminates insignificant gaps
Mitigation Tracking : Monitors when price touches both gap boundaries. A gap is marked as filled when the price has touched both the top and bottom of the gap zone, even if this occurs across multiple candles.
Visual Elements :
Green boxes: Unfilled gaps above current price (potential bullish targets)
Red boxes: Unfilled gaps below current price (potential bearish targets)
Gray boxes: Filled gaps (historical reference)
Labels: Display gap type, price level, and distance percentage
Analysis Table: Shows :
Distance % to nearest bullish gap (above price)
Distance % to nearest bearish gap (below price)
Trade bias (LONG if nearest gap is above, SHORT if nearest gap is below)
------------------------------------------------------
Key Features
Detects gaps on any timeframe (1m, 5m, 1h, 1D, etc.)
Boxes extend 500 bars forward for active gaps, stop at the fill bar for mitigated gaps
Real-time distance calculations update on every candle
Configurable age filter removes outdated gaps
ATR multiplier ensures gap detection adapts to market volatility and timeframe
------------------------------------------------------
Disclaimer
This indicator is provided for informational and educational purposes only.
It does not constitute financial advice, investment recommendations, or trading signals. The concept that gaps attract price is based on historical observation and does not guarantee future results.
Gap fills are not certain - gaps may remain unfilled indefinitely, or the price may reverse before reaching a gap. This indicator should not be used as the sole basis for trading decisions.
All trading involves substantial risk, including the potential loss of principal. Users should conduct their own research, apply proper risk management, test strategies thoroughly, and consult with qualified financial professionals before making trading decisions.
The authors and publishers are not responsible for any losses incurred through the use of this indicator.
Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
ICT Sessions Ranges [SwissAlgo]ICT Session Ranges - ICT Liquidity Zones & Market Structure
OVERVIEW
This indicator identifies and visualizes key intraday trading sessions and liquidity zones based on Inner Circle Trader (ICT) methodology (AM, NY Lunch Raid, PM Session, London Raid). It tracks 'higher high' and 'lower low' price levels during specific time periods that may represent areas where market participants have placed orders (liquidity).
PURPOSE
The indicator helps traders observe:
Session-based price ranges during different market hours
Opening range gaps between market close and next day's open
Potential areas where liquidity may be concentrated and trigger price action
SESSIONS TRACKED
1. London Session (02:00-05:00 ET): Tracks price range during early London trading hours
2. AM Session (09:30-12:00 ET): Tracks price range during the morning New York session
3. NY Lunch Session (12:00-13:30 ET): Tracks price range during typical low-volume lunch period
4. PM Session (13:30-16:00 ET): Tracks price range during the afternoon New York session
CALCULATIONS
Session High/Low: The highest high and lowest low recorded during each active session period
Opening Range Gap: Calculated as the difference between the previous day's 16:00 close and the current day's 09:30 open
Gap Mitigation: A gap is considered mitigated when the price reaches 50% of the gap range
All times are based on America/New_York timezone (ET)
BACKGROUND INDICATORS
NY Trading Hours (09:30-16:00 ET): Optional gray background overlay
Asian Session (20:00-23:59 ET): Optional purple background overlay
VISUAL ELEMENTS
Horizontal lines mark session highs and lows
Subtle background boxes highlight each session range
Labels identify each session type
Orange shaded boxes indicate unmitigated opening range gaps
Dotted line at 50% gap level shows mitigation threshold
FEATURES
Toggle visibility for each session independently
Customizable colors for each session type
Automatic removal of mitigated gaps
All drawing objects use transparent backgrounds for chart clarity
ICT CONCEPTS
This tool relates to concepts discussed by Inner Circle Trader regarding liquidity pools, session-based analysis, and gap theory. The indicator assumes that session highs and lows may represent areas where liquidity is concentrated, and that opening range gaps may attract price until mitigated.
USAGE NOTES
Best used on intraday timeframes (1-15 minute charts)
All sessions are calculated based on actual price movement during specified time periods
Historical session data is preserved as new sessions develop
Gap detection only triggers at 09:30 ET market open
DISCLAIMER
This indicator is for educational and informational purposes only. It displays historical price levels and time-based calculations. Past performance of price levels is not indicative of future results. The identification of "liquidity zones" is a theoretical concept and does not guarantee that orders exist at these levels or that prices will react to them. Trading involves substantial risk of loss. Users should conduct their own analysis and risk assessment before making any trading decisions.
TIME ZONE
Set your timezone to: America/New_York (UTC-5)
Position Sizer (% of Acct & Shares Req)
This indicator calculates % position size and share quantity required based on total capital and user-defined risk percentages
This indicator differs from the Shares Qty indicator in that it is based on %'s rather than a user-defined, fixed dollar amount to risk (for those who prefer to calculate risk in this manner instead)
Tracks real-time Low of Day (LoD) during regular trading hours (RTH) for accurate stop placement
Current price as well as output rows 2 and 3 can be toggled on/off, per preference
Allows stop loss selection between LoD, Low of Week (LoW), and Prior Day Low (PDL)
Keeps data updating intraday to reflect changing LoD and price conditions
Provides a second “Stop Loss Compare” dropdown to compare two stop methods side by side
Displays all results in a dynamic on-chart table that updates with live prices
Shows capital amount, stop type, stop price, and share counts for three risk levels
=========
Risk rows displayed as: Risk of Cap Amt: ,
=========
Disclaimer:
This indicator is for educational and informational purposes only. It should not be used as the sole basis for trading decisions. Always combine with other forms of analysis, proper risk management techniques, and consider your individual trading plan and risk tolerance. All calculations and outputs are provided as-is, and it is your responsibility to verify their accuracy before making any trading decisions.
Aquantprice: Institutional Structure MatrixSETUP GUIDE
Open TradingView
Go to Indicators
Search: Aquantprice: Institutional Structure Matrix
Click Add to Chart
Customize:
Min Buy = 10, Min Sell = 7
Show only PP, R1, S1, TC, BC
Set Decimals = 5 (Forex) or 8 (Crypto)
USE CASES & TRADING STRATEGIES
1. CPR Confluence Trading (Most Popular)
Rule: Enter when ≥3 timeframes show Buy ≥10/15 or Sell ≥7/13
text Example:
Daily: 12/15 Buy
Weekly: 11/15 Buy
Monthly: 10/15 Buy
→ **STRONG LONG BIAS**
Enter on pullback to nearest **S1 or L3**
2. Hot Zone Scalping (Forex & Indices)
Rule: Trade only when price is in Hot Zone (closest 2 levels)
text Hot: S1-PP → Expect bounce or breakout
Action:
- Buy at S1 if Buy Count ↑
- Sell at PP if Sell Count ↑
3. Institutional Reversal Setup
Rule: Price at H3/L3 + Reversal Condition
text Scenario:
Price touches **Monthly L3**
L3 in **Hot Zone**
Buy Count = 13/15
→ **High-Probability Reversal Long**
4. CPR Width Filter (Avoid Choppy Markets)
Rule: Trade only if CPR Label = "Strong Trend"
text CPR Size < 0.25 → Trending
CPR Size > 0.75 → Sideways (Avoid)
5. Multi-Timeframe Bias Dashboard
Use "Buy" and "Sell" columns as a sentiment meter
TimeframeBuySellBiasDaily123BullishWeekly89BearishMonthly112Bullish
→ Wait for alignment before entering
HOW TO READ THE TABLE
Column Meaning Time frame D, W, M, 3M, 6M, 12MOpen Price Current session open PP, TC, BC, etc. Pivot levels (color-coded if in Hot Zone) Buy X/15 conditions met (≥10 = Strong Buy)Sell X/13 conditions met (≥7 = Strong Sell)CPR Size Histogram + Label (Trend vs Range)Zone Hot: PP-S1, Med: S2-L3, etc. + PP Distance
PRO TIPS
Best on 5M–1H charts for entries
Use with volume or order flow for confirmation
Set alerts on Buy ≥12/15 or Sell ≥10/13
Hide unused levels to reduce clutter
Combine with AQuantPrice Dashboard (Small TF) for full system
IDEAL MARKETS
Forex (EURUSD, GBPUSD, USDJPY)
Indices (NAS100, SPX500, DAX)
Crypto (BTC, ETH – use 6–8 decimals)
Commodities (Gold, Oil)
🚀 **NEW INDICATOR ALERT**
**Aquantprice: Institutional Structure Matrix**
The **ALL-IN-ONE CPR Dashboard** used by smart money traders.
✅ **6 Timeframes in 1 Table** (Daily → Yearly)
✅ **15 Buy + 13 Sell Conditions** (Institutional Logic)
✅ **Hot Zones, CPR Width, PP Distance**
✅ **Fully Customizable – Show/Hide Any Level**
✅ **Real-Time Zone Detection** (Hot, Med, Low)
✅ **Precision up to 8 Decimals**
**No more switching charts. No more confusion.**
See **where institutions are positioned** — instantly.
👉 **Add to Chart Now**: Search **"Aquantprice: Institutional Structure Matrix"**
🔥 **Free Access | Pro-Level Insights**
*By AQuant – Trusted by 10,000+ Traders*
#CPR #PivotTrading #SmartMoney #TradingView
FINAL TAGLINE
"See What Institutions See — Before They Move."
Aquantprice: Institutional Structure Matrix
Your Edge. One Dashboard.
Position Sizer (Share Qty)
This indicator enables fast & accurate position sizing for traders using (user defined) fixed dollar risk, eliminating the need for manual calculations and supporting disciplined risk management directly on the chart
Calculates precise share quantity for fixed-risk trades using the formula Shares = Risk Amount / (Current Price – Stop Price), rounded to the nearest whole share, updating in real time on every bar
Offers two dynamic stop-loss options: Low of Day (LoD) — tracked only during Regular Trading Hours (9:30 AM – 4:00 PM ET) with automatic daily reset — or Low of Week (LoW) via weekly timeframe data
Displays all critical trade data in a clean, customizable on-screen table showing: Risk Amount, Stop Loss type (LoD/LoW), Stop Price, and calculated Shares Qty
Allows full table placement control with four corner positions with optional Top Offset and Bottom Offset (0–20 blank rows each) to prevent overlap with price action or other indicators
Provides complete visual styling control for header text/background, value text/background, and share quantity text/background
Ensures efficient rendering by recreating the table only when position, row count, or layout changes, deleting the prior instance to avoid flicker or memory issues
Handles edge cases safely: shows 0 shares if stop is 'na' or above current price, and initializes LoD only on the first RTH bar of each session
For use on equities only (table will not display on futures instruments)
--
Future improvements:
Visual Stop Loss line for either LoD or LoW
Functionality and toggle to include Extended hours (PM /AH) for LoD stop pricing
SatoshiFrame Lot Size CalculatorSatoshiFrame Lot Size Calculator that help you to manage your lot size in forex and crypto trade
Risk & Position DashboardRisk & Position Dashboard
Overview
The Risk & Position Dashboard is a comprehensive trading tool designed to help traders calculate optimal position sizes, manage risk, and visualize potential profit/loss scenarios before entering trades. This indicator provides real-time calculations for position sizing based on account size, risk percentage, and stop-loss levels, while displaying multiple take-profit targets with customizable risk-reward ratios.
Key Features
Position Sizing & Risk Management:
Automatic position size calculation based on account size and risk percentage
Support for leveraged trading with maximum leverage limits
Fractional shares support for brokers that allow partial share trading
Real-time fee calculation including entry, stop-loss, and take-profit fees
Break-even price calculation including trading fees
Multi-Target Profit Management:
Support for up to 3 take-profit levels with individual portion allocations
Customizable risk-reward ratios for each take-profit target
Visual profit/loss zones displayed as colored boxes on the chart
Individual profit calculations for each take-profit level
Visual Dashboard:
Clean, customizable table display showing all key metrics
Configurable label positioning and styling options
Real-time tracking of whether stop-loss or take-profit levels have been reached
Color-coded visual zones for easy identification of risk and reward areas
Advanced Configuration:
Comprehensive input validation and error handling
Support for different chart timeframes and symbols
Customizable colors, fonts, and display options
Hide/show individual data fields for personalized dashboard views
How to Use
Set Account Parameters: Configure your account size, maximum risk percentage per trade, and trading fees in the "Account Settings" section.
Define Trade Setup: Use the "Entry" time picker to select your entry point on the chart, then input your entry price and stop-loss level.
Configure Take Profits: Set your desired risk-reward ratios and portion allocations for each take-profit level. The script supports 1-3 take-profit targets.
Analyze Results: The dashboard will automatically calculate and display position size, number of shares, potential profits/losses, fees, and break-even levels.
Visual Confirmation: Colored boxes on the chart show profit zones (green) and loss zones (red), with lines extending to current price levels.
Reset Entry and SL:
You can easily reset the entry and stop-loss by clicking the "Reset points..." button from the script's "More" menu.
This is useful if you want to quickly clear your current trade setup and start fresh without manually adjusting the points on the chart.
Calculations
The script performs sophisticated calculations including:
Position size based on risk amount and price difference between entry and stop-loss
Leverage requirements and position amount calculations
Fee-adjusted risk-reward ratios for realistic profit expectations
Break-even price including all trading costs
Individual profit calculations for partial position closures
Detailed Take-Profit Calculation Formula:
The take-profit prices are calculated using the following mathematical formula:
// Core variables:
// risk_amount = account_size * (risk_percentage / 100)
// total_risk_per_share = |entry_price - sl_price| + (entry_price * fee%) + (sl_price * fee%)
// shares = risk_amount / total_risk_per_share
// direction_factor = 1 for long positions, -1 for short positions
// Take-profit calculation:
net_win = total_risk_per_share * shares * RR_ratio
tp_price = (net_win + (direction_factor * entry_price * shares) + (entry_price * fee% * shares)) / (direction_factor * shares - fee% * shares)
Step-by-step example for a long position (based on screenshot):
Account Size: 2,000 USDT, Risk: 2% = 40 USDT
Entry: 102,062.9 USDT, Stop Loss: 102,178.4 USDT, Fee: 0.06%
Risk per share: |102,062.9 - 102,178.4| + (102,062.9 × 0.0006) + (102,178.4 × 0.0006) = 115.5 + 61.24 + 61.31 = 238.05 USDT
Shares: 40 ÷ 238.05 = 0.168 shares (rounded to 0.17 in display)
Position Size: 0.17 × 102,062.9 = 17,350.69 USDT
Position Amount (with 9x leverage): 17,350.69 ÷ 9 = 1,927.85 USDT
For 2:1 RR: Net win = 238.05 × 0.17 × 2 = 80.94 USDT
TP1 price = (80.94 + (1 × 102,062.9 × 0.17) + (102,062.9 × 0.0006 × 0.17)) ÷ (1 × 0.17 - 0.0006 × 0.17) = 101,464.7 USDT
For 3:1 RR: TP2 price = 101,226.7 USDT (following same formula with RR=3)
This ensures that after accounting for all fees, the actual risk-reward ratio matches the specified target ratio.
Risk Management Features
Maximum Trade Amount: Optional setting to limit position size regardless of account size
Leverage Limits: Built-in maximum leverage protection
Fee Integration: All calculations include realistic trading fees for accurate expectations
Validation: Automatic checking that take-profit portions sum to 100%
Historical Tracking: Visual indication when stop-loss or take-profit levels are reached (within last 5000 bars)
Understanding Max Trade Amount - Multiple Simultaneous Trades:
The "Max Trade Amount" feature is designed for traders who want to open multiple positions simultaneously while maintaining proper risk management. Here's how it works:
Key Concept:
- Risk percentage (2%) always applies to your full Account Size
- Max Trade Amount limits the capital allocated per individual trade
- This allows multiple trades with full risk on each trade
Example from Screenshot:
Account Size: 2,000 USDT
Max Trade Amount: 500 USDT
Risk per Trade: 2% × 2,000 = 40 USDT per trade
Stop Loss Distance: 0.11% from entry
Result: Position Size = 17,350.69 USDT with 35x leverage
Total Risk (including fees): 40.46 USDT
Multiple Trades Strategy:
With this setup, you can open:
Trade 1: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 2: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 3: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 4: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Total Portfolio Exposure:
- 4 simultaneous trades = 4 × 495.73 = 1,982.92 USDT position amount
- Total risk exposure = 4 × 40 = 160 USDT (8% of account)
Simulated Fear & Greed (CNN-calibrated v2)🧭 Fear & Greed Index — TradingView Version (Simulated CNN Model)
🔍 Purpose
The Fear & Greed Index is a sentiment indicator that quantifies market emotion on a scale from 0 to 100, where:
0 represents Extreme Fear (capitulation, oversold conditions), and
100 represents Extreme Greed (euphoria, overbought conditions).
It helps traders assess whether the market is driven by fear (risk aversion) or greed (risk appetite) — giving a high-level view of potential turning points in market sentiment.
⚙️ How It Works in TradingView
Because TradingView cannot directly access CNN’s or alternative external sentiment feeds, this indicator simulates the Fear & Greed Index by analyzing in-chart technical data that reflect investor psychology.
It uses a multi-factor model, converting price and volume signals into a composite sentiment score.
🧩 Components Used (Simulated Metrics)
Category Metric Emotional Interpretation
Volatility ATR (Average True Range) High ATR = Fear, Low ATR = Greed
Momentum RSI + MACD Histogram Rising momentum = Greed, Falling = Fear
Volume Activity Volume Z-Score High positive deviation = Greed, Low = Fear
Trend Context SMA Regime Bias (50/200) Downtrend adds Fear penalty, Uptrend supports Greed
These elements are normalized into a 0–100 scale using percentile ranks (like statistical scoring) and then combined using user-adjustable weights.
⚖️ CNN-Style Calibration
The script follows CNN’s five sentiment bands for clarity:
Range Zone Colour Description
0–25 Extreme Fear 🔴 Red Panic, forced selling, capitulation risk
25–45 Fear 🟠 Orange Uncertainty, hesitation, early accumulation phase
45–55 Neutral ⚪ Gray Balanced sentiment, indecision
55–75 Greed 🟢 Light Green Optimism, trend continuation
75–100 Extreme Greed 💚 Bright Green Euphoria, risk of reversal
This structure aligns visually with CNN’s public gauge, making it easy to interpret.
Dual Harmonic-based AHR DCA (Default :BTC-ETH)A panel indicator designed for dual-asset BTC/ETH DCA (Dollar Cost Averaging) decisions.
It is inspired by the Chinese community indicator "AHR999" proposed by “Jiushen”.
How to use:
Lower HM-based AHR → cheaper (potential buy zone).
Higher HM-based AHR → more expensive (potential risk zone).
Higher than Risk Threshold → consider to sell, but not suitable for DCA.
When both AHR lines are below the Risk threshold → buy the cheaper one (or split if similar).
If one AHR is above Risk → buy the other asset.
If both are above Risk → simulation shows “STOP (both risk)”.
Not limited to BTC/ETH — you can freely change symbols in the input panel
to build any dual-asset DCA pair you want (e.g., BTC/BNB, ETH/SOL, etc.).
What you’ll see:
Two lines: AHR BTC (HM) and AHR ETH (HM)
Two dashed lines: OppThreshold (green) and RiskThreshold (red)
Colored fill showing which asset is cheaper (BTC or ETH)
Buy markers:
- B = Buy BTC
- E = Buy ETH
- D = Dual (split budget)
Top-right table: prices, AHRs, thresholds, qOpp/qRisk%, simulation, P&L
Labels showing last-bar AHR values
Core idea:
Use an AHR based on Harmonic Moving Average (HM) — a ratio that measures how “cheap or expensive” price is relative to both its short-term mean and long-term trend.
The original AHR999 used SMA and was designed for BTC only.
This indicator extends it with cross-exchange percentile mapping, allowing the empirical “opportunity/risk” zones of the AHR999 (on Bitstamp) to adapt automatically to the current market pair.
The indicator derives two adaptive thresholds:
OppThreshold – opportunity zone
RiskThreshold – risk zone
These thresholds are compared with the current HM-based AHR of BTC and ETH to decide which asset is cheaper, and whether it is good to DCA or not, or considering to sell(When it in risk area).
This version uses
Display base: Binance (default: perpetual) with HM-based AHR
Percentile base: Bitstamp spot SMA-AHR (complete, stable history)
Rolling window: 2920 daily bars (~8 years) for percentile tracking
Concept summary
AHR measures the ratio of price to its long-term regression and short-term mean.
HM replaces SMA to better reflect equal-fiat-cost DCA behavior.
Cross-exchange percentile mapping (Bitstamp → Binance) keeps thresholds consistent with the original AHR999 interpretation.
Recommended settings (1D):
DCA length (harmonic): 200
Log-regression lookback: 1825 (≈5 years)
Rolling window: 2920 (≈8 years)
Reference thresholds: 0.45 / 1.20 (AHR999 empirical priors)
Tie split tolerance (ΔAHR): 0.05
Daily budget: 15 USDT (simulation)
All display options can be toggled: table, markers, labels, etc.
Notes:
When the rolling window is filled (2920 bars by default), thresholds are first calculated and then visually backfilled as left-extended lines.
The “buy markers” and “decision table” are light simulations without fees or funding costs — for rhythm and relative analysis, not backtesting.






















