Cognex Fibonacci Breakout StrategyTHE COMPLETE TRADE LOGIC (What We Want):
Step 1: Morning Session (9:30-10:30)
Track session high and low
Step 2: After 10:30 - Wait for Breakout
Bullish: Close above session high
Bearish: Close below session low
Step 3: Track Extreme After Breakout
Keep updating highest_after_breakout or lowest_after_breakout
This continuously updates as price makes new extremes
Step 4: Detect 28% Retracement (THE LOCK)
When price retraces to 28%, set last_extreme_for_retracement to the current extreme
This LOCKS the extreme for fibonacci calculations
fib_100 should use this locked value
Step 5: Place Limit Order EARLY (at 20% retracement)
When price retraces to 20%, place limit order at 28% entry
This is so the order is ready when price hits 28%
Step 6: Cancel & Recalculate if New Extreme
If price makes a NEW extreme AFTER the order is placed
Cancel the old order
Wait for new 20% retracement to place new order
Step 7: One Trade Per Day
Only ONE order placement attempt per day
Even if cancelled, don't try again
Indikator dan strategi
TSI.LTA | Base BTC 1DTSI.LTA | Base BTC 1D is a closed‑source trend‑following strategy designed for BTC on the 1D timeframe .
It focuses on participating in the main directional moves of the market while avoiding as much short‑term noise as possible.
📊 The script:
Uses a combination of moving‑average–based filters and volatility bands to define the active trend.
Applies optional volume filters to avoid low‑participation or exhausted moves.
Includes risk‑management controls (Stop Loss, Take Profit, Trailing Stop) that work on a per‑trade basis.
All entries and exits are confirmed at bar close and the script does not repaint .
This makes it suitable for backtesting, alerts and external automation.
█ 💡 CONCEPTS
This strategy is built around a few simple ideas:
1 — Trend first.
Positions are only taken when a group of smoothed trend filters agree on direction.
The goal is to ride larger swings, not to scalp each fluctuation.
2 — Volatility awareness.
Standard‑deviation–based bands help avoid entries in abnormal spikes or during very compressed ranges.
3 — Participation filter.
Optional volume‑based conditions (VWMA, OBV slope, MFI, volume Z‑score) try to ensure that entries occur when the market shows enough activity, not during dead phases.
4 — Risk defined in advance.
Stop‑loss and trailing‑stop inputs are expressed as percentages relative to entry price, so users can align them with their own risk tolerance.
The logic is purposely conservative: it is expected to stay flat during parts of the market where the trend is unclear or participation is weak.
█ ⚙️ FEATURES & INPUTS
This section follows approximately the order of the script’s inputs, so users can read here and then match what they see in the “Inputs” tab.
1 — 📐 Trend filters
These inputs control how the strategy detects the underlying trend:
DEMA / Gaussian / SMMA lengths
Control how fast or slow the trend reacts to price changes.
Shorter lengths → more responsive, more trades, more noise.
Longer lengths → slower reaction, fewer trades, more filtering.
Volatility Bands (SD length & multipliers)
Standard‑deviation bands around the smoothed price series.
They are used to avoid entries during extreme moves or very narrow ranges where a breakout is not yet confirmed.
In practice, these settings let the user choose between a more “aggressive” trend follower (shorter lengths, smaller bands) or a more “patient” one.
2 — 📊 Volume filters (optional)
These filters are meant to restrict trades to periods where the market shows meaningful participation:
VWMA filter
Requires price to be aligned with a Volume‑Weighted Moving Average, which de‑emphasizes moves on very low volume.
OBV slope filter
Uses the slope of On‑Balance Volume to check that net volume flow supports the direction of the trade.
MFI band filter
Uses the Money Flow Index to avoid taking new entries in zones that often correspond to exhaustion (extreme values defined by the user).
Volume Z‑Score
Compares current volume to its recent history. Trades can be restricted when volume is unusually low or out of character for that period.
When any of these filters are turned off, the strategy relies only on price‑based trend and volatility logic.
When they are on, trades are more selective and may be fewer.
3 — 🛡️ Risk management
These inputs define how individual trades are managed once entered.
They do not change the trend logic itself:
Stop Loss (%)
A percentage move against the entry price that will close the position.
Typical values on BTC 1D remain in the single‑digit range so that no single trade risks an unrealistic portion of equity.
Take Profit (%)
An optional fixed target that closes the trade when price has moved a chosen percentage in favor.
This can be disabled if the user prefers to let the trend filters perform the exit.
Trailing Stop (%)
A stop that follows the most favorable price reached since entry.
When the “use lower timeframe peak” option is enabled, peaks can be detected on a lower timeframe for more granular trailing, while decisions still occur at the close of the 1D bar.
Fixed SL/TP Price and Activation Date
Allow defining absolute price levels and a date from which they start applying.
This is useful when the user wants structural protection around known price zones.
The combination of these controls determines how deep a pullback the user is willing to tolerate and how much profit they are prepared to give back in order to stay in trends.
4 — 🚫 Filter failure & cooldown
To avoid over‑trading in difficult environments, the script can:
Automatically exit when filters remain unfavorable for a configurable number of bars.
Enter a cooldown period, during which no new trades are taken, even if some conditions improve.
These mechanisms are intended to protect capital during choppy or low‑quality phases rather than force constant exposure.
█ 📚 HOW TO USE
A suggested process for using this strategy as a study tool:
1 — Start on BTC 1D.
Apply the script to BTCUSD or BTC/USDT on the 1D timeframe, with default inputs.
2 — Open the Strategy Tester.
Choose a time window (for example a full halving cycle, a crash + recovery period, or just the most recent bull leg).
3 — Compare with Buy & Hold.
For the same window, look at:
Net profit of the strategy vs Buy & Hold.
Max drawdown of the strategy vs Buy & Hold.
The goal is not to hit a particular number, but to see whether, in that window, the strategy manages to:
Provide a smoother equity curve (lower drawdown),
While still performing at least as well as, or better than, simply holding the asset.
4 — Experiment with risk inputs.
Vary Stop Loss, Trailing Stop and the volume filters.
After each change, re‑check the same two questions above. This should make clear how each input affects the trade‑off between participation and risk.
5 — Forward‑test.
Before using any configuration with real capital, let it run for a while in paper‑trading or demo conditions.
█ 🚧 LIMITATIONS
The strategy is built and tuned primarily for BTC on 1D.
It can be used on other symbols and timeframes, but behavior may differ and requires new testing.
In very tight ranges or during event‑driven gaps, trend logic may enter later than discretionary trading would. This is expected for a conservative trend‑following approach.
Results from historical backtests depend on data quality, broker settings, fees and slippage configured in the Strategy Tester.
█ 📝 NOTES
Signals are generated on bar close.
The script is closed‑source, but the description explains the main ideas so users and moderators can understand what it does and how to use it.
The HUD on the chart is meant as a compact summary of the same statistics available in the Strategy Tester; it simply makes comparisons quicker.
█ ⚠️ DISCLAIMER
This strategy is provided for educational and research purposes only .
It is not financial advice and does not recommend any specific trades, assets, position sizes, or risk levels.
Users are fully responsible for:
Choosing their own risk parameters (Stop Loss, Take Profit, Trailing Stop, position sizing, etc.).
Testing the script on the markets and timeframes they intend to trade.
Verifying that any configuration is appropriate for their capital, risk tolerance and jurisdiction.
Past performance in backtests or examples does not guarantee future results.
Always test carefully before considering any live deployment.
RubberBand Scalp NQ Strategy (V6 - High PF Focus)
================================================================================
RUBBERBAND SCALP NQ (V6 - HIGH PF FOCUS)
================================================================================
// STRATEGY OVERVIEW
// -----------------
// Instrument: NQ (Nasdaq 100 E-mini Futures)
// Style: Intraday mean-reversion scalping
// Core Idea: Price "stretches" away from VWAP, then "snaps back" → enter on strong reversal
// Session: 9:00 AM – 2:30 PM CST (America/Chicago)
// Timeframe: 1–5 min (ideal: 2–3 min)
// Position: 2 contracts, pyramiding = 0
// Commission: $2.00 per contract
// Goal: High Profit Factor via asymmetric exits (1R fixed + unlimited runner)
// KEY FILTERS
// -----------
// • Only trade when ATR(15) > 5.0 points (~$100 range) → avoids chop
// • Must be in session → forces flat at 2:30 PM
// • VWAP proximity: price must touch within 0.5 × ATR of VWAP
// ENTRY LOGIC (LONG)
// -----------------
// 1. In session & no position
// 2. Close > Open (bullish bar)
// 3. Close > highest high of last 4 bars → momentum confirmation
// 4. Close > VWAP
// 5. Low < VWAP + (0.5 × ATR) → pullback reached VWAP zone
// 6. ATR > 5.0
// 7. Bar confirmed
// → Plot green triangle below bar
// ENTRY LOGIC (SHORT) – Symmetric
// -----------------
// 1. Close < Open
// 2. Close < lowest low of last 4 bars
// 3. Close < VWAP
// 4. High > VWAP - (0.5 × ATR)
// 5. ATR > 5.0
// → Plot red triangle above bar
// STOP LOSS – DUAL SYSTEM (Widest Stop Wins)
// -----------------------------------------
// VWAP Stop (Long): VWAP - 0.20
// ATR Stop (Long): Close - min(ATR × 1.0, 15.0)
// Final Stop: MAX(VWAP Stop, ATR Stop) → then CAP at Close - 0.20
// Short: MIN of both → FLOOR at Close + 0.20
// → Max buffer: 0.20 pts = $20 (4 ticks)
// → Risk = |Entry – Final Stop|
// PROFIT TAKING – 2 CONTRACTS
// ---------------------------
// Contract #1: Fixed 1R → limit = entry + risk (long) / entry - risk (short)
// Contract #2: Trailing stop only → trail_points = risk, trail_offset = 0
// NO FIXED TAKE PROFIT ON RUNNER → lets 3R, 5R, 10R+ winners run
// BUG: Short runner uses trail_offset = 1.5 → CHANGE TO 0
// V6 IMPROVEMENTS
// ---------------
// 1. ATR_STOP_MULTIPLIER reduced from 1.5 → 1.0 → tighter average loss
// 2. Removed fixed 2R cap on runner → unlimited upside
// 3. Widest-stop logic → prevents premature stop-outs
// TRADE EXAMPLE (LONG)
// -------------------
// Entry: 18,125 (2 contracts)
// Stop: 18,110 → Risk = $300/contract
// 1R: 18,155 → Contract #1 exits (+$600)
// Runner trails by $300 → exits at 18,425 (+$6,000)
// Total P&L: +$6,600
// PERFORMANCE EXPECTATIONS
// ------------------------
// Win Rate: 40–50%
// Avg Winner: >3× avg loser
// Profit Factor: 2.0–3.5+
// Max Drawdown: <5% (with risk controls)
// DAILY CHECKLIST
// ---------------
// 2–3 min NQ chart
// Timezone: America/Chicago
// ATR > 5.0
// Price touched VWAP zone
// 4-bar breakout confirmed
// trail_offset = 0 (both sides)
// Alerts on
// Log R-multiple
// FINAL NOTES
// -----------
// This is a PROFIT FACTOR system — not a high win-rate system.
// Success = discipline + volatility + clean execution.
================================================================================
GOLDM Dow Theory – 1H Trend + 5m Pullback1. Strategy Overview
Instrument: MCX GOLDM
Chart timeframe: 5 minutes
Side: Long-only
Position size: Fixed 3 lots
Core idea:
Trade only in 1H uptrend, enter after a 5m pullback and breakout, with basic volume/volatility filters and ATR-based SL/TP.
2. High-Level Logic Flow (Per Bar)
On every 5-minute bar, the script does this:
Update session/time, volume, and ATR filters
Read 1H trend from higher timeframe
Update 5m pullback state (whether a valid dip happened)
Check if there is a valid breakout back in the direction of the 1H trend
If all filters + conditions align → enter Long (3 lots)
While in a trade:
Manage SL/TP using ATR
Close trade if 1H trend flips down or price closes below 5m EMA
Everything else (plots, alerts) is just for visibility and convenience.
3. Inputs & Configuration
Main inputs:
pullbackLookback – how many 5m bars to look back to detect a pullback
breakoutLookback – how many bars to consider for recent swing high
emaLenTrendFast / emaLenTrendSlow – 1H EMAs (50/200) for trend
emaLenPullback – 5m EMA used for pullback logic (default 20)
tradeSession – default "0900-2315" (you can change)
volLookback, volMult – volume filter
atrLen, atrSmaLen – ATR filter
slATRmult (1.4), tpATRmult (3.0) – ATR multiples → ~1.4 : 3 RR
4. Session / Time Filter
tradeSession = "0900-2315"
inSession = not useSessionFilter or not na(time(timeframe.period, tradeSession))
Only allows entries when the current bar’s time is inside 09:00–23:15.
If useSessionFilter is false, this filter is ignored.
No trade opens outside this window, but existing trades can still exit.
5. Volume & Volatility Filters
Volume Filter
avgVol = ta.sma(volume, volLookback)
highVolume = not useVolumeFilter or (volume > avgVol * volMult)
If enabled, current bar’s volume must be greater than average volume × multiplier.
Purpose: avoid thin, illiquid periods.
ATR Filter
atr5 = ta.atr(atrLen)
atrSma = ta.sma(atr5, atrSmaLen)
goodATR = not useATRFilter or (atr5 > atrSma)
If enabled, current ATR must be above its own moving average.
Purpose: avoid flat / extremely low-volatility periods.
Only if both highVolume and goodATR are true, the system considers entering.
6. Higher Timeframe Trend (1H)
emaFast1h = request.security(syminfo.tickerid, "60", ta.ema(close, emaLenTrendFast), ...)
emaSlow1h = request.security(syminfo.tickerid, "60", ta.ema(close, emaLenTrendSlow), ...)
trendUp = emaFast1h > emaSlow1h
trendDown = emaFast1h < emaSlow1h
On the 1-hour timeframe:
If EMA Fast (50) > EMA Slow (200) → trendUp = true
If EMA Fast (50) < EMA Slow (200) → trendDown = true
This is the core trend filter:
We only look for longs when trendUp is true.
7. 5-Minute Structure Logic (Dow-style)
7.1 Pullback Detection
emaPull = ta.ema(close, emaLenPullback)
pulledBackLong = ta.lowest(close, pullbackLookback) < emaPull
A pullback is defined as:
In the last pullbackLookback bars, price closed below the 5m EMA (emaPull) at least once.
This indicates a dip against the 1H uptrend.
A state flag tracks this:
var bool hadLongPullback = false
hadLongPullback := trendUp and pulledBackLong ? true : (not trendUp ? false : hadLongPullback)
When:
trendUp AND pulledBackLong → hadLongPullback = true.
If the trend stops being up (trendUp = false), flag resets to false.
So the system remembers:
“There has been a proper dip while the 1H uptrend is active.”
7.2 Breakout Confirmation
recentHigh = ta.highest(high, pullbackLookback)
breakoutUp = close > recentHigh
After a pullback, we wait for price to close above the highest high of recent bars (excluding the current one).
This mimics:
“Higher high after a higher low” → breakout in Dow Theory terms.
8. Final Long Entry Logic
The base entry condition:
baseLongEntry =
trendUp and
hadLongPullback and
breakoutUp and
close > emaPull
Translated:
1H trend is up (trendUp).
A valid pullback happened recently (hadLongPullback).
Current candle broke above the recent swing high (breakoutUp).
Price is now back above the 5m EMA (pullback is resolving, not deepening).
Then filters are applied:
longEntryCond =
baseLongEntry and
inSession and
highVolume and
goodATR and
not isLong
So a long entry only occurs if:
Core structure conditions (baseLongEntry) are true
Time is within session
Volume is high enough
ATR is healthy
You are not already in a long
When longEntryCond is true:
if longEntryCond
strategy.entry("Long", strategy.long, comment = "Dow Long: Trend+PB+BO")
hadLongPullback := false
Enters 3 lots long (as per default_qty_type + default_qty_value).
Resets hadLongPullback so we don’t re-use the same pullback.
9. Exit Logic
There are two exit layers:
9.1 Logical Exit (Trend or Structure Change)
exitLongTrendFlip = trendDown
exitLongEMA = ta.crossunder(close, emaPull)
longExitCond = isLong and (exitLongTrendFlip or exitLongEMA)
If in a long:
Exit when trend flips down (1H EMA50 < EMA200), OR
Price crosses below 5m EMA (pullback may be turning into reversal).
Then:
if longExitCond
strategy.close("Long", comment = "Exit Long: Trend flip / EMA break")
This closes the position at market (on bar close).
9.2 ATR-based Stop Loss & Take Profit
if useSLTP and isLong
longStop = strategy.position_avg_price - atr5 * slATRmult
longLimit = strategy.position_avg_price + atr5 * tpATRmult
strategy.exit("Long SLTP", "Long", stop = longStop, limit = longLimit)
SL = entry price – 1.4 × ATR(14, 5m)
TP = entry price + 3.0 × ATR(14, 5m)
This gives roughly 1.4 : 3 RR.
If SL or TP is hit, strategy.exit will close the trade.
So exits can come from:
Hitting Stop Loss
Hitting Take Profit
OR logic-based exit (trend flip / EMA break)
10. Alerts
Two alertconditions:
alertcondition(longEntryCond, title="Long Entry Signal",
message="GOLDM LONG: 1H Uptrend + 5m Pullback Breakout + Filters OK")
alertcondition(longExitCond, title="Long Exit Signal",
message="GOLDM LONG EXIT: Trend flip or EMA break")
You can set TradingView alerts based on:
“Long Entry Signal” → tells you when all entry conditions align.
“Long Exit Signal” → tells you when the logic-based exit triggers.
(ATR SL/TP exits won’t auto-alert unless you separately set price alerts or add extra conditions.)
11. Mental Model Summary (How YOU should think about it)
For every trade, the system is basically doing this:
Is GOLDM in an uptrend on 1H?
→ If no: do nothing
Did we get a clear dip below 5m EMA in that uptrend?
→ If no: wait
Did price then break above recent highs and reclaim EMA20?
→ If yes: this is our Dow-style continuation entry
Is market liquid and moving (volume + ATR)?
→ If yes: go Long with 3 lots
Manage with:
ATR SL & TP
Exit early if 1H trend flips or price falls back below EMA20
SP500 Session Gap Fade StrategySummary in one paragraph
SPX Session Gap Fade is an intraday gap fade strategy for index futures, designed around regular cash sessions on five minute charts. It helps you participate only when there is a full overnight or pre session gap and a valid intraday session window, instead of trading every open. The original part is the gap distance engine which anchors both stop and optional target to the previous session reference close at a configurable flat time, so every trade’s risk scales with the actual gap size rather than a fixed tick stop.
Scope and intent
• Markets. Primarily index futures such as ES, NQ, YM, and liquid index CFDs that exhibit overnight gaps and regular cash hours.
• Timeframes. Intraday timeframes from one minute to fifteen minutes. Default usage is five minute bars.
• Default demo used in the publication. Symbol CME:ES1! on a five minute chart.
• Purpose. Provide a simple, transparent way to trade opening gaps with a session anchored risk model and forced flat exit so you are not holding into the last part of the session.
• Limits. This is a strategy. Orders are simulated on standard candles only.
Originality and usefulness
• Unique concept or fusion. The core novelty is the combination of a strict “full gap” entry condition with a session anchored reference close and a gap distance based TP and SL engine. The stop and optional target are symmetric multiples of the actual gap distance from the previous session’s flat close, rather than fixed ticks.
• Failure mode it addresses. Fixed sized stops do not scale when gaps are unusually small or unusually large, which can either under risk or over risk the account. The session flat logic also reduces the chance of holding residual positions into late session liquidity and news.
• Testability. All key pieces are explicit in the Inputs: session window, minutes before session end, whether to use gap exits, whether TP or SL are active, and whether to allow candle based closes and forced flat. You can toggle each component and see how it changes entries and exits.
• Portable yardstick. The main unit is the absolute price gap between the entry bar open and the previous session reference close. tp_mult and sl_mult are multiples of that gap, which makes the risk model portable across contracts and volatility regimes.
Method overview in plain language
The strategy first defines a trading session using exchange time, for example 08:30 to 15:30 for ES day hours. It also defines a “flat” time a fixed number of minutes before session end. At the flat bar, any open position is closed and the bar’s close price is stored as the reference close for the next session. Inside the session, the strategy looks for a full gap bar relative to the prior bar: a gap down where today’s high is below yesterday’s low, or a gap up where today’s low is above yesterday’s high. A full gap down generates a long entry; a full gap up generates a short entry. If the gap risk engine is enabled and a valid reference close exists, the strategy measures the distance between the entry bar open and that reference close. It then sets a stop and optional target as configurable multiples of that gap distance and manages them with strategy.exit. Additional exits can be triggered by a candle color flip or by the forced flat time.
Base measures
• Range basis. The main unit is the absolute difference between the current entry bar open and the stored reference close from the previous session flat bar. That value is used as a “gap unit” and scaled by tp_mult and sl_mult to build the target and stop.
Components
• Component one: Gap Direction. Detects full gap up or full gap down by comparing the current high and low to the previous bar’s high and low. Gap down signals a long fade, gap up signals a short fade. There is no smoothing; it is a strict structural condition.
• Component two: Session Window. Only allows entries when the current time is within the configured session window. It also defines a flat time before the session end where positions are forced flat and the reference close is updated.
• Component three: Gap Distance Risk Engine. Computes the absolute distance between the entry open and the stored reference close. The stop and optional target are placed as entry ± gap_distance × multiplier so that risk scales with gap size.
• Optional component: Candle Exit. If enabled, a bullish bar closes short positions and a bearish bar closes long positions, which can shorten holding time when price reverses quickly inside the session.
• Session windows. Session logic uses the exchange time of the chart symbol. When changing symbols or venues, verify that the session time string still matches the new instrument’s cash hours.
Fusion rule
All gates are hard conditions rather than weighted scores. A trade can only open if the session window is active and the full gap condition is true. The gap distance engine only activates if a valid reference close exists and use_gap_risk is on. TP and SL are controlled by separate booleans so you can use SL only, TP only, or both. Long and short are symmetric by construction: long trades fade full gap downs, short trades fade full gap ups with mirrored TP and SL logic.
Signal rule
• Long entry. Inside the active session, when the current bar shows a full gap down relative to the previous bar (current high below prior low), the strategy opens a long position. If the gap risk engine is active, it places a gap based stop below the entry and an optional target above it.
• Short entry. Inside the active session, when the current bar shows a full gap up relative to the previous bar (current low above prior high), the strategy opens a short position. If the gap risk engine is active, it places a gap based stop above the entry and an optional target below it.
• Forced flat. At the configured flat time before session end, any open position is closed and the close price of that bar becomes the new reference close for the following session.
• Candle based exit. If enabled, a bearish bar closes longs, and a bullish bar closes shorts, regardless of where TP or SL sit, as long as a position is open.
What you will see on the chart
• Markers on entry bars. Standard strategy entry markers labeled “long” and “short” on the gap bars where trades open.
• Exit markers. Standard exit markers on bars where either the gap stop or target are hit, or where a candle exit or forced flat close occurs. Exit IDs “long_gap” and “short_gap” label gap based exits.
• Reference levels. Horizontal lines for the current long TP, long SL, short TP, and short SL while a position is open and the gap engine is enabled. They update when a new trade opens and disappear when flat.
• Session background. This version does not add background shading for the session; session logic runs internally based on time.
• No on chart table. All decisions are visible through orders and exit levels. Use the Strategy Tester for performance metrics.
Inputs with guidance
Session Settings
• Trading session (sess). Session window in exchange time. Typical value uses the regular cash session for each contract, for example “0830-1530” for ES. Adjust if your broker or symbol uses different hours.
• Minutes before session end to force exit (flat_before_min). Minutes before the session end where positions are forced flat and the reference close is stored. Typical range is 15 to 120. Raising it closes trades earlier in the day; lowering it allows trades later in the session.
Gap Risk
• Enable gap based TP/SL (use_gap_risk). Master switch for the gap distance exit engine. Turning it off keeps entries and forced flat logic but removes automatic TP and SL placement.
• Use TP limit from gap (use_gap_tp). Enables gap based profit targets. Typical values are true for structured exits or false if you want to manage exits manually and only keep a stop.
• Use SL stop from gap (use_gap_sl). Enables gap based stop losses. This should normally remain true so that each trade has a defined initial risk in ticks.
• TP multiplier of gap distance (tp_mult). Multiplier applied to the gap distance for the target. Typical range is 0.5 to 2.0. Raising it places the target further away and reduces hit frequency.
• SL multiplier of gap distance (sl_mult). Multiplier applied to the gap distance for the stop. Typical range is 0.5 to 2.0. Raising it widens the stop and increases risk per trade; lowering it tightens the stop and may increase the number of small losses.
Exit Controls
• Exit with candle logic (use_candle_exit). If true, closes shorts on bullish candles and longs on bearish candles. Useful when you want to react to intraday reversal bars even if TP or SL have not been reached.
• Force flat before session end (use_forced_flat). If true, guarantees you are flat by the configured flat time and updates the reference close. Turn this off only if you understand the impact on overnight risk.
Filters
There is no separate trend or volatility filter in this version. All trades depend on the presence of a full gap bar inside the session. If you need extra filtering such as ATR, volume, or higher timeframe bias, they should be added explicitly and documented in your own fork.
Usage recipes
Intraday conservative gap fade
• Timeframe. Five minute chart on ES regular session.
• Gap risk. use_gap_risk = true, use_gap_tp = true, use_gap_sl = true.
• Multipliers. tp_mult around 0.7 to 1.0 and sl_mult around 1.0.
• Exits. use_candle_exit = false, use_forced_flat = true. Focus on the structured TP and SL around the gap.
Intraday aggressive gap fade
• Timeframe. Five minute chart.
• Gap risk. use_gap_risk = true, use_gap_tp = false, use_gap_sl = true.
• Multipliers. sl_mult around 0.7 to 1.0.
• Exits. use_candle_exit = true, use_forced_flat = true. Entries fade full gaps, stops are tight, and candle color flips flatten trades early.
Higher timeframe gap tests
• Timeframe. Fifteen minute or sixty minute charts on instruments with regular gaps.
• Gap risk. Keep use_gap_risk = true. Consider slightly higher sl_mult if gaps are structurally wider on the higher timeframe.
• Note. Expect fewer trades and be careful with sample size; multi year data is recommended.
Properties visible in this publication
• On average our risk for each position over the last 200 trades is 0.4% with a max intraday loss of 1.5% of the total equity in this case of 100k $ with 1 contract ES. For other assets, recalculations and customizations has to be applied.
• Initial capital. 100 000.
• Base currency. USD.
• Default order size method. Fixed with size 1 contract.
• Pyramiding. 0.
• Commission. Flat 2 USD per order in the Strategy Tester Properties. (2$ buying + 2$selling)
• Slippage. One tick in the Strategy Tester Properties.
• Process orders on close. ON.
Realism and responsible publication
• No performance claims are made. Past results do not guarantee future outcomes.
• Costs use a realistic flat commission and one tick of slippage per trade for ES class futures.
• Default sizing with one contract on a 100 000 reference account targets modest per trade risk. In practice, extreme slippage or gap through events can exceed this, so treat the one and a half percent risk target as a design goal, not a guarantee.
• All orders are simulated on standard candles. Shapes can move while a bar is forming and settle on bar close.
Honest limitations and failure modes
• Economic releases, thin liquidity, and limit conditions can break the assumptions behind the simple gap model and lead to slippage or skipped fills.
• Symbols with very frequent or very large gaps may require adjusted multipliers or alternative risk handling, especially in high volatility regimes.
• Very quiet periods without clean gaps will produce few or no trades. This is expected behavior, not a bug.
• Session windows follow the exchange time of the chart. Always confirm that the configured session matches the symbol.
• When both the stop and target lie inside the same bar’s range, the TradingView engine decides which is hit first based on its internal intrabar assumptions. Without bar magnifier, tie handling is approximate.
Legal
Education and research only. This strategy is not investment advice. You remain responsible for all trading decisions. Always test on historical data and in simulation with realistic costs before considering any live use.
MSB Trend Breakout Strategy V7**MSB Trend Breakout Strategy V7**
This is the full, high-precision automated strategy designed for disciplined traders who understand directional price action. The script functions as a robust **entry and trade management tool** following two proprietary concepts:
**1. Trend Confirmation:** A customized Moving Average filter is utilized to ensure entries strictly align with the dominant market flow.
**2. Momentum Confirmation:** The system uses a specific short-term **multi-bar breakout range** to pinpoint high-probability entries at the start of a momentum shift, avoiding choppy market conditions.
**Key Features:**
* **Automated Risk Management:** Includes complete dynamic Stop Loss (SL) and Take Profit (TP) order management to ensure capital preservation.
* **Time Filter:** Optimizes performance by filtering signals to the most liquid Forex trading hours (01:00 to 19:00, broker time).
**PREREQUISITE FOR ACCESS:**
This is an advanced tool. To utilize the strategy effectively, the user should have a foundational understanding of directional bias and trade management principles.
---
**Important Note & Risk Disclosure:**
This strategy is published under **Invite-only** protection. The script does not provide financial advice or guarantee profits. Past performance is not indicative of future results.
ETH SuperTrend Hull Strategy - 15min Futures(重制版)🟠 ETH SuperTrend Hull Strategy - 15min Futures
Strategy Overview
The "ETH SuperTrend Hull Strategy" is a sophisticated 15-minute trading system specifically designed for Bitcoin perpetual contracts. This advanced algorithm integrates SuperTrend indicators with Hull moving averages to deliver high-precision trend following through a triple-confirmation mechanism, featuring intelligent position management and multi-level take-profit systems.
Core Value Proposition
Triple Trend Confirmation: SuperTrend + Hull MA + ATR volatility filtering
Adaptive Take-Profit System: 6-level dynamic profit targets adjusted to market conditions
Smart Position Management: Three martingale modes with automatic sizing
Real-time Webhook Integration: Direct exchange connectivity for automated execution
🟠 Technical Framework
Multi-Layer Trend Detection
Layer 1 - SuperTrend Filter
pinescript
= ta.supertrend(supertrend_factor, supertrend_atr_period)
is_supertrend_long = direction < 0 // Bullish trend line
is_supertrend_short = direction >= 0 // Bearish trend line
Layer 2 - Hull MA Confirmation
pinescript
HMA = HMA(close, 73) // Hull Moving Average
hull_is_green = HULL > HULL // Uptrend confirmation
hull_is_red = HULL <= HULL // Downtrend confirmation
Layer 3 - ATR Breakout Signals
pinescript
xATR = ta.atr(5)
nLoss = key_value * xATR // Dynamic stop distance
Entry Conditions
Long Entry:
Price breaks above ATR trailing stop
Hull MA shows green uptrend
SuperTrend indicates bullish momentum
Price positioned above Hull MA
Short Entry:
Price breaks below ATR trailing stop
Hull MA shows red downtrend
SuperTrend indicates bearish momentum
Price positioned below Hull MA
🟠 Risk Management System
Position Sizing
text
Base Position = Initial Capital × Risk % / Entry Price × Leverage
Actual Position = Base Position × Martingale Multiplier (1.0-5.0x)
Martingale Modes
4x Mode: Conservative approach, maximum 4x position scaling
5x Mode: Balanced risk management, maximum 5x scaling
5x Big Mode: Aggressive growth with faster position increases
Dynamic Take-Profit System
6-Level Profit Targets:
TP1: 2.2×ATR (Close 30%)
TP2: 4.5×ATR (Close 25%)
TP3: 7.5×ATR (Close 20%)
TP4: 10.5×ATR (Close 10%)
TP5: 15.5×ATR (Close 7%)
TP6: 20.5×ATR (Close 3%)
ATR Adaptive Adjustment:
Short-term ATR > Long-term ATR: TP distance +0.5
Short-term ATR < Long-term ATR: TP distance -0.5
🟠 Configuration Parameters
Core Settings
pinescript
// Trend Sensitivity
key_value = 2.0 // ATR multiplier (lower = more sensitive)
supertrend_factor = 3.0 // SuperTrend factor
// Risk Management
risk_percent = 19.9 // Per trade risk %
leverage = 1.0 // Leverage multiplier
Hull MA Configuration
pinescript
length = 73 // Hull period (55-200)
modeSwitch = "Hma" // Hull variant (Hma/Thma/Ehma)
🟠 Quick Start Guide
Initial Setup
Apply to BTCUSDT perpetual 15-minute chart
Configure Webhook Signal ID and User ID
Adjust position parameters according to risk preference
Signal Monitoring
Long Signals: Green arrows with Hull MA turning green
Short Signals: Red arrows with Hull MA turning red
Trend Direction: SuperTrend line color changes
Execution Workflow
Wait for triple-signal confluence
Confirm all entry conditions met
System automatically calculates position size and TP levels
Webhook sends trade instructions to connected platform
Advanced Features
Heikin-Ashi Mode: Smooth price data using Heikin-Ashi candles
Fixed Position Mode: Disable martingale, use fixed sizing
Multi-Timeframe: Higher timeframe confirmation integration
🟠 ETH SuperTrend Hull Strategy - 15min Futures
策略概述
"ETH超级趋势Hull策略"是一款专为比特币永续合约设计的15分钟短线交易系统。该策略融合超级趋势指标与Hull均线,通过三重过滤机制实现高精度趋势跟踪,具备智能仓位管理和多级止盈体系。
核心价值
三重趋势确认:Supertrend + Hull均线 + ATR波动过滤
自适应止盈系统:6级动态止盈,根据市场波动调整目标
智能仓位管理:支持三种倍投模式,自动调整仓位规模
实时Webhook通知:直连交易平台,实现自动化执行
🟠 策略原理
趋势识别系统
第一层 - 超级趋势过滤
pinescript
= ta.supertrend(supertrend_factor, supertrend_atr_period)
is_supertrend_long = direction < 0 // 绿色趋势线
is_supertrend_short = direction >= 0 // 红色趋势线
第二层 - Hull均线确认
pinescript
HMA = HMA(close, 73) // Hull移动平均线
hull_is_green = HULL > HULL // 上升趋势
hull_is_red = HULL <= HULL // 下降趋势
第三层 - ATR突破信号
pinescript
xATR = ta.atr(5)
nLoss = key_value * xATR // 动态止损距离
入场条件
多头入场:
价格突破ATR追踪止损
Hull均线呈绿色上升趋势
超级趋势显示看涨信号
价格位于Hull均线上方
空头入场:
价格跌破ATR追踪止损
Hull均线呈红色下降趋势
超级趋势显示看跌信号
价格位于Hull均线下方
🟠 风险管理
仓位计算
text
基础仓位 = 初始资金 × 风险比例% / 入场价格 × 杠杆倍数
实际仓位 = 基础仓位 × 倍投系数 (1.0-5.0倍)
倍投模式
4倍模式:保守型,最大4倍加仓
5倍模式:均衡型,最大5倍加仓
5倍大模式:激进型,更快仓位增长
动态止盈系统
6级止盈目标:
TP1: 2.2×ATR (平仓30%)
TP2: 4.5×ATR (平仓25%)
TP3: 7.5×ATR (平仓20%)
TP4: 10.5×ATR (平仓10%)
TP5: 15.5×ATR (平仓7%)
TP6: 20.5×ATR (平仓3%)
ATR自适应调整:
短期ATR > 长期ATR:止盈距离+0.5
短期ATR < 长期ATR:止盈距离-0.5
🟠 参数配置
核心参数
pinescript
// 趋势敏感度
key_value = 2.0 // ATR乘数,值越小越敏感
supertrend_factor = 3.0 // 超级趋势因子
// 风险管理
risk_percent = 19.9 // 单次交易风险%
leverage = 1.0 // 杠杆倍数
Hull均线设置
pinescript
length = 73 // Hull周期 (55-200)
modeSwitch = "Hma" // Hull变体 (Hma/Thma/Ehma)
🟠 使用指南
初始设置
添加到BTCUSDT永续合约15分钟图表
配置Webhook信号ID和用户ID
根据风险偏好调整仓位参数
信号监控
多单信号:绿色箭头,Hull均线转绿
空单信号:红色箭头,Hull均线转红
趋势方向:超级趋势线颜色变化
执行流程
等待三重信号共振
确认入场条件满足
系统自动计算仓位和止盈
通过Webhook发送交易指令
高级功能
K线均线模式:使用Heikin-Ashi平滑价格
固定仓位模式:禁用倍投,固定仓位大小
多时间框架:集成更高时间框架确认
Moving Average Band StrategyOverview
The Moving Average Band Strategy is a fully customizable breakout and trend-continuation system designed for traders who need both simplicity and control.
The strategy creates adaptive bands around a user-selected moving average and executes trades when price breaks out of these bands, with advanced risk-management settings including optional Risk:Reward targets.
This script is suitable for intraday, swing, and positional traders across all markets — equities, futures, crypto, and forex.
Key Features
✔ Six Moving Average Types
Choose the MA that best matches your trading style:
SMA
EMA
WMA
HMA
VWMA
RMA
✔ Dynamic Bands
Upper Band built from MA of highs
Lower Band built from MA of lows
Adjustable band offset (%)
Color-coded band fill indicating price position
✔ Configurable Strategy Preferences
Toggle Long and/or Short trades
Toggle Risk:Reward Take-Profit
Adjustable Risk:Reward Ratio
Default position sizing: % of equity (configurable via strategy settings)
Entry Conditions
Long Entry
A long trade triggers when:
Price crosses above the Upper Band
Long trades are enabled
No existing long position is active
Short Entry
A short trade triggers when:
Price crosses below the Lower Band
Short trades are enabled
No existing short position is active
Clear entry markers and price labels appear on the chart.
Risk Management
This strategy includes a complete set of risk-controls:
Stop-Loss (Fixed at Entry)
Long SL: Lower Band
Short SL: Upper Band
These levels remain constant for the entire trade.
Optional Risk:Reward Take-Profit
Enabled/disabled using a toggle switch.
When enabled:
Long TP = Entry + (Risk × Risk:Reward Ratio)
Short TP = Entry – (Risk × Risk:Reward Ratio)
When disabled:
Exits are handled by reverse crossover signals.
Exit Conditions
Long Exit
Stop-Loss Hit (touch-based)
Take-Profit Hit (if enabled)
Reverse Band Crossover (if TP disabled)
Short Exit
Stop-Loss Hit (touch-based)
Take-Profit Hit (if enabled)
Reverse Band Crossover (if TP disabled)
Exit markers and price labels are plotted automatically.
Visual Tools
To improve clarity:
Upper & Lower Band (blue, adjustable width)
Middle Line
Dynamic band fill (green/red/yellow)
SL & TP line plotting when in position
Entry/Exit markers
Price labels for all executed trades
These are built to help users visually follow the strategy logic.
Alerts Included
Every trading event is covered:
Long Entry
Short Entry
Long SL / TP / Cross Exit
Short SL / TP / Cross Exit
Combined Alert for webhook/automation (JSON-formatted)
Perfect for algo trading, Discord bots, or automation platforms.
Best For
This strategy performs best in:
Trending markets
Breakout environments
High-momentum instruments
Clean intraday swings
Works seamlessly on:
Stocks
Index futures
Commodities
Crypto
Forex
⚠️ Important Disclaimer
This script is for educational purposes only.
Trading involves risk. Backtest results are not indicative of future performance.
Always validate settings and use proper position sizing.
Bank nifty with RSI + SMA (Bli-Rik)best to trade for 100 points on 15 mins time frame, very rarly fails
EMA VIP STRThis strategy works on EMAS and standard deviation on both sides , the tp is decided on RSI levels. the strategy is a systematic trading setup
Adaptive Volatility StrategyHere's a professional description for publishing your indicator:
Adaptive Volatility Strategy - Multi-Indicator Confirmation System
A comprehensive trading strategy that combines multiple technical indicators with adaptive volatility filtering to identify high-probability trade setups while managing risk effectively.
Key Features:
Multi-Indicator Confirmation: Combines RSI, MACD, and ADX signals with trend analysis (20/50/200 EMAs) to reduce false signals and improve entry quality
Adaptive Volatility Filter: Intelligent volatility detection using ATR that can filter trades based on either fixed percentage thresholds or multiples of average volatility, helping avoid unstable market conditions
Flexible Session Filtering: Optional time-based trading windows with customizable hours and trading days to align with your preferred market sessions
Smart Signal Generation: Requires minimum signal confirmations before entering trades, with separate tracking for directional and confirmation signals
Comprehensive Risk Management: Configurable take profit and stop loss percentages with automatic position exits on signal reversals
Real-Time Dashboard: Visual display showing current indicator values, signals, volatility levels, and trend direction for quick market assessment
Strategy Logic:
Enters long when bullish signals outnumber bearish signals (minimum 2 signals) with ADX confirmation
Enters short when bearish signals outnumber bullish signals with ADX confirmation
All trades must pass volatility and session filters when enabled
Exits on take profit, stop loss, or signal reversal
Best Used For:
Swing trading on 1H to daily timeframes
Markets with clear trending behavior
Traders who prefer multiple confirmations before entering positions
Note: This is a complete strategy with entry/exit logic. Backtest thoroughly and adjust parameters for your specific instrument and timeframe before live trading.
FX Swing — Compact Auto-Sizing (Fixed)A compact Forex swing-trading strategy that combines higher-timeframe EMA trend bias, EMA pullback confirmation, and RSI momentum filtering. It automatically sizes positions using either risk-percentage or fixed-risk, adapts pip values for JPY and non-JPY pairs, and generates clear SL/TP levels with partial take-profit exits. The script also sends structured JSON alerts for webhooks or WhatsApp automation, making it ideal for fast, disciplined, and risk-controlled swing entries.
MOMO – Imbalance Trend (SIMPLE BUY/SELL)MOMO – Imbalance Trend (SIMPLE BUY/SELL)
This strategy combines trend breaks, imbalance detection, and first-tap supply/demand entries to create a clean and disciplined trading model.
It automatically highlights imbalance candles, draws fresh zones, and waits for the first retest to deliver precise BUY and SELL signals.
Performance
On optimized settings, this strategy shows an estimated 57%–70% win-rate, depending on the asset and timeframe.
Actual performance may vary, but the model is built for consistency, discipline, and improved decision-making.
How it works
Detects trend structure shifts (BOS / Break of Trend)
Identifies displacement (imbalance) candles
Creates supply and demand zones from imbalance origin
Waits for first tap only (no second chances)
Confirms direction using trend logic
Generates clean BUY/SELL arrows
Automatic SL/TP based on user settings
Features
Clean BUY/SELL markers
Auto-drawn supply & demand zones
Trend break markers
Imbalance tags
Smart first-tap confirmation
Customizable stop loss & take profit
Works on crypto, gold, forex, indices
Best on M5–H1 for day trading
Note
This strategy is designed for day traders who want clarity, structure, and zero emotional trading.
Use it with discipline — and it will serve you well.
Good luck, soldier.
Fractional Candlestick Long Only Experimental V10Fractional Candlestick Long-Only Strategy – Technical Description
This document provides a professional English description of the "Fractional Candlestick Long Only Experimental V6" strategy using pure CF/AB fractional kernels and wavelet-based filtering.
1. Fractional Candlesticks (CF / AB)
The strategy computes two fractional representations of price using Caputo–Fabrizio (CF) and Atangana–Baleanu (AB) kernels. These provide long-memory filtering without EMA approximations. Both CF and AB versions are applied to O/H/L/C, producing fractional candlesticks and fractional Heikin-Ashi variants.
2. Trend Stack Logic
Trend confirmation is based on a 4-component stack:
- CF close > AB close
- HA_CF close > HA_AB close
- HA_CF bullish
- HA_AB bullish
The user selects how many components must align (4, 3, or any 2).
3. Wavelet Filtering
A wavelet transform (Haar, Daubechies-4, Mexican Hat) is applied to a chosen source (e.g., HA_CF close). The wavelet response is used as:
- entry filter (4 modes)
- exit filter (4 modes)
Wavelet modes: off, confirm, wavelet-only, block adverse signals.
4. Trailing System
Trailing stop uses fractional AB low × buffer, providing long-memory dynamic trailing behavior. A fractional trend channel (CF/AB lows vs HA highs) is also plotted.
5. Exit Framework
Exit options include: stack flip, CF
Positional Supertrend Strategy (1D Filter + 2H Entry)Positional Supertrend Strategy (1D Filter + 2H Entry)
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.






















