Positional Supertrend Strategy (1D Filter + 2H Entry)Positional Supertrend Strategy (1D Filter + 2H Entry)
Chỉ báo và chiến lược
Supertrend +QQE + DEMASupertrend + QQE + DEMA — Strategy
Inspired by UNITED and my best friend ChatGPT
This strategy combines dual Supertrends, a QQE trend filter, and a 200-period DEMA directional filter to generate structured, trend-aligned entries. It is designed for Heikin Ashi charts , where trend noise is reduced and swing structure becomes clearer.
How It Works
The system fires a trade only when all conditions agree:
1. Both Supertrends flip in the same direction
This identifies strong directional shifts and removes weak reversals.
2. QQE Trend Confirmation
QQE acts as a momentum filter, requiring either a green (bullish) or red (bearish) state with optional consecutive-bar confirmation.
3. 200 DEMA Filter
Only longs above the DEMA and only shorts below the DEMA.
This keeps trades aligned with the higher-timeframe trend.
Because each component filters the other, signals are high-quality, controlled, and structured rather than frequent or reactive.
Expected Performance
Based on the design and typical market testing, this combination yields a 50–70% win rate, depending on:
The market (best on indices like NQ/MNQ, ES/MES, DAX, etc.)
Volatility conditions
Whether used on Heikin Ashi , which increases trend-cleanliness and reduces chop
Timeframe (1m–5m often optimal for intraday)
The system avoids rapid flip-flopping by using “arm → confirm → fire once” logic, which further improves win consistency and reduces whipsaw losses.
How to Properly Use It (IMPORTANT)
This strategy is meant to be run on a Heikin Ashi chart.
Why?
Heikin Ashi smooths candles, giving clearer:
Trend transitions
Pullbacks
Momentum continuation
Supertrend reliability
Running this on normal candles will still work, but the win rate and smoothness drop significantly because Supertrend + QQE respond more cleanly to HA structure.
Trade Behavior
Longs trigger when both Supertrends flip up, QQE is bullish, and price is above DEMA.
Shorts trigger when both Supertrends flip down, QQE is bearish, and price is below DEMA.
Strategy closes when the opposite Supertrend flip occurs.
Alerts fire automatically for buy/sell confirmations.
Best Use Cases
Intraday trend trading
Momentum continuation after a confirmed reversal
Avoiding chop with multi-layer confirmation
Backtesting rule-based execution
Sunflower Quant - ETH 15min Strategy🟠 Sunflower Quant - ETH 15min Strategy
Strategy Overview
The " Sunflower Quant - ETH 15min Strategy" is a sophisticated automated trading system specifically designed for ETH/USDT on 15-minute timeframes. This advanced algorithm integrates over 20 technical indicators and price action patterns to deliver intelligent entry decisions and comprehensive risk management.
Core Value Proposition
Multi-Timeframe Integration: Combines 1-hour and 4-hour higher timeframe data for signal validation
Dynamic Market Regime Detection: Real-time identification of Low Volatility, Ranging, and High Volatility market environments
Comprehensive Scoring System: Three-dimensional evaluation model based on Breakout Signals, Pattern Recognition, and Position Analysis
Adaptive Position Sizing: Dynamic allocation based on signal strength and market volatility
🟠 Core Architecture
Three-Layer Analytical Framework
1. Market Regime Detection System
Real-time market environment assessment through four dimensions:
ATR Relative Volatility
Bollinger Band Width
Average Amplitude
Momentum Strength
Market State Classification:
Low Volatility (≤30 points): Narrow ranges, awaiting breakout
Ranging Market (31-65 points): Moderate volatility, suitable for range trading
High Volatility (>65 points): Strong trends, ideal for trend following
2. Signal Generation Engine
Breakout Signal Layer:
Donchian Channel Breakouts (Upper/Middle/Lower)
Keltner Channel Breakouts (Upper/Middle/Lower)
Double ATR Momentum Confirmation
Pattern Recognition Layer:
Price Action: Outside Bars, Engulfing Patterns, False Breakouts
Candlestick Patterns: Hammer, Inverted Hammer, Doji, Dragonfly, Gravestone
Three Soldiers Method: Single-bar and Three-bar consecutive patterns
Position Analysis Layer:
Ichimoku Cloud Position (Above/Within/Below)
ADX Trend Strength Confirmation
DC/KC Middle Band Position Analysis
3. Volume & POC Analysis
Volume Confirmation:
High Volume Breakout Validation
Medium Volume Support Confirmation
Point of Control (POC) Value Areas:
Volume-based dense trading zone identification
POC Cluster Scoring System (Size Score + Volume Score + Time Score)
🟠 Trading Logic Specification
Entry Signal Classification
A-Class Signals (Strong Breakout)
Trigger: VP breaking key POC levels + strong pattern confirmation
Characteristics: High confidence, larger position sizing
Stop Loss: Wider stops based on historical ATR volatility
B-Class Signals (Pattern Confirmed)
Trigger: Clear price patterns + volume confirmation
Characteristics: Medium confidence, standard position sizing
Stop Loss: Based on pattern lows/highs
C-Class Signals (Weak Reversal)
Trigger: Single indicator signals + positional support
Characteristics: Lower confidence, small exploratory positions
Stop Loss: Tight stops for quick exits
Scoring Weight Distribution
text
Base Score = Breakout(30%) + Patterns(40%) + Position(30%)
Final Score = Base Score × Market Regime Coefficient × Cloud Position Coefficient
🟠 Risk Management System
Dynamic Stop Loss Strategy
Initial Stop Loss: ATR-based volatility + market regime adjustment
Trailing Stop: Phased tracking, progressively locking profits
Position Management
text
Base Position = Initial Capital × Base Coefficient / Stop Distance
Final Position = Base Position × Signal Strength Coefficient × Market Volatility Coefficient
Take Profit System
Scaled Profit Taking: 8 profit levels with proportional position distribution
Dynamic Adjustment: Trailing stop activation upon reaching specific profit tiers
🟠 Configuration Parameters
Market Regime Thresholds
pinescript
Low Volatility: ≤30 points
Ranging Market: 31-65 points
High Volatility: >65 points
Signal Strength Thresholds
pinescript
// Current Entry Thresholds (No Position)
Low Volatility: Long 82 / Short 82
Ranging: Long 75 / Short 80
High Volatility: Long 80 / Short 85
// Reversal Entry Thresholds
Low Volatility: Long 75 / Short 90
Ranging: Long 85 / Short 90
High Volatility: Long 90 / Short 100
🟠 Usage Guide
1. Initial Setup
Apply to ETH/USDT 15-minute chart
Configure webhook Signal ID and UID
Adjust initial capital parameters according to account size
2. Key Monitoring Elements
Market Regime Indicator: Watch background color changes
Signal Score Display: Monitor real-time long/short scores
POC Value Areas: Identify key support/resistance levels
3. Trading Decision Process
Trend Confirmation Phase:
text
1. Observe market regime background
2. Confirm Ichimoku cloud position
3. Check ADX trend strength
Entry Signal Screening:
text
1. Comprehensive score > corresponding threshold
2. Multiple indicator signal confluence
3. Volume confirmation alignment
Risk Management Execution:
text
1. Automatic position size calculation
2. Set scaled take profit and stop loss
3. Monitor trailing stop updates
4. Advanced Features
Lookback Mode: Historical signal validation
Special Close: Early exit based on ATR ratio
Signal Filtering: Optimize signal quality through component weight adjustment
This systematic multi-factor scoring strategy delivers stable automated trading decisions in complex market environments, particularly well-suited for the short-term volatility characteristics of cryptocurrencies like Ethereum.
Strategy Name: Sunflower Quantitative Strategy
Symbol: ETH/USDT
Timeframe: 15-minute
Market: Cryptocurrency
Strategy Type: Multi-timeframe Quantitative Analysis
Risk Level: Medium-High
Recommended Capital: $10,000+ for optimal position sizing
"向日葵量化"是一款专为ETH 15分钟图表设计的全自动量化交易策略。该策略通过多维度技术分析框架,集成超过20种技术指标与价格行为模式,实现智能化的入场决策与风险控制。
核心价值
多时间框架协同:整合1小时、4小时高周期数据,确保信号质量
动态市场状态识别:实时识别低波动、震荡、高波动三种市场环境
综合评分系统:基于突破信号、形态识别、位置分析的三维评分模型
智能仓位管理:根据信号强度与市场波动率动态调整仓位规模
🟠【核心架构】
策略基于三层分析框架构建:
1. 市场状态识别系统
通过ATR相对波动率、布林带宽、平均振幅、动量强度四个维度,实时判断当前市场环境:
低波动市场(≤30分):窄幅震荡,等待突破
震荡市场(31-65分):中等波动,适合区间交易
高波动市场(>65分):趋势明确,适合趋势跟踪
2. 信号生成引擎
突破信号层:
DC通道突破(上轨/中轨/下轨)
KC通道突破(上轨/中轨/下轨)
双ATR动量确认
形态识别层:
价格行为模式:外包线、吞没形态、假突破
K线形态:锤子线、倒锤子线、十字星、蜻蜓线、墓碑线
三兵三法:单根强度与三根连续形态
位置分析层:
云图位置关系(之上/之中/之下)
ADX趋势强度确认
DC/KC中轨位置判断
3. 成交量与POC分析
成交量确认:
高成交量突破确认
中等成交量支撑确认
POC价值区域:
基于成交量分布的密集成交区识别
POC集群评分系统(规模分+成交量分+时间分)
🟠【交易逻辑详解】
入场信号分类
A类信号(强势突破)
触发条件:VP突破POC关键位 + 强势形态确认
特征:高置信度,大仓位配置
止损设置:相对宽松,基于ATR历史波动率
B类信号(形态确认)
触发条件:明确价格形态 + 成交量确认
特征:中等置信度,标准仓位
止损设置:基于形态低点/高点
C类信号(弱势反弹)
触发条件:单一指标信号 + 位置支撑
特征:低置信度,小仓位试探
止损设置:紧凑止损,快速离场
评分权重分配
text
基础分 = 突破分(30%) + 形态分(40%) + 位置分(30%)
最终分 = 基础分 × 市场状态系数 × 云图位置系数
🟠【风险管理系统】
动态止损策略
初始止损:基于ATR波动率 + 市场状态调整系数
移动止损:分阶段跟踪,逐级锁定利润
仓位管理
text
基础仓位 = 初始资金 × 基础系数 / 止损距离
最终仓位 = 基础仓位 × 信号强度系数 × 市场波动系数
止盈系统
分级止盈:8个止盈级别,按仓位比例分配
动态调整:达到特定止盈级别后启动移动止损
🟠【配置参数】
市场状态阈值
pinescript
低波动区间:≤30分
震荡区间:31-65分
高波动区间:>65分
信号强度阈值
pinescript
// 当前开仓阈值(无持仓)
低波动:做多82分 / 做空82分
震荡:做多75分 / 做空80分
高波动:做多80分 / 做空85分
// 反转开仓阈值
低波动:做多75分 / 做空90分
震荡:做多85分 / 做空90分
高波动:做多90分 / 做空100分
🟠【使用指南】
1. 初始设置
添加到ETH/USDT 15分钟图表
配置webhook信号ID和UID
根据资金量调整初始资本参数
2. 监控要点
市场状态指示器:关注背景颜色变化
信号评分显示:实时查看多头/空头得分
POC价值区域:识别关键支撑阻力
3. 交易决策流程
趋势确认阶段:
text
1. 观察市场状态背景色
2. 确认云图位置关系
3. 检查ADX趋势强度
入场信号筛选:
text
1. 综合评分 > 对应阈值
2. 多指标信号共振
3. 成交量确认配合
风险管理执行:
text
1. 自动计算仓位大小
2. 设置分级止盈止损
3. 监控移动止损更新
4. 高级功能
回看模式:启用历史信号验证
特殊平仓:基于ATR比率的提前离场
信号过滤:通过调整各组件权重优化信号质量
该策略通过系统化的多因子评分机制,在复杂的市场环境中实现稳定的自动化交易决策,特别适合ETH等加密货币的短期波动特性。
ASHOK 15 Novashok trial 15 nov 1845h
I have created this strategy to convert my chart pattern and MACD, EMA observations to tradeable logic.
Reversal Point Dynamics - Machine Learning⇋ Reversal Point Dynamics - Machine Learning
RPD Machine Learning: Self-Adaptive Multi-Armed Bandit Trading System
RPD Machine Learning is an advanced algorithmic trading system that implements genuine machine learning through contextual multi-armed bandits, reinforcement learning, and online adaptation. Unlike traditional indicators that use fixed rules, RPD learns from every trade outcome , automatically discovers which strategies work in current market conditions, and continuously adapts without manual intervention .
Core Innovation: The system deploys six distinct trading policies (ranging from aggressive trend-following to conservative range-bound strategies) and uses LinUCB contextual bandit algorithms with Random Fourier Features to learn which policy performs best in each market regime. After the initial learning phase (50-100 trades), the system achieves autonomous adaptation , automatically shifting between policies as market conditions evolve.
Target Users: Quantitative traders, algorithmic trading developers, systematic traders, and data-driven investors who want a system that adapts over time . Suitable for stocks, futures, forex, and cryptocurrency on any liquid instrument with >100k daily volume.
The Problem This System Solves
Traditional Technical Analysis Limitations
Most trading systems suffer from three fundamental challenges :
Fixed Parameters: Static settings (like "buy when RSI < 30") work well in backtests but may struggle when markets change character. What worked in low-volatility environments may not work in high-volatility regimes.
Strategy Degradation: Manual optimization (curve-fitting) produces systems that perform well on historical data but may underperform in live trading. The system never adapts to new market conditions.
Cognitive Overload: Running multiple strategies simultaneously forces traders to manually decide which one to trust. This leads to hesitation, late entries, and inconsistent execution.
How RPD Machine Learning Addresses These Challenges
Automated Strategy Selection: Instead of requiring you to choose between trend-following and mean-reversion strategies, RPD runs all six policies simultaneously and uses machine learning to automatically select the best one for current conditions. The decision happens algorithmically, removing human hesitation.
Continuous Learning: After every trade, the system updates its understanding of which policies are working. If the market shifts from trending to ranging, RPD automatically detects this through changing performance patterns and adjusts selection accordingly.
Context-Aware Decisions: Unlike simple voting systems that treat all conditions equally, RPD analyzes market context (ADX regime, entropy levels, volatility state, volume patterns, time of day, historical performance) and learns which combinations of context features correlate with policy success.
Machine Learning Architecture: What Makes This "Real" ML
Component 1: Contextual Multi-Armed Bandits (LinUCB)
What Is a Multi-Armed Bandit Problem?
Imagine facing six slot machines, each with unknown payout rates. The exploration-exploitation dilemma asks: Should you keep pulling the machine that's worked well (exploitation) or try others that might be better (exploration)? RPD solves this for trading policies.
Academic Foundation:
RPD implements Linear Upper Confidence Bound (LinUCB) from the research paper "A Contextual-Bandit Approach to Personalized News Article Recommendation" (Li et al., 2010, WWW Conference). This algorithm is used in content recommendation and ad placement systems.
How It Works:
Each policy (AggressiveTrend, ConservativeRange, VolatilityBreakout, etc.) is treated as an "arm." The system maintains:
Reward History: Tracks wins/losses for each policy
Contextual Features: Current market state (8-10 features including ADX, entropy, volatility, volume)
Uncertainty Estimates: Confidence in each policy's performance
UCB Formula: predicted_reward + α × uncertainty
The system selects the policy with highest UCB score , balancing proven performance (predicted_reward) with potential for discovery (uncertainty bonus). Initially, all policies have high uncertainty, so the system explores broadly. After 50-100 trades, uncertainty decreases, and the system focuses on known-performing policies.
Why This Matters:
Traditional systems pick strategies based on historical backtests or user preference. RPD learns from actual outcomes in your specific market, on your timeframe, with your execution characteristics.
Component 2: Random Fourier Features (RFF)
The Non-Linearity Challenge:
Market relationships are often non-linear. High ADX may indicate favorable conditions when volatility is normal, but unfavorable when volatility spikes. Simple linear models struggle to capture these interactions.
Academic Foundation:
RPD implements Random Fourier Features from "Random Features for Large-Scale Kernel Machines" (Rahimi & Recht, 2007, NIPS). This technique approximates kernel methods (like Support Vector Machines) while maintaining computational efficiency for real-time trading.
How It Works:
The system transforms base features (ADX, entropy, volatility, etc.) into a higher-dimensional space using random projections and cosine transformations:
Input: 8 base features
Projection: Through random Gaussian weights
Transformation: cos(W×features + b)
Output: 16 RFF dimensions
This allows the bandit to learn non-linear relationships between market context and policy success. For example: "AggressiveTrend performs well when ADX >25 AND entropy <0.6 AND hour >9" becomes naturally encoded in the RFF space.
Why This Matters:
Without RFF, the system could only learn "this policy has X% historical performance." With RFF, it learns "this policy performs differently in these specific contexts" - enabling more nuanced selection.
Component 3: Reinforcement Learning Stack
Beyond bandits, RPD implements a complete RL framework :
Q-Learning: Value-based RL that learns state-action values. Maps 54 discrete market states (trend×volatility×RSI×volume combinations) to 5 actions (4 policies + no-trade). Updates via Bellman equation after each trade. Converges toward optimal policy after 100-200 trades.
TD(λ) with Eligibility Traces: Extension of Q-Learning that propagates credit backwards through time . When a trade produces an outcome, TD(λ) updates not just the final state-action but all states visited during the trade, weighted by eligibility decay (λ=0.90). This accelerates learning from multi-bar trades.
Policy Gradient (REINFORCE): Learns a stochastic policy directly from 12 continuous market features without discretization. Uses gradient ascent to increase probability of actions that led to positive outcomes. Includes baseline (average reward) for variance reduction.
Meta-Learning: The system learns how to learn by adapting its own learning rates based on feature stability and correlation with outcomes. If a feature (like volume ratio) consistently correlates with success, its learning rate increases. If unstable, rate decreases.
Why This Matters:
Q-Learning provides fast discrete decisions. Policy Gradient handles continuous features. TD(λ) accelerates learning. Meta-learning optimizes the optimization. Together, they create a robust, multi-approach learning system that adapts more quickly than any single algorithm.
Component 4: Policy Momentum Tracking (v2 Feature)
The Recency Challenge:
Standard bandits treat all historical data equally. If a policy performed well historically but struggles in current conditions due to regime shift, the system may be slow to adapt because historical success outweighs recent underperformance.
RPD's Solution:
Each policy maintains a ring buffer of the last 10 outcomes. The system calculates:
Momentum: recent_win_rate - global_win_rate (range: -1 to +1)
Confidence: consistency of recent results (1 - variance)
Policies with positive momentum (recent outperformance) get an exploration bonus. Policies with negative momentum and high confidence (consistent recent underperformance) receive a selection penalty.
Effect: When markets shift, the system detects the shift more quickly through momentum tracking, enabling faster adaptation than standard bandits.
Signal Generation: The Core Algorithm
Multi-Timeframe Fractal Detection
RPD identifies reversal points using three complementary methods :
1. Quantum State Analysis:
Divides price range into discrete states (default: 6 levels)
Peak signals require price in top states (≥ state 5)
Valley signals require price in bottom states (≤ state 1)
Prevents mid-range signals that may struggle in strong trends
2. Fractal Geometry:
Identifies swing highs/lows using configurable fractal strength
Confirms local extremum with neighboring bars
Validates reversal only if price crosses prior extreme
3. Multi-Timeframe Confirmation:
Analyzes higher timeframe (4× default) for alignment
MTF confirmation adds probability bonus
Designed to reduce false signals while preserving valid setups
Probability Scoring System
Each signal receives a dynamic probability score (40-99%) based on:
Base Components:
Trend Strength: EMA(velocity) / ATR × 30 points
Entropy Quality: (1 - entropy) × 10 points
Starting baseline: 40 points
Enhancement Bonuses:
Divergence Detection: +20 points (price/momentum divergence)
RSI Extremes: +8 points (RSI >65 for peaks, <40 for valleys)
Volume Confirmation: +5 points (volume >1.2× average)
Adaptive Momentum: +10 points (strong directional velocity)
MTF Alignment: +12 points (higher timeframe confirms)
Range Factor: (high-low)/ATR × 3 - 1.5 points (volatility adjustment)
Regime Bonus: +8 points (trending ADX >25 with directional agreement)
Penalties:
High Entropy: -5 points (entropy >0.85, chaotic price action)
Consolidation Regime: -10 points (ADX <20, no directional conviction)
Final Score: Clamped to 40-99% range, classified as ELITE (>85%), STRONG (75-85%), GOOD (65-75%), or FAIR (<65%)
Entropy-Based Quality Filter
What Is Entropy?
Entropy measures randomness in price changes . Low entropy indicates orderly, directional moves. High entropy indicates chaotic, unpredictable conditions.
Calculation:
Count up/down price changes over adaptive period
Calculate probability: p = ups / total_changes
Shannon entropy: -p×log(p) - (1-p)×log(1-p)
Normalized to 0-1 range
Application:
Entropy <0.5: Highly ordered (ELITE signals possible)
Entropy 0.5-0.75: Mixed (GOOD signals)
Entropy >0.85: Chaotic (signals blocked or heavily penalized)
Why This Matters:
Prevents trading during choppy, news-driven conditions where technical patterns may be less reliable. Automatically raises quality bar when market is unpredictable.
Regime Detection & Market Microstructure - ADX-Based Regime Classification
RPD uses Wilder's Average Directional Index to classify markets:
Bull Trend: ADX >25, +DI > -DI (directional conviction bullish)
Bear Trend: ADX >25, +DI < -DI (directional conviction bearish)
Consolidation: ADX <20 (no directional conviction)
Transitional: ADX 20-25 (forming direction, ambiguous)
Filter Logic:
Blocks all signals during Transitional regime (avoids trading during uncertain conditions)
Blocks Consolidation signals unless ADX ≥ Min Trend Strength
Adds probability bonus during strong trends (ADX >30)
Effect: Designed to reduce signal frequency while focusing on higher-quality setups.
Divergence Detection
Bearish Divergence:
Price makes higher high
Velocity (price momentum) makes lower high
Indicates weakening upward pressure → SHORT signal quality boost
Bullish Divergence:
Price makes lower low
Velocity makes higher low
Indicates weakening downward pressure → LONG signal quality boost
Bonus: Adds probability points and additional acceleration factor. Divergence signals have historically shown higher success rates in testing.
Hierarchical Policy System - The Six Trading Policies
1. AggressiveTrend (Policy 0):
Probability Threshold: 60% (trades more frequently)
Entropy Threshold: 0.70 (tolerates moderate chaos)
Stop Multiplier: 2.5× ATR (wider stops for trends)
Target Multiplier: 5.0R (larger targets)
Entry Mode: Pyramid (scales into winners)
Best For: Strong trending markets, breakouts, momentum continuation
2. ConservativeRange (Policy 1):
Probability Threshold: 75% (more selective)
Entropy Threshold: 0.60 (requires order)
Stop Multiplier: 1.8× ATR (tighter stops)
Target Multiplier: 3.0R (modest targets)
Entry Mode: Single (one-shot entries)
Best For: Range-bound markets, low volatility, mean reversion
3. VolatilityBreakout (Policy 2):
Probability Threshold: 65% (moderate)
Entropy Threshold: 0.80 (accepts high entropy)
Stop Multiplier: 3.0× ATR (wider stops)
Target Multiplier: 6.0R (larger targets)
Entry Mode: Tiered (splits entry)
Best For: Compression breakouts, post-consolidation moves, gap opens
4. EntropyScalp (Policy 3):
Probability Threshold: 80% (very selective)
Entropy Threshold: 0.40 (requires extreme order)
Stop Multiplier: 1.5× ATR (tightest stops)
Target Multiplier: 2.5R (quick targets)
Entry Mode: Single
Best For: Low-volatility grinding moves, tight ranges, highly predictable patterns
5. DivergenceHunter (Policy 4):
Probability Threshold: 70% (quality-focused)
Entropy Threshold: 0.65 (balanced)
Stop Multiplier: 2.2× ATR (moderate stops)
Target Multiplier: 4.5R (balanced targets)
Entry Mode: Tiered
Best For: Divergence-confirmed reversals, exhaustion moves, trend climax
6. AdaptiveBlend (Policy 5):
Probability Threshold: 68% (balanced)
Entropy Threshold: 0.75 (balanced)
Stop Multiplier: 2.0× ATR (standard)
Target Multiplier: 4.0R (standard)
Entry Mode: Single
Best For: Mixed conditions, general trading, fallback when no clear regime
Policy Clustering (Advanced/Extreme Modes)
Policies are grouped into three clusters based on regime affinity:
Cluster 1 (Trending): AggressiveTrend, DivergenceHunter
High regime affinity (0.8): Performs well when ADX >25
Moderate vol affinity (0.6): Works in various volatility
Cluster 2 (Ranging): ConservativeRange, AdaptiveBlend
Low regime affinity (0.3): Better suited for ADX <20
Low vol affinity (0.4): Optimized for calm markets
Cluster 3 (Breakout): VolatilityBreakout
Moderate regime affinity (0.6): Works in multiple regimes
High vol affinity (0.9): Requires high volatility for optimal characteristics
Hierarchical Selection Process:
Calculate cluster scores based on current regime and volatility
Select best-matching cluster
Run UCB selection within chosen cluster
Apply momentum boost/penalty
This two-stage process reduces learning time - instead of choosing among 6 policies from scratch, system first narrows to 1-2 policies per cluster, then optimizes within cluster.
Risk Management & Position Sizing
Dynamic Kelly Criterion Sizing (Optional)
Traditional Fixed Sizing Challenge:
Using the same position size for all signal probabilities may be suboptimal. Higher-probability signals could justify larger positions, lower-probability signals smaller positions.
Kelly Formula:
f = (p × b - q) / b
Where:
p = win probability (from signal score)
q = loss probability (1 - p)
b = win/loss ratio (average_win / average_loss)
f = fraction of capital to risk
RPD Implementation:
Uses Fractional Kelly (1/4 Kelly default) for safety. Full Kelly is theoretically optimal but can recommend large position sizes. Fractional Kelly reduces volatility while maintaining adaptive sizing benefits.
Enhancements:
Probability Bonus: Normalize(prob, 65, 95) × 0.5 multiplier
Divergence Bonus: Additional sizing on divergence signals
Regime Bonus: Additional sizing during strong trends (ADX >30)
Momentum Adjustment: Hot policies receive sizing boost, cold policies receive reduction
Safety Rails:
Minimum: 1 contract (floor)
Maximum: User-defined cap (default 10 contracts)
Portfolio Heat: Max total risk across all positions (default 4% equity)
Multi-Mode Stop Loss System
ATR Mode (Default):
Stop = entry ± (ATR × base_mult × policy_mult)
Consistent risk sizing
Ignores market structure
Best for: Futures, forex, algorithmic trading
Structural Mode:
Finds swing low (long) or high (short) over last 20 bars
Identifies fractal pivots within lookback
Places stop below/above structure + buffer (0.1× ATR)
Best for: Stocks, instruments that respect structure
Hybrid Mode (Intelligent):
Attempts structural stop first
Falls back to ATR if:
Structural level is invalid (beyond entry)
Structural stop >2× ATR away (too wide)
Best for: Mixed instruments, adaptability
Dynamic Adjustments:
Breakeven: Move stop to entry + 1 tick after 1.0R profit
Trailing: Trail stop 0.8R behind price after 1.5R profit
Timeout: Force close after 30 bars (optional)
Tiered Entry System
Challenge: Equal sizing on all signals may not optimize capital allocation relative to signal quality.
Solution:
Tier 1 (40% of size): Enters immediately on all signals
Tier 2 (60% of size): Enters only if probability ≥ Tier 2 trigger (default 75%)
Example:
Calculated optimal size: 10 contracts
Signal probability: 72%
Tier 2 trigger: 75%
Result: Enter 4 contracts only (Tier 1)
Same signal at 80% probability
Result: Enter 10 contracts (4 Tier 1 + 6 Tier 2)
Effect: Automatically scales size to signal quality, optimizing capital allocation.
Performance Optimization & Learning Curve
Warmup Phase (First 50 Trades)
Purpose: Ensure all policies get tested before system focuses on preferred strategies.
Modifications During Warmup:
Probability thresholds reduced 20% (65% becomes 52%)
Entropy thresholds increased 20% (more permissive)
Exploration rate stays high (30%)
Confidence width (α) doubled (more exploration)
Why This Matters:
Without warmup, system might commit to early-performing policy without testing alternatives. Warmup forces thorough exploration before focusing on best-performing strategies.
Curriculum Learning
Phase 1 (Trades 1-50): Exploration
Warmup active
All policies tested
High exploration (30%)
Learning fundamental patterns
Phase 2 (Trades 50-100): Refinement
Warmup ended, thresholds normalize
Exploration decaying (30% → 15%)
Policy preferences emerging
Meta-learning optimizing
Phase 3 (Trades 100-200): Specialization
Exploration low (15% → 8%)
Clear policy preferences established
Momentum tracking fully active
System focusing on learned patterns
Phase 4 (Trades 200+): Maturity
Exploration minimal (8% → 5%)
Regime-policy relationships learned
Auto-adaptation to market shifts
Stable performance expected
Convergence Indicators
System is learning well when:
Policy switch rate decreasing over time (initially ~50%, should drop to <20%)
Exploration rate decaying smoothly (30% → 5%)
One or two policies emerge with >50% selection frequency
Performance metrics stabilizing over time
Consistent behavior in similar market conditions
System may need adjustment when:
Policy switch rate >40% after 100 trades (excessive exploration)
Exploration rate not decaying (parameter issue)
All policies showing similar selection (not differentiating)
Performance declining despite relaxed thresholds (underlying signal issue)
Highly erratic behavior after learning phase
Advanced Features
Attention Mechanism (Extreme Mode)
Challenge: Not all features are equally important. Trading hour might matter more than price-volume correlation, but standard approaches treat them equally.
Solution:
Each RFF dimension has an importance weight . After each trade:
Calculate correlation: sign(feature - 0.5) × sign(reward)
Update importance: importance += correlation × 0.01
Clamp to range
Effect: Important features get amplified in RFF transformation, less important features get suppressed. System learns which features correlate with successful outcomes.
Temporal Context (Extreme Mode)
Challenge: Current market state alone may be incomplete. Historical context (was volatility rising or falling?) provides additional information.
Solution:
Includes 3-period historical context with exponential decay (0.85):
Current features (weight 1.0)
1 bar ago (weight 0.85)
2 bars ago (weight 0.72)
Effect: Captures momentum and acceleration of market features. System learns patterns like "rising volatility with falling entropy" that may precede significant moves.
Transfer Learning via Episodic Memory
Short-Term Memory (STM):
Last 20 trades
Fast adaptation to immediate regime
High learning rate
Long-Term Memory (LTM):
Condensed historical patterns
Preserved knowledge from past regimes
Low learning rate
Transfer Mechanism:
When STM fills (20 trades), patterns consolidated into LTM . When similar regime recurs later, LTM provides faster adaptation than starting from scratch.
Practical Implementation Guide - Recommended Settings by Instrument
Futures (ES, NQ, CL):
Adaptive Period: 20-25
ML Mode: Advanced
RFF Dimensions: 16
Policies: 6
Base Risk: 1.5%
Stop Mode: ATR or Hybrid
Timeframe: 5-15 min
Forex Majors (EURUSD, GBPUSD):
Adaptive Period: 25-30
ML Mode: Advanced
RFF Dimensions: 16
Policies: 6
Base Risk: 1.0-1.5%
Stop Mode: ATR
Timeframe: 5-30 min
Cryptocurrency (BTC, ETH):
Adaptive Period: 20-25
ML Mode: Extreme (handles non-stationarity)
RFF Dimensions: 32 (captures complexity)
Policies: 6
Base Risk: 1.0% (volatility consideration)
Stop Mode: Hybrid
Timeframe: 15 min - 4 hr
Stocks (Large Cap):
Adaptive Period: 25-30
ML Mode: Advanced
RFF Dimensions: 16
Policies: 5-6
Base Risk: 1.5-2.0%
Stop Mode: Structural or Hybrid
Timeframe: 15 min - Daily
Scaling Strategy
Phase 1 (Testing - First 50 Trades):
Max Contracts: 1-2
Goal: Validate system on your instrument
Monitor: Performance stabilization, learning progress
Phase 2 (Validation - Trades 50-100):
Max Contracts: 2-3
Goal: Confirm learning convergence
Monitor: Policy stability, exploration decay
Phase 3 (Scaling - Trades 100-200):
Max Contracts: 3-5
Enable: Kelly sizing (1/4 Kelly)
Goal: Optimize capital efficiency
Monitor: Risk-adjusted returns
Phase 4 (Full Deployment - Trades 200+):
Max Contracts: 5-10
Enable: Full momentum tracking
Goal: Sustained consistent performance
Monitor: Ongoing adaptation quality
Limitations & Disclaimers
Statistical Limitations
Learning Sample Size: System requires minimum 50-100 trades for basic convergence, 200+ trades for robust learning. Early performance (first 50 trades) may not reflect mature system behavior.
Non-Stationarity Risk: Markets change over time. A system trained on one market regime may need time to adapt when conditions shift (typically 30-50 trades for adjustment).
Overfitting Possibility: With 16-32 RFF dimensions and 6 policies, system has substantial parameter space. Small sample sizes (<200 trades) increase overfitting risk. Mitigated by regularization (λ) and fractional Kelly sizing.
Technical Limitations
Computational Complexity: Extreme mode with 32 RFF dimensions, 6 policies, and full RL stack requires significant computation. May perform slowly on lower-end systems or with many other indicators loaded.
Pine Script Constraints:
No true matrix inversion (uses diagonal approximation for LinUCB)
No cryptographic RNG (uses market data as entropy)
No proper random number generation for RFF (uses deterministic pseudo-random)
These approximations reduce mathematical precision compared to academic implementations but remain functional for trading applications.
Data Requirements: Needs clean OHLCV data. Missing bars, gaps, or low liquidity (<100k daily volume) can degrade signal quality.
Forward-Looking Bias Disclaimer
Reward Calculation Uses Future Data: The RL system evaluates trades using an 8-bar forward-looking window. This means when a position enters at bar 100, the reward calculation considers price movement through bar 108.
Why This is Disclosed:
Entry signals do NOT look ahead - decisions use only data up to entry bar
Forward data used for learning only, not signal generation
In live trading, system learns identically as bars unfold in real-time
Simulates natural learning process (outcomes are only known after trades complete)
Implication: Backtested metrics reflect this 8-bar evaluation window. Live performance may vary if:
- Positions held longer than 8 bars
- Slippage/commissions differ from backtest settings
- Market microstructure changes (wider spreads, different execution quality)
Risk Warnings
No Guarantee of Profit: All trading involves substantial risk of loss. Machine learning systems can fail if market structure fundamentally changes or during unprecedented events.
Maximum Drawdown: With 1.5% base risk and 4% max total risk, expect potential drawdowns. Historical drawdowns do not predict future drawdowns. Extreme market conditions can exceed expectations.
Black Swan Events: System has not been tested under: flash crashes, trading halts, circuit breakers, major geopolitical shocks, or other extreme events. Such events can exceed stop losses and cause significant losses.
Leverage Risk: Futures and forex involve leverage. Adverse moves combined with leverage can result in losses exceeding initial investment. Use appropriate position sizing for your risk tolerance.
System Failures: Code bugs, broker API failures, internet outages, or exchange issues can prevent proper execution. Always monitor automated systems and maintain appropriate safeguards.
Appropriate Use
This System Is:
✅ A machine learning framework for adaptive strategy selection
✅ A signal generation system with probabilistic scoring
✅ A risk management system with dynamic sizing
✅ A learning system designed to adapt over time
This System Is NOT:
❌ A price prediction system (does not forecast exact prices)
❌ A guarantee of profits (can and will experience losses)
❌ A replacement for due diligence (requires monitoring and understanding)
❌ Suitable for complete beginners (requires understanding of ML concepts, risk management, and trading fundamentals)
Recommended Use:
Paper trade for 100 signals before risking capital
Start with minimal position sizing (1-2 contracts) regardless of calculated size
Monitor learning progress via dashboard
Scale gradually over several months only after consistent results
Combine with fundamental analysis and broader market context
Set account-level risk limits (e.g., maximum drawdown threshold)
Never risk more than you can afford to lose
What Makes This System Different
RPD implements academically-derived machine learning algorithms rather than simple mathematical calculations or optimization:
✅ LinUCB Contextual Bandits - Algorithm from WWW 2010 conference (Li et al.)
✅ Random Fourier Features - Kernel approximation from NIPS 2007 (Rahimi & Recht)
✅ Q-Learning, TD(λ), REINFORCE - Standard RL algorithms from Sutton & Barto textbook
✅ Meta-Learning - Learning rate adaptation based on feature correlation
✅ Online Learning - Real-time updates from streaming data
✅ Hierarchical Policies - Two-stage selection with clustering
✅ Momentum Tracking - Recent performance analysis for faster adaptation
✅ Attention Mechanism - Feature importance weighting
✅ Transfer Learning - Episodic memory consolidation
Key Differentiators:
Actually learns from trade outcomes (not just parameter optimization)
Updates model parameters in real-time (true online learning)
Adapts to changing market regimes (not static rules)
Improves over time through reinforcement learning
Implements published ML algorithms with proper citations
Conclusion
RPD Machine Learning represents a different approach from traditional technical analysis to adaptive, self-learning systems . Instead of manually optimizing parameters (which can overfit to historical data), RPD learns behavior patterns from actual trading outcomes in your specific market.
The combination of contextual bandits, reinforcement learning, random fourier features, hierarchical policy selection, and momentum tracking creates a multi-algorithm learning system designed to handle non-stationary markets better than static approaches.
After the initial learning phase (50-100 trades), the system achieves autonomous adaptation - automatically discovering which strategies work in current conditions and shifting allocation without human intervention. This represents an approach where systems adapt over time rather than remaining static.
Use responsibly. Paper trade extensively. Scale gradually. Understand that past performance does not guarantee future results and all trading involves risk of loss.
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
Any Strategy BacktestA simple script for backtesting your strategies with TP and SL settings. For this to work, your indicators must have sources for long and short conditions.
Qullamagi EMA Breakout Autotrade (Crypto Futures L+S)Title: Qullamagi EMA Breakout – Crypto Autotrade
Overview
A crypto-focused, Qullamagi-style EMA breakout strategy built for autotrading on futures and perpetual swaps.
It combines a 5-MA trend stack (EMA 10/20, SMA 50/100/200), volatility contraction boxes, volume spikes and an optional higher-timeframe 200-MA filter. The script supports both long and short trades, partial take profit, trailing MA exits and percent-of-equity position sizing for automated crypto futures trading.
Key Features (Crypto)
Qullamagi MA Breakout Engine – trades only when price is aligned with a strong EMA/SMA trend and breaks out of a tight consolidation range. Longs use: Close > EMA10 > EMA20 > SMA50 > SMA100 > SMA200. Shorts are the mirror condition with all MAs sloping in the trend direction.
Strict vs Loose Modes – Strict (Daily) is designed for cleaner swing trades on 1H–4H (full MA stack, box+ATR and volume filters, optional HTF filter). Loose (Intraday) focuses on 10/20/50 alignment with relaxed filters for more frequent 15m–30m signals.
Volatility & Volume Filters for Crypto – ATR-based box height limit to detect volatility contraction, wide-candle filter to avoid chasing exhausted breakouts, and a volume spike condition requiring current volume to exceed an SMA of volume.
Higher-Timeframe Trend Filter (Optional) – uses a 200-period SMA on a higher timeframe (default: 1D). Longs only when HTF close is above the HTF 200-SMA, shorts only when it is below, helping avoid trading against dominant crypto trends.
Autotrade-Oriented Trade Management – position size as % of equity, initial stop anchored to a chosen MA (EMA10 / EMA20 / SMA50) with optional buffer, partial take profit at a configurable R-multiple, trailing MA exit for the remainder, and an optional cooldown after a full exit.
Markets & Timeframes
Best suited for BTC, ETH and major altcoin futures/perpetuals (Binance, Bybit, OKX, etc.).
Strict preset: 1H–4H charts for classic Qullamagi-style trend structure and fewer fake breakouts.
Loose preset: 15m–30m charts for higher trade frequency and more active intraday trading.
Always retune ATR length, box length, volume multiplier and position size for each symbol and exchange.
Strategy Logic (Quick Summary)
Long (Strict): MA stack in bullish alignment with all MAs sloping up → tight volatility box (ATR-based) → volume spike above SMA(volume) × multiplier → breakout above box high (close or intrabar) → optional HTF close above 200-SMA.
Short: Mirror logic: bearish MA stack, tight box, volume spike and breakdown below box low with optional HTF downtrend.
Best Practices for Crypto
Backtest on each symbol and timeframe you plan to autotrade, including commissions and slippage.
Start on higher timeframes (1H/4H) to learn the behavior, then move to 15m–30m if you want more signals.
Use the higher-timeframe filter when markets are strongly trending to reduce counter-trend trades.
Keep position-size percentage conservative until you fully understand the drawdowns.
Forward-test / paper trade before connecting to live futures accounts.
Webhook / Autotrade Integration
Designed to work with TradingView webhooks and external crypto trading bots.
Alert messages include structured fields such as: EVENT=ENTRY / SCALE_OUT / EXIT, SIDE=LONG / SHORT, STRATEGY=Qullamagi_MA.
Map each EVENT + SIDE combination to your bot logic (open long/short, partial close, full close, etc.) on your preferred exchange.
Important Notes & Disclaimer
Crypto markets are highly volatile and can change regime quickly. Backtest and forward-test thoroughly before using real capital. Higher timeframes generally produce cleaner MA structures and fewer fake breakouts.
This strategy is for educational and informational purposes only and does not constitute financial advice. Trading leveraged crypto products involves substantial risk of loss. Always do your own research, manage risk carefully, and never trade with money you cannot afford to lose.
AlosAlgoAlosAlgo Version: 1 BETA
A multi-timeframe, ATR-driven trend strategy with flexible entry engines (Open/Close vs Renko), optional HTF Heikin Ashi filtering, and a built-in 3-stage take-profit model designed to be backtested on TradingView and automated via webhooks.
Трендовые линии с продвинутыми стопамиtrend analysis strategy can work in every trend on the market.
Fractal Break Strategy with Time FilterThis strategy isn't complete yet but just curious how fast they will take it down. It is based off breaks of fractals and then taking the High/Low of the break candle
Fractional Candlestick Long Only Experimental V4 Another example of use an idea of Fractional Candlestick , based on mathematical rules of Fractional Calculus , typical kernel Caputo-Fabrizio ( CF ) and Atangana-Baleanu is used, alfa factor ( esential for calculation ) is in range 0,1-0.9.
Let's fun with this script .
ATR + ATR 전략It is a strong trend strategy based on ATR and ADX. Optimized for 15 installments of Bitcoin futures.
KELTNER + ADX 전략It's a trend strategy based on the Keltner channel and ADX. It's optimized for the Bitcoin Futures 15 Distribution Chart.
GMH : Tech Bubble Good Morning Holding
Simulating How to Ride the Bubble — and Jump Out Before the Crash
Be careful! Most simulation results show that this strategy sometimes underperforms a simple buy-and-hold, because it gives away positions during deep retracements and buys back at higher thresholds.
Humans often struggle with cutting losses. When the pain becomes too much, they lose the confidence needed to execute even a reasonable strategy.
But in terms of mentality, this approach reduces long-term portfolio volatility. It helps investors feel more at peace, especially during real market crashes like the tech bubble in 2021.
How to use : Select TimeFrame 4HR on trading view
Trilok saini EMA Pullback + MACD + ADX Strategy📌 HA Double EMA Pullback + MACD + ADX Strategy — Description
This strategy combines Heikin Ashi candles, Double EMA pullbacks, MACD momentum filtering, and ADX trend-strength confirmation to generate high-probability trend-continuation signals.
It is designed to avoid choppy markets and focus only on strong trending conditions.
🔥 Key Features
1️⃣ Heikin Ashi Trend Analysis
Heikin Ashi candles are calculated on the selected timeframe.
They smooth out market noise to highlight clear bullish or bearish trends.
Trend direction is displayed in a live info table.
2️⃣ Double EMA Pullback Logic
The main signal engine of this strategy:
Buy conditions
Price crosses above EMA 20
EMA 20 > EMA 50 (confirming uptrend)
A pullback is detected using the back-step (price was above EMA earlier)
MACD + ADX filters approve the trade
Sell conditions
Price crosses below EMA 20
EMA 20 < EMA 50 (confirming downtrend)
Pullback confirmation based on earlier price action
MACD + ADX filters approve the trade
This logic focuses on trend continuation instead of reversal setups.
3️⃣ MACD Momentum Filter
Buy signals appear only when MACD histogram is positive (green).
Sell signals appear only when MACD histogram is negative (red).
Prevents entries during weak or directionless momentum.
4️⃣ ADX Trend Strength Filter
Signals are blocked when ADX is below the selected threshold.
Ensures trades happen only in strong trending markets, reducing false signals.
5️⃣ Visual Enhancements
Clean Heikin Ashi candles with customizable colors
Optional regular candles for comparison
EMA overlays on HA candles
Buy/Sell labels with customizable text
Info table showing:
Trend direction
HA close
Regular close
EMA values
ADX reading
Active filters
🎯 Ideal Use Cases
Trend-following traders
Swing traders
Intraday traders who want filtered signals
Anyone wanting fewer false signals in sideways markets
⚠️ Disclaimer
This script is for educational and research purposes only.
Past performance does not guarantee future results. Always backtest and use proper risk management.
LiquiBreak — Semi-Automatic Breakout, Gap & Trend-Filter StrategLiquiBreak is a semi-automatic breakout + gap detection strategy that combines pivots, a volatility filter and an optional Supertrend direction check to generate entry signals. It can optionally place take-profit and stop-loss orders in points. Use it to highlight high-probability breakout/gap setups and to automate exits when you want — otherwise treat its signals as trade alerts that require your confirmation.
📌 LiquiBreak — Semi-Automatic Breakout, Gap & Trend Strategy
1. Overview
1. LiquiBreak is a semi-automatic breakout + gap strategy designed to catch high-quality moves with volatility confirmation.
2. Uses pivot-based support/resistance , gap detection , Supertrend filtering , and optional automatic TP/SL in points .
3. Works on all assets and timeframes, especially effective on XAUUSD, Indices, Crypto and FX pairs .
---
2. What This Script Detects
1. Breakouts above resistance and below support during strong volatility.
2. Bullish & bearish gap patterns confirmed with momentum sequences.
3. Dynamic volatility zones based on normalized ATR ranges.
4. Optional Supertrend trend direction for filtering bad signals.
5. Automatic TP/SL orders when enabled.
---
3. Recommended Indicators to Combine With
To increase accuracy and reduce false breakouts:
1. Supertrend (included) – best for trend direction.
2. EMA 9/21 or EMA 20/50 – confirms trend strength & pullbacks.
3. RSI or Stoch RSI – avoid overbought/oversold breakouts.
4. VWAP – institutional bias & fair value zones.
5. CPR / Pivot Points – confluence with breakout levels.
6. MACD – trend confirmation on higher timeframe.
7. Volume Profile (optional) – find breakout liquidity zones.
These indicators help filter low-quality signals without affecting the script’s core logic.
---
4. Key Features
1. Volatility-based pivot support & resistance .
2. Reliable breakout confirmation using real-time volatility strength.
3. Strong gap pattern detection with ATR threshold.
4. Optional Supertrend confirmation for safer entries.
5. Point-based Take Profit / Stop Loss .
6. Toggle on/off: Longs, Shorts, TP, SL .
7. Semi-automatic execution — not fully automated.
8. Clean, optimized structure for stability and speed.
---
5. Inputs / Settings
1. Pivot / Levels Period – defines structural S/R levels.
2. Volatility Filter (%) – prevents low-quality signals.
3. TP Points – automatic take-profit target.
4. SL Points – automatic stop-loss.
5. Enable TP / Enable SL – full exit control.
6. Allow Long / Allow Short – direction control.
7. Supertrend Filter – filter weak counter-trend trades.
---
6. How to Use the Strategy
1. Select timeframe & tune pivot/volatility settings.
2. Enable/disable automatic TP/SL based on your style.
3. Turn ON Supertrend for safer trend-based trades.
4. Confirm signals using EMA, RSI, VWAP, Volume or CPR.
5. Watch for high-volatility breakouts near key levels.
6. Use multiple timeframe analysis for stronger confirmation.
---
7. Important Warning (User Must Monitor Trades)
⚠ This script is NOT a fully automatic bot.
1. You MUST monitor the chart while using this strategy.
2. You MUST manually close trades if market conditions change.
3. Auto TP/SL helps, but during news events or fast markets, slippage may occur.
4. Treat this script as a signal + entry assistant , not a fire-and-forget system.
---
8. Best Practices
1. Works best on XAUUSD, NAS100, BTC, ETH, EURUSD .
2. Avoid major news unless experienced.
3. Increase volatility filter during choppy markets.
4. Use M15–H1 for clean breakouts; M5 for scalping.
5. For beginners: keep TP/SL enabled for safety.
6. Backtest first → then paper trade → then live trade.
---
9. Disclaimer
1. For educational and research purposes only .
2. Not financial advice.
3. User is fully responsible for their trades and risk.
4. Past performance does not guarantee future results.
KDH v2.0 (English) Trading Strategy Indicator# KDH Diamond Strategy v3.3 - TradingView Description
---
## 🇬🇧 ENGLISH VERSION
### 📊 KDH Diamond Strategy v3.3
**Professional High-Leverage Futures Trading System**
---
#### 🎯 Overview
KDH Diamond is an advanced algorithmic trading strategy specifically optimized for **1-hour timeframe futures trading** with high-leverage environments. Built on proven institutional concepts including Fair Value Gaps (FVG), Volume Profile analysis, and multi-layered confirmation filters, this strategy delivers consistent results without repainting.
---
#### ✨ Key Features
**🔥 Optimized for 1H Timeframe**
- Extensively backtested across multiple markets
- Highest profit rate achieved on 1-hour charts
- Perfect for swing traders and active position management
**🎨 No Repainting - 100% Reliable Signals**
- All signals are confirmed and locked on bar close
- What you see in backtest is what you get in real-time
- Complete transparency with `calc_on_order_fills=true`
**💎 Automated Risk Management**
- Automatic Stop Loss and Take Profit calculation
- Intelligent SL/TP placement based on market structure
- Built-in position sizing controls (adjustable % per trade)
**🚀 High-Leverage Futures Optimized**
- Designed specifically for leveraged futures trading
- Risk-reward ratios calibrated for 10-20x leverage environments
- Precision entry timing to maximize profit potential
**🔄 Advanced Position Management**
- Automatic reversal entries at TP levels
- Multiple re-entry opportunities per signal
- Dynamic trade management based on market conditions
**🎛️ Multi-Layer Confirmation System**
- **SMA50 Filter (1H)**: Trend alignment confirmation
- **Momentum Filter**: KAMA-based directional strength
- **RSI Divergence Filter**: Reversal detection at extremes
- **Volume Profile Filter**: Order flow and liquidity analysis
---
#### 📈 How It Works
**Signal Generation**
The strategy identifies **Inverted Fair Value Gaps (IFVG)** - institutional order blocks that signal high-probability reversal or continuation zones. Each signal is validated through multiple confirmation filters before execution.
**Entry Logic**
- Limit orders placed at optimal price levels within FVG zones
- Price must touch the midline and close in favorable direction
- All filters must align for signal activation
**Exit Strategy**
- Stop Loss: Placed at the next opposing FVG level
- Take Profit: Calculated using nearest FVG in profit direction
- Automatic reversal entry option at TP levels
**Visual System**
- Color-coded boxes show FVG zones (green/red)
- Real-time position tracking with entry, SL, and TP lines
- Comprehensive dashboard displaying filter status and P&L
---
#### 🎯 Who Is This For?
✅ **Perfect For:**
- Futures traders using 10-20x leverage
- Traders seeking systematic, rule-based strategies
- Those who want automated SL/TP management
- 1-hour chart swing traders
- Traders familiar with institutional concepts (FVG, order flow)
❌ **Not Ideal For:**
- Scalpers (designed for 1H timeframe)
- Spot-only traders (optimized for leveraged futures)
- Beginners unfamiliar with leverage risks
- Set-and-forget automated trading (requires monitoring)
---
#### 📊 What You Get
**Strategy Features:**
- Complete FVG detection and inversion system
- 4 professional-grade confirmation filters
- Automated SL/TP calculation and placement
- TP reversal entry system
- Volume Profile sentiment analysis
- Real-time position tracking dashboard
- Webhook alert support for automation
- Clean, organized code with detailed comments
**Visual Components:**
- FVG boxes with inversion coloring
- Volume Profile sentiment boxes (optional)
- Entry, SL, and TP lines for each position
- Position status table with live P&L
- Filter status dashboard
---
#### ⚙️ Customization Options
**Adjustable Filters (User Control):**
- SMA50 Filter (1H) - Trend alignment ON/OFF
- Momentum Filter - Directional strength ON/OFF
- RSI Divergence Filter - Reversal detection ON/OFF
- Volume Profile Filter - Order flow analysis ON/OFF
**Fixed Parameters (Optimized):**
- All core parameters are pre-optimized for 1H timeframe
- Ensures consistent performance without overwhelming options
- Prevents parameter over-fitting by users
---
#### ⚠️ Important Disclaimers
**Risk Warning:**
This strategy is designed for leveraged futures trading, which carries substantial risk. High leverage (10-20x) can result in rapid losses. Only trade with capital you can afford to lose.
**Performance:**
Past performance does not guarantee future results. Always backtest on your specific market and timeframe before live trading.
**Usage:**
This is a trading tool, not financial advice. Users are responsible for their own trading decisions and risk management.
**Requirements:**
- Understanding of futures trading and leverage
- Familiarity with Fair Value Gaps and institutional concepts
- Ability to monitor positions (not fully automated)
- Proper risk management discipline
---
#### 🔧 Technical Specifications
- **Platform:** TradingView Pine Script v5
- **Type:** Strategy (with backtesting capabilities)
- **Timeframe:** Optimized for 1H (works on other timeframes)
- **Markets:** Any futures market (crypto, stocks, indices, forex)
- **Repainting:** NO - All signals are final on bar close
- **Alerts:** Full webhook support for automation
- **Default Settings:** 10% position size, pyramiding enabled (max 10 positions)
---
#### 📞 Support
Questions about setup or usage? Contact the author through TradingView messages.
**Note:** This indicator is for educational and trading tool purposes only. The author is not responsible for trading losses. Trade responsibly and within your risk tolerance.
QQQ Momentum Regime Rider (EMA + VWAP + ADX + Vol Pullback)My strategy catches intraday momentum, has a phenomenal return of 18% annually
OPPLIGER SMA Stufen-TP Strategie (200/100/50/25) mit Reentry✔️ 5.- transaction costs
✔️ 7% Stop-Loss
✔️ 3 Take-Profit SMA-levels
✔️ Reentry via SMA100 correction
✔️ Reentry via SMA25/SMA50 crossover
✔️ New REENTRY rule after Stop-Loss
→ only if SMA stack is bullish AND the 3rd & 4th candle after SL are above SMA25
SMA Stufen-TP Strategie (200/100/50/25) mit ReentryStrategy Description for TradingView: Multi-SMA Momentum & Reentry System
This Pine Script strategy, named "SMA Stufen-TP Strategie (200/100/50/25) mit Reentry," is a Long-Only trend-following system designed to capitalize on upward momentum and capture significant gains while incorporating sophisticated logic for reentry after corrections.
The system relies on four Simple Moving Averages (SMAs): SMA 200, SMA 100, SMA 50, and SMA 25. These indicators are used to define the trend structure, trigger entries, and set dynamic, layered Take-Profit (TP) levels.
Entry Rules
The strategy has one main entry and two specific reentry triggers:
Main Entry (Standard Trend): A long position is opened when the price crosses above the SMA 200. This acts as the initial signal for a strong, long-term uptrend.
Reentry 1 (Medium Correction): This reentry is sought after an official exit (Stop Loss or Take Profit). It is permitted if the SMA 100 is above the SMA 200 and two conditions are met: the price previously dipped below the SMA 100 during the correction, and it now closes two consecutive bars above the SMA 100. This targets a confirmed bounce within an overall bullish structure.
Reentry 2 (Deep Correction/Momentum Shift): This triggers during a deep correction where all shorter SMAs (100, 50, 25) are below the SMA 200. Reentry occurs when the SMA 25 crosses above the SMA 50, signaling a powerful short-term momentum shift that precedes a larger recovery.
Exit and Take-Profit Logic
Exits are governed by a prioritized system including a fixed Stop Loss and three dynamic Take-Profit stages.
A. Stop Loss (Highest Priority)
The primary risk control is a fixed Stop Loss at -10% below the entry price. This is always the first exit condition checked.
B. Layered Take-Profits (TP)
Profits are secured using a step-wise mechanism that trails the price using the shorter SMAs, but only after specific profit thresholds are met. This ensures that the strategy provides ample room for a strong rally while securing gains as the trend matures.
TP Stage 1: Activated when the price first crosses above the SMA 100. The position is closed if the profit reaches 10% or more and the price closes two consecutive bars below the SMA 100.
TP Stage 2: Activated when the price first crosses above the SMA 50. The position is closed if the profit reaches 20% or more and the price closes two consecutive bars below the SMA 50.
TP Stage 3: Activated when the price first crosses above the SMA 25. The position is closed if the profit reaches 40% or more and the price closes two consecutive bars below the SMA 25.
The exit priority ensures that the tightest active stop is used: Stop Loss takes precedence, followed by TP 3 (the highest profit and tightest trail), then TP 2, and finally TP 1.
Range Oscillator Strategy + Stoch Confirm🔹 Short summary
This is a free, educational long-only strategy built on top of the public “Range Oscillator” by Zeiierman (used under CC BY-NC-SA 4.0), combined with a Stochastic timing filter, an EMA-based exit filter and an optional risk-management layer (SL/TP and R-multiple exits). It is NOT financial advice and it is NOT a magic money machine. It’s a structured framework to study how range-expansion + momentum + trend slope can be combined into one rule-based system, often with intentionally RARE trades.
────────────────────────
0. Legal / risk disclaimer
────────────────────────
• This script is FREE and public. I do not charge any fee for it.
• It is for EDUCATIONAL PURPOSES ONLY.
• It is NOT financial advice and does NOT guarantee profits.
• Backtest results can be very different from live results.
• Markets change over time; past performance is NOT indicative of future performance.
• You are fully responsible for your own trades and risk.
Please DO NOT use this script with money you cannot afford to lose. Always start in a demo / paper trading environment and make sure you understand what the logic does before you risk any capital.
────────────────────────
1. About default settings and risk (very important)
────────────────────────
The script is configured with the following defaults in the `strategy()` declaration:
• `initial_capital = 10000`
→ This is only an EXAMPLE account size.
• `default_qty_type = strategy.percent_of_equity`
• `default_qty_value = 100`
→ This means 100% of equity per trade in the default properties.
→ This is AGGRESSIVE and should be treated as a STRESS TEST of the logic, not as a realistic way to trade.
TradingView’s House Rules recommend risking only a small part of equity per trade (often 1–2%, max 5–10% in most cases). To align with these recommendations and to get more realistic backtest results, I STRONGLY RECOMMEND you to:
1. Open **Strategy Settings → Properties**.
2. Set:
• Order size: **Percent of equity**
• Order size (percent): e.g. **1–2%** per trade
3. Make sure **commission** and **slippage** match your own broker conditions.
• By default this script uses `commission_value = 0.1` (0.1%) and `slippage = 3`, which are reasonable example values for many crypto markets.
If you choose to run the strategy with 100% of equity per trade, please treat it ONLY as a stress-test of the logic. It is NOT a sustainable risk model for live trading.
────────────────────────
2. What this strategy tries to do (conceptual overview)
────────────────────────
This is a LONG-ONLY strategy designed to explore the combination of:
1. **Range Oscillator (Zeiierman-based)**
- Measures how far price has moved away from an adaptive mean.
- Uses an ATR-based range to normalize deviation.
- High positive oscillator values indicate strong price expansion away from the mean in a bullish direction.
2. **Stochastic as a timing filter**
- A classic Stochastic (%K and %D) is used.
- The logic requires %K to be below a user-defined level and then crossing above %D.
- This is intended to catch moments when momentum turns up again, rather than chasing every extreme.
3. **EMA Exit Filter (trend slope)**
- An EMA with configurable length (default 70) is calculated.
- The slope of the EMA is monitored: when the slope turns negative while in a long position, and the filter is enabled, it triggers an exit condition.
- This acts as a trend-protection exit: if the medium-term trend starts to weaken, the strategy exits even if the oscillator has not yet fully reverted.
4. **Optional risk-management layer**
- Percentage-based Stop Loss and Take Profit (SL/TP).
- Risk/Reward (R-multiple) exit based on the distance from entry to SL.
- Implemented as OCO orders that work *on top* of the logical exits.
The goal is not to create a “holy grail” system but to serve as a transparent, configurable framework for studying how these concepts behave together on different markets and timeframes.
────────────────────────
3. Components and how they work together
────────────────────────
(1) Range Oscillator (based on “Range Oscillator (Zeiierman)”)
• The script computes a weighted mean price and then measures how far price deviates from that mean.
• Deviation is normalized by an ATR-based range and expressed as an oscillator.
• When the oscillator is above the **entry threshold** (default 100), it signals a strong move away from the mean in the bullish direction.
• When it later drops below the **exit threshold** (default 30), it can trigger an exit (if enabled).
(2) Stochastic confirmation
• Classic Stochastic (%K and %D) is calculated.
• An entry requires:
- %K to be below a user-defined “Cross Level”, and
- then %K to cross above %D.
• This is a momentum confirmation: the strategy tries to enter when momentum turns up from a pullback rather than at any random point.
(3) EMA Exit Filter
• The EMA length is configurable via `emaLength` (default 70).
• The script monitors the EMA slope: it computes the relative change between the current EMA and the previous EMA.
• If the slope turns negative while the strategy holds a long position and the filter is enabled, it triggers an exit condition.
• This is meant to help protect profits or cut losses when the medium-term trend starts to roll over, even if the oscillator conditions are not (yet) signalling exit.
(4) Risk management (optional)
• Stop Loss (SL) and Take Profit (TP):
- Defined as percentages relative to average entry price.
- Both are disabled by default, but you can enable them in the Inputs.
• Risk/Reward Exit:
- Uses the distance from entry to SL to project a profit target at a configurable R-multiple.
- Also optional and disabled by default.
These exits are implemented as `strategy.exit()` OCO orders and can close trades independently of oscillator/EMA conditions if hit first.
────────────────────────
4. Entry & Exit logic (high level)
────────────────────────
A) Time filter
• You can choose a **Start Year** in the Inputs.
• Only candles between the selected start date and 31 Dec 2069 are used for backtesting (`timeCondition`).
• This prevents accidental use of tiny cherry-picked windows and makes tests more honest.
B) Entry condition (long-only)
A long entry is allowed when ALL the following are true:
1. `timeCondition` is true (inside the backtest window).
2. If `useOscEntry` is true:
- Range Oscillator value must be above `entryLevel`.
3. If `useStochEntry` is true:
- Stochastic condition (`stochCondition`) must be true:
- %K < `crossLevel`, then %K crosses above %D.
If these filters agree, the strategy calls `strategy.entry("Long", strategy.long)`.
C) Exit condition (logical exits)
A position can be closed when:
1. `timeCondition` is true AND a long position is open, AND
2. At least one of the following is true:
- If `useOscExit` is true: Oscillator is below `exitLevel`.
- If `useMagicExit` (EMA Exit Filter) is true: EMA slope is negative (`isDown = true`).
In that case, `strategy.close("Long")` is called.
D) Risk-management exits
While a position is open:
• If SL or TP is enabled:
- `strategy.exit("Long Risk", ...)` places an OCO stop/limit order based on the SL/TP percentages.
• If Risk/Reward exit is enabled:
- `strategy.exit("RR Exit", ...)` places an OCO order using a projected R-multiple (`rrMult`) of the SL distance.
These risk-based exits can trigger before the logical oscillator/EMA exits if price hits those levels.
────────────────────────
5. Recommended backtest configuration (to avoid misleading results)
────────────────────────
To align with TradingView House Rules and avoid misleading backtests:
1. **Initial capital**
- 10 000 (or any value you personally want to work with).
2. **Order size**
- Type: **Percent of equity**
- Size: **1–2%** per trade is a reasonable starting point.
- Avoid risking more than 5–10% per trade if you want results that could be sustainable in practice.
3. **Commission & slippage**
- Commission: around 0.1% if that matches your broker.
- Slippage: a few ticks (e.g. 3) to account for real fills.
4. **Timeframe & markets**
- Volatile symbols (e.g. crypto like BTCUSDT, or major indices).
- Timeframes: 1H / 4H / **1D (Daily)** are typical starting points.
- I strongly recommend trying the strategy on **different timeframes**, for example 1D, to see how the behaviour changes between intraday and higher timeframes.
5. **No “caution warning”**
- Make sure your chosen symbol + timeframe + settings do not trigger TradingView’s caution messages.
- If you see warnings (e.g. “too few trades”), adjust timeframe/symbol or the backtest period.
────────────────────────
5a. About low trade count and rare signals
────────────────────────
This strategy is intentionally designed to trade RARELY:
• It is **long-only**.
• It uses strict filters (Range Oscillator threshold + Stochastic confirmation + optional EMA Exit Filter).
• On higher timeframes (especially **1D / Daily**) this can result in a **low total number of trades**, sometimes WELL BELOW 100 trades over the whole backtest.
TradingView’s House Rules mention 100+ trades as a guideline for more robust statistics. In this specific case:
• The **low trade count is a conscious design choice**, not an attempt to cherry-pick a tiny, ultra-profitable window.
• The goal is to study a **small number of high-conviction long entries** on higher timeframes, not to generate frequent intraday signals.
• Because of the low trade count, results should NOT be interpreted as statistically strong or “proven” – they are only one sample of how this logic would have behaved on past data.
Please keep this in mind when you look at the equity curve and performance metrics. A beautiful curve with only a handful of trades is still just a small sample.
────────────────────────
6. How to use this strategy (step-by-step)
────────────────────────
1. Add the script to your chart.
2. Open the **Inputs** tab:
- Set the backtest start year.
- Decide whether to use Oscillator-based entry/exit, Stochastic confirmation, and EMA Exit Filter.
- Optionally enable SL, TP, and Risk/Reward exits.
3. Open the **Properties** tab:
- Set a realistic account size if you want.
- Set order size to a realistic % of equity (e.g. 1–2%).
- Confirm that commission and slippage are realistic for your broker.
4. Run the backtest:
- Look at Net Profit, Max Drawdown, number of trades, and equity curve.
- Remember that a low trade count means the statistics are not very strong.
5. Experiment:
- Tweak thresholds (`entryLevel`, `exitLevel`), Stochastic settings, EMA length, and risk params.
- See how the metrics and trade frequency change.
6. Forward-test:
- Before using any idea in live trading, forward-test on a demo account and observe behaviour in real time.
────────────────────────
7. Originality and usefulness (why this is more than a mashup)
────────────────────────
This script is not intended to be a random visual mashup of indicators. It is designed as a coherent, testable strategy with clear roles for each component:
• Range Oscillator:
- Handles mean vs. range-expansion states via an adaptive, ATR-normalized metric.
• Stochastic:
- Acts as a timing filter to avoid entering purely on extremes and instead waits for momentum to turn.
• EMA Exit Filter:
- Trend-slope-based safety net to exit when the medium-term direction changes against the position.
• Risk module:
- Provides practical, rule-based exits: SL, TP, and R-multiple exit, which are useful for structuring risk even if you modify the core logic.
It aims to give traders a ready-made **framework to study and modify**, not a black box or “signals” product.
────────────────────────
8. Limitations and good practices
────────────────────────
• No single strategy works on all markets or in all regimes.
• This script is long-only; it does not short the market.
• Performance can degrade when market structure changes.
• Overfitting (curve fitting) is a real risk if you endlessly tweak parameters to maximise historical profit.
Good practices:
- Test on multiple symbols and timeframes.
- Focus on stability and drawdown, not only on how high the profit line goes.
- View this as a learning tool and a basis for your own research.
────────────────────────
9. Licensing and credits
────────────────────────
• Core oscillator idea & base code:
- “Range Oscillator (Zeiierman)”
- © Zeiierman, licensed under CC BY-NC-SA 4.0.
• Strategy logic, Stochastic confirmation, EMA Exit Filter, and risk-management layer:
- Modifications by jokiniemi.
Please respect both the original license and TradingView House Rules if you fork or republish any part of this script.
────────────────────────
10. No payments / no vendor pitch
────────────────────────
• This script is completely FREE to use on TradingView.
• There is no paid subscription, no external payment link, and no private signals group attached to it.
• If you have questions, please use TradingView’s comment system or private messages instead of expecting financial advice.
Use this script as a tool to learn, experiment, and build your own understanding of markets.
────────────────────────
11. Example backtest settings used in screenshots
────────────────────────
To avoid any confusion about how the results shown in screenshots were produced, here is one concrete example configuration:
• Symbol: BTCUSDT (or similar major BTC pair)
• Timeframe: 1D (Daily)
• Backtest period: from 2018 to the most recent data
• Initial capital: 10 000
• Order size type: Percent of equity
• Order size: 2% per trade
• Commission: 0.1%
• Slippage: 3 ticks
• Risk settings: Stop Loss and Take Profit disabled by default, Risk/Reward exit disabled by default
• Filters: Range Oscillator entry/exit enabled, Stochastic confirmation enabled, EMA Exit Filter enabled
If you change any of these settings (symbol, timeframe, risk per trade, commission, slippage, filters, etc.), your results will look different. Please always adapt the configuration to your own risk tolerance, market, and trading style.






















