BTC 5-MA Multi Cross Strategy By Hardik Prajapati Ai TradelabThis strategy is built around the five most powerful and commonly used moving averages in crypto trading — 5, 20, 50, 100, and 200-period SMAs (Simple Moving Averages) — applied on a 1-hour Bitcoin chart.
Core Idea:
The strategy aims to identify strong bullish trends by confirming when the price action crosses above all key moving averages. This alignment of multiple MAs indicates momentum shift and helps filter out false breakouts.
⸻
⚙️ How It Works:
1. Calculates 5 Moving Averages:
• 5 MA → Short-term momentum (fastest signal)
• 20 MA → Near-term trend confirmation
• 50 MA → Mid-term trend filter
• 100 MA → Long-term trend foundation
• 200 MA → Macro-trend direction (strongest support/resistance)
2. Buy Condition (Entry):
• A Buy is triggered when:
• The price crosses above the 5 MA, and
• The closing price remains above all other MAs (20, 50, 100, 200)
This signals that momentum is aligned across all time horizons — a strong uptrend confirmation.
3. Sell Condition (Exit):
• The position is closed when price crosses below the 20 MA, showing weakness in short-term momentum.
4. Visual Signals:
• 🟢 BUY triangle below candles → Entry signal
• 🔴 SELL triangle above candles → Exit signal
• Colored MAs plotted for trend clarity.
⸻
📈 Recommended Usage:
• Chart: BTC/USDT
• Timeframe: 1 Hour
• Type: Trend-following crossover strategy
• Ideal for: Identifying major breakout moves and confirming trend reversals.
⸻
⚠️ Notes:
• This script is meant for educational and backtesting purposes only.
• Always apply additional confirmation tools (like RSI, Volume, or VIX-style filters) before live trading.
• Works best during trending markets; may produce whipsaws in sideways zones.
المؤشرات والاستراتيجيات
Trend Catcher and Mean ReversionPlease DM if you want to use this strategy.
it took long time to make this code profitable using 3 parameters only!
it allow you to:
1- Pyramid as you see fit.
2- allow option to use trend catching strategy ( while keeping mean reversion strategy)
3- Time filter to limit trading and exit at your preferred time.
4- it works for long, short or both positions.
5- has trailing tp as an option as well while keeping initial sl as hard stop
6- tp multiple (of stop loss) is optional
ongoing working for alerts and automation. More on that for subscribers only.
i will charge the minimum fee to utilize this code as we don't need your money but we need people to support our vision.
PG DMean & Price Sync ver 9.4 - ConsolidatedPG DMean & Price Sync Strategy (SD Filter)
This strategy combines the momentum-oscillator properties of the Detrended Mean (DMean) with a Standard Deviation (SD) Price Filter for confirming trend direction, aiming to isolate high-conviction trades while actively managing risk.
🔑 Core Logic
DMean Momentum Signal: The strategy's primary engine is the DMean, which measures the percentage difference between the current closing price and a longer-term Moving Average (price_ma). It is then smoothed by a DMean Signal line (MA of the DMean).
Entry Signal: A trade is triggered when the DMean line crosses above (for Long) or below (for Short) its Signal Line, but it must clear a user-defined Dead Zone Threshold to confirm momentum commitment.
SD Filter Confirmation (Price Sync): A Standard Deviation Channel, based on a separate user-defined price source and period, is used to filter trades.
Long Filter: Allows Long entries only when the price is trading above the lower SD band, suggesting the current price action is stronger than the recent average volatility to the downside.
Short Filter: Allows Short entries only when the price is currently below the Filter Basis (SMA), confirming a bearish stance within the SD channel.
🛡️ Risk & Exit Management
Primary Exit: All trades are exited by reverse DMean Crossover/Crossunder, meaning the position is closed when the DMean momentum reverses against the open trade (e.g., DMean crosses under the Signal to exit a Long).
Hard Stop Loss (Short Trades): A mandatory percentage-based Hard Stop Loss is implemented only for short positions to protect against sudden upward price spikes, closing the trade if the loss exceeds the set percentage. (Note: This version does not include a Hard SL for Long trades).
📊 Performance Dashboard
A custom Performance Dashboard Table is displayed at the bottom right of the chart to provide real-time, at-a-glance comparison of the strategy's equity performance versus a simple Buy & Hold over the selected backtesting date range.
Crypto Scalping Strategy - High Win Rategrok first try. I used grok to create a scalping strategy that is automated for crypto scalp trading on 5-15 min intervals
Golden StrategyTitle: XAUUSD (Gold) Smart Entry Strategy with Dynamic Scaling
Description:
This is a precision-based entry strategy for XAUUSD (Gold), optimized for lower timeframes like the 5-minute and 15-minute charts. It uses a custom logic engine to detect potential reversals and applies dynamic scaling (pyramiding) to build positions strategically based on price behavior.
🔍 Key Features:
✅ Smart entry logic for trend shifts
✅ Configurable position scaling up to 7 level
✅ Built-in capital efficiency for smaller accounts
✅ Backtest window control for historical testing
✅ Compact on-screen table for user guidance
Timeframes Recommended:
🔸 15-minute: Best balance of risk and consistency
🔸 5-minute: More frequent signals, slightly higher risk
⚠️ Important Disclaimer
This script is for educational and informational purposes only. It is not financial advice or a signal service. Trading carries risk, and past performance does not guarantee future results. Use at your own discretion and always manage risk appropriately.
Trend-Following & Breakout — Index Quant Strategy (NASDAQ)📈 Trend-Following & Breakout — Index Quant Strategy (NASDAQ & S&P 500)
Type: Invite-only strategy
Markets: NASDAQ 100 (NAS100 / US100 / NQ), S&P 500 (US500 / SPX), and other major equity indices.
🧠 Concept: Continuous trend model combining EWMAC (trend-following) and Donchian (breakout) signals, scaled by forecast strength and portfolio risk.
⚙️ Execution: Rebalances only on decision-bar closes, using hysteresis and a no-trade band to reduce churn.
📊 Default bias: Long-only — aligned with equity index drift.
🧩 How it works
• EWMAC Trend: Difference between fast and slow EMAs, normalized by an EWMA of absolute returns.
• Donchian Breakout: Distance beyond a 200-bar channel (Strict mode) or relative z-score position within it.
• Forecast combination: Weighted sum of trend and breakout points, clamped to ± capPoints.
• Hysteresis: Prevents quick sign flips near zero forecast.
• Risk scaling: Maps forecast strength to position size using equity × risk budget × ATR-based stop distance.
• Rebalance: Executes only if the required quantity change exceeds the Δqty threshold; can optionally block increases on Sundays (for CFDs).
⚙️ Default parameters
Deployed on NQ / US100 / NAS100 on Daily Timeframe
• Decision timeframe = 360 min (other options from 1 min to 1 week).
• Trend (EWMAC): Fast = 64, Slow = 256, Vol Norm = 32, Weight = 0.8.
• Breakout (Donchian): Length = 200, Mode = Strict, Weight = 0.2.
• Forecast scaling: ptsPerSigma = 1.0, capPoints = 10.
• Risk % per rebalance = 4 % of equity.
• ATR stop: ATR(14) × 1.0.
• No-trade band (Δqty) = 4 units.
• Hysteresis = 2 forecast points.
• Bias = Long-only (Neutral / Long-bias 50 % optional).
• Skip Sunday increases = false (default).
📋 Backtest properties (documented)
• Initial capital = 100 000 USD.
• Commission = 0.20 % per trade.
• Pyramiding = 10.
• Calc on every tick = false.
• Point value = 1 (for NAS100 CFD).
• No financing or slippage modeled.
• If using CFDs, account for overnight funding.
• On futures (NQ / ES), carry is implicit.
📊 Typical behaviour
• Many small scratches, a few large winners.
• Performs best during multi-week / multi-month trends.
• Underperforms in tight or volatile ranges.
• Average hold ≈ 30 – 90 days in historical tests.
💡 Risk and performance guide (illustrative)
Sharpe ≈ 1.25
Sortino ≈ 1.10 – 1.30
Max drawdown ≈ –18 % to –25 %
Annual volatility ≈ 24 – 28 %
CAGR ≈ 50 – 60 % (at 4 % risk)
Edge ratio ≈ 5 (MFE / MAE)
Historical backtests only — past performance does not guarantee future results.
🌍 Intended markets and timeframes
Optimized for NASDAQ 100 and S&P 500; also effective on similar indices (DAX, Dow Jones, FTSE).
Best on Daily or higher timeframes.
Aligns with long-term index drift — suitable for long-bias systematic trend portfolios.
⚠️ Limitations
• Backtests exclude CFD funding costs.
• Trend models will have losing streaks in range-bound markets.
• Designed for experienced traders seeking systematic exposure.
🔑 Requesting access
Send a private TradingView message to with the text:
“Request access to Trend-Following & Breakout — Index Quant Strategy.”
Access is granted only on explicit request.
For further information, see my TradingView Signature.
🆕 Release notes (v1.0)
• Initial release (360 min TF): EWMAC 64/256 + Donchian 200 Strict.
• Risk 4 %, ATR × 1.0, Long-only bias, hysteresis 2 pts, Δqty ≥ 4.
• Developed for NASDAQ 100 and S&P 500 indices.
• Implements continuous risk-scaled positioning and no-trade band logic.
🧾 Originality statement
This strategy is original work built entirely from TradingView built-ins (EMA, ATR, Highest, Lowest).
It does not reuse open-source invite-only code.
Any future reuse of open scripts will be done with explicit permission and credit.
my_strategy_2.0Overview:
This is a high-speed scalping strategy optimized for volatile crypto assets (BTC, ETH, etc.) on timeframes 1m–5m. It combines trend-following SuperTrend with confirmations from MACD, RSI, Bollinger Bands, and volume spikes for precise entries. Focus on quick profits (1–3 ATR) with strict risk control: partial take-profits, stop-loss, and trailing breakeven after the first TP.
Key Signals:
Long: SuperTrend flip up + MACD crossover up + RSI >50 + BB Upper breakout + volume spike + volatility filter (ATR >0.5%).
Short: Similar but downward.
Exits and Risks:
TP: 33% at +1 ATR, 33% at +2 ATR, 34% at +3 ATR (customizable).
SL: Initial at -1 ATR, after TP1 — to breakeven with trailing on BB midline (optional).
Filters: Minimum ATR to avoid flat markets; realistic commissions in backtests.
Recommendations:
Test on 2020–2025 data (out-of-sample 2024+). Expected Win Rate ~55%, Profit Factor >1.8, Drawdown <10%. Ideal for 1–2% risk per trade. Not for beginners — use paper trading.
Disclaimer: Past results do not guarantee future performance. Trade at your own risk.
(Pine v6 code, ready for publication. Author: gopog777 with expert fixes.)
Nemesis Strategy MLWinning That's all I know
Years of research been done to this strategy It's based on algorithm that detects where the markets are going Works on crypto this strategy his excellent indicators and it can generate a lot of money if you know what you are doing and depending on the fees of the exchanges as well So be smart and be kind God bless you all
BTC 1D InOut EMA (WF + Optimizer Ready, Long-Only)BTC 1D In/Out EMA — Walk‑Forward & Optimizer‑Ready (Long‑Only)
What it is
Daily BTC trend strategy that beat buy‑and‑hold over full history with much shallower drawdowns. It includes walk‑forward windows, optimizer‑friendly inputs, realistic costs, and alert‑ready entries/exits.
Defaults
Fast EMA 13, Slow EMA 90, Exit threshold 1.5, Squeeze = Sqz Off only, Trend filter ON (EMA 100), Trailing OFF.
Execution: commission 0.06% per side, slippage 0–1 ticks, quantity % of equity, pyramiding 0.
How to use
Add to a BTC 1‑Day chart (e.g., BLX / INDEX:BTCUSD for full history; BYBIT:BTCUSDT.P or BINANCE:BTCUSDT.P for live).
Set alerts → Condition: this strategy → Order fills only → Once per bar close.
Walk‑forward modes let you test IS/OOS windows before reverting to “Whole Chart” for live alerts.
Risk
This is educational software, not investment advice. Past performance (simulated or live) does not guarantee future results. Trend strategies still incur drawdowns; size positions responsibly.
Contact / Docs
Docs: docs.google.com Support: grantlyt58+support@gmail.com
Tags: BTC, BTCUSD, Bitcoin, EMA, trend, strategy, long‑only, walk‑forward
Kz GC1! ORBStrategy that trades breakouts on GC1! futures on the 5min timeframe. It also works on MGC1! for lower drawdown and to manage Apex and Top Step accounts with the lower risk.
Risk Disclaimer:
Past results as well as strategy tester reports do not indicate future performance. Guarantees do not exist in trading. By using this strategy you risk losing all your money.
Important:
It trades all days that markets are open. Set times may be seen on settings. Trades multiple times a day sometimes.
It works on the 5 and 15min timeframe only. Results are better on 5min timeframe.
The settings are optimized already for GC1! on the 5min timeframe.
How it works:
Every trading day it measures the range of the first 15min candle of pre-selected hours. As soon as price closes above or below on the 15min timeframe, it will trade the breakout targeting a set risk to reward ratio. SL on the opposite side of the range.
Settings:
Hourly Trading Hours: These are the times that worked best for this strategy. All boxes should be checked for best results. Excluded times were when it performed bad which is why those times have been left out.
ORB Formation Period: This setting determines on which timeframe candle has to close outside the opening range box in order to take a trade. It's set to 15min by default because this is what worked by far the best
Entry Type: Entries are immediate instead of waiting for a pull back to enter on a limit order.
Limit Orders: If enabled, the strategy will place a pending order x points from the current price, instead of a market order. Immediate orders are enabled by default for a better performance. Important: It doesn't actually place a limit order. The strategy will just wait for a pullback and then enter with a market order. It's more like a hidden limit order.
Limit Order Offset Points: If you have limit orders enabled, this setting determines how many points from the current price the limit order will be placed.
FVG Detection Type: How fast it detects the fair value gaps. Standard detection over immediate had better performance
Risk Type: You can chose either between Fixed USD Amount, Risk per Trade in % or Fixed Contract Size. By default it's set to fixed contract size.
Risk Amount (USD or Contracts): This setting is to set how many USD or how many contracts you want to risk per trade. Make sure to check which risk type you have selected before you choose the risk amount.
Take Profit Multiplier: This is simply the total SL size in points multiplied by x.
Example: If you put 2, you get a 2:1 Risk to Reward Ratio. By Default it's set to 2.5 because this gave the best results in backtests.
Stop Loss Padding: This is simply the buffer in points that is added to the SL for safety reasons. If you have it on 0, the SL will be at the exact price of the opposite side of the range. By default it's set to 5 because this is what delivered the best results in backtests.
Stop Loss Placement: This determines where the stop loss gets placed for the order. It has been set to ORB Range by default as this delivered the best results.
Max Trades Per Hour: This allows the user to decide how many trades are taken an hour. 1 is been set to default for best results
Visual Settings: Check boxes to show orb range, FVG's, Entry points, and trade visualization boxes.
Backtest Settings:
For the backtest the commissions were set to 1.29USD per contract and .35USD for micros which is the highest amount Tradovate charges Margin was not accounted for because typically on prop accounts you can use way more contracts than you need for the extremely low max drawdown. Margin would be important on personal accounts but even there typically it's not an issue at all especially because this strategy runs on the 15min timeframe so it won't use a lot of contracts anyways.
Why the source code is hidden:
The source code is hidden because I invested a lot of time and money into developing this strategy and optimizing it with paid 3rd party software.
SMC Strategy with RSI/OB at Market PriceTakes trade using smc with rsi confirmation
Buy Signal Triggers When:
Scenario 1 (Immediate Touch): Price touches/enters bullish OB boundaries AND previous candle closed with RSI ≤ 35
Scenario 2 (Close Inside): Current candle closes inside bullish OB AND current RSI ≤ 35
Sell Signal Triggers When:
Scenario 1 (Immediate Touch): Price touches/enters bearish OB boundaries AND previous candle closed with RSI ≥ 65
Scenario 2 (Close Inside): Current candle closes inside bearish OB AND current RSI ≥ 65
TurtleTrader Intraday Extended by exp3rts🐢 TurtleTrader Intraday Extended by exp3rts
A modern intraday adaptation of the classic Turtle Trading strategy, optimized for short-term breakout trading with built-in risk management, pyramiding, and optional trend filters.
This strategy captures strong directional moves by entering breakouts from price channels, using ATR-based stop losses and controlled position scaling.
🔑 Key Features:
📈 Channel Breakout Entries: Buy/sell on breakout of highest highs or lowest lows
🛑 Dynamic ATR Stop Loss: Automatically calculated from market volatility
🔁 Pyramiding: Adds up to 4 positions as price moves in your favor
🔄 Directional Mode: Choose Long-only or Short-only mode
🧠 Skip After Win Option: Avoid overtrading by skipping the next entry after a profitable trade
📊 Optional EMA Display: Plot up to 3 EMAs for trend filtering or visual confirmation
📉 On-Chart ATR Label: Displays real-time ATR metrics (including ½N size used in classic Turtle rules)
⚙️ Strategy Inputs:
Entry/Exit channel length
ATR multiplier and period
Entry delay (bar offset)
Optional trade filter after profitable trades
Show/hide EMAs and ATR label
🧪 Best For:
Intraday breakout traders (works well on 5m–1h timeframes)
Traders who prefer mechanical rules and structured risk
Anyone testing volatility-based entries and exits
Inspired by the original Turtle Trading system — redesigned for modern markets with more intraday flexibility and visual enhancements.
15min ACTIVE Rangeevery 9:30 am New York Time, Gold prints a high Volume 15 min Candle: "ACTIVE RANGE"
Every time gold prints a candle in which it has a higher candle than the current "ACTIVE RANGE" there would be a new "ACTIVE RANGE"
Breakout and retest the ACTIVE Range
多单ETH/XRP/LTC/IP/分段止盈(优先成本区止损)Experience the backtesting of a 30x leverage If you need a long-term strategy, please send me a message.
多单ETH/XRP/LTC/IP/分段止盈(优先成本区止损)Feel the 30x leverage effect on the entire historical BTC data. Release your hands and take off!
SuperTrended Moving Averages Strategyself use
used in 1 second timeframe
please let me publish it aaa
Diabolos Long What the strategy tries to do
It looks for RSI dips into oversold, then waits for RSI to recover above a chosen level before placing a limit buy slightly below the current price. If the limit doesn’t fill within a few bars, it cancels it. Once in a trade, it sets a fixed take-profit and stop-loss. It can pyramid up to 3 entries.
Step-by-step
1) Inputs you control
RSI Length (rsiLen), Oversold level (rsiOS), and a re-entry threshold (rsiEntryLevel) you want RSI to reach after oversold.
Entry offset % (entryOffset): how far below the current close to place your limit buy.
Cancel after N bars (cancelAfterBars): if still not filled after this many bars, the limit order is canceled.
Risk & compounding knobs: initialRisk (% of equity for first order), compoundRate (% to artificially grow the equity base after each signal), plus fixed TP% and SL%.
2) RSI logic (arming the setup)
It calculates rsi = ta.rsi(close, rsiLen).
If RSI falls below rsiOS, it sets a flag inOversold := true (this “arms” the next potential long).
A long signal (longCondition) happens only when:
inOversold is true (we were oversold),
RSI comes back above rsiOS,
and RSI is at least rsiEntryLevel.
So: dip into OS → recover above OS and to your threshold → signal fires.
3) Placing the entry order
When longCondition is true:
It computes a limit price: close * (1 - entryOffset/100) (i.e., below the current bar’s close).
It sizes the order as positionRisk / close, where:
positionRisk starts as accountEquity * (initialRisk/100).
accountEquity was set once at script start to strategy.equity.
It places a limit long: strategy.order("Long Entry", strategy.long, qty=..., limit=limitPrice).
It then resets inOversold := false (disarms until RSI goes oversold again).
It remembers the bar index (orderBarIndex := bar_index) so it can cancel later if unfilled.
Important nuance about “compounding” here
After signaling, it does:
compoundedEquity := compoundedEquity * (1 + compoundRate/100)
positionRisk := compoundedEquity * (initialRisk/100)
This means your future order sizes grow by a fixed compound rate every time a signal occurs, regardless of whether previous trades won or lost. It’s not tied to actual PnL; it’s an artificial growth curve. Also, accountEquity was captured only once at start, so it doesn’t automatically track live equity changes.
4) Auto-cancel the limit if it doesn’t fill
On each bar, if bar_index - orderBarIndex >= cancelAfterBars, it does strategy.cancel("Long Entry") and clears orderBarIndex.
If the order already filled, cancel does nothing (there’s nothing pending with that id).
Behavioral consequence: Because you set inOversold := false at signal time (not on fill), if a limit order never fills and later gets canceled, the strategy will not fire a new entry until RSI goes below oversold again to re-arm.
5) Managing the open position
If strategy.position_size > 0, it reads the avg entry price, then sets:
takeProfitPrice = avgEntryPrice * (1 + exitGainPercentage/100)
stopLossPrice = avgEntryPrice * (1 - stopLossPercentage/100)
It places a combined exit:
strategy.exit("TP / SL", from_entry="Long Entry", limit=takeProfitPrice, stop=stopLossPrice)
With pyramiding=3, multiple fills can stack into one net long position. Using the same from_entry id ties the TP/SL to that logical entry group (not per-layer). That’s OK in TradingView (it will manage TP/SL for the position), but you don’t get per-layer TP/SL.
6) Visuals & alerts
It plots a green triangle under the bar when the long signal condition occurs.
It exposes an alert you can hook to: “Покупка при достижении уровня”.
A quick example timeline
RSI drops below rsiOS → inOversold = true (armed).
RSI rises back above rsiOS and reaches rsiEntryLevel → signal.
Strategy places a limit buy a bit below current price.
4a) If price dips to fill within cancelAfterBars, you’re long. TP/SL are set as fixed % from avg entry.
4b) If price doesn’t dip enough, after N bars the limit is canceled. The system won’t re-try until RSI becomes oversold again.
Key quirks to be aware of
Risk sizing isn’t PnL-aware. accountEquity is frozen at start, and compoundedEquity grows on every signal, not on wins. So size doesn’t reflect real equity changes unless you rewrite it to use strategy.equity each time and (optionally) size by stop distance.
Disarm on signal, not on fill. If a limit order goes stale and is canceled, the system won’t try again unless RSI re-enters oversold. That’s intentional but can reduce fills.
Single TP/SL id for pyramiding. Works, but you can’t manage each add-on with different exits.
Natural Gas Intraday Strategy [15m] with Partial Profit & TrailBuy when:
1. Close > EMA 100 and EMA 20 > EMA 100
2. MACD (8,21,5) > Signal and histogram rising
3. RSI > 60
4. ATR > threshold (avoid flat market)
Sell when:
1. Close < EMA 100 and EMA 20 < EMA 100
2. MACD (8,21,5) < Signal and histogram falling
3. RSI < 40
4. ATR > threshold
Exit:
• SL = recent swing ± 0.5 ATR
• TP1 = 1 ATR, trail rest with EMA 20
Zero Lag + Momentum Bias StrategyZero Lag + Momentum Bias Strategy (MTF + Strong MBI + R:R + Partial TP + Alerts)
NSE/FT/INTRADAYIt combines technical indicators and momentum signals to capture quick price movements while managing risk effectively. The strategy emphasizes fast execution, strict stop-loss placement, and disciplined profit booking, making it suitable for traders who prefer multiple trades within the same day rather than holding overnight positions.
Macro Momentum – 4-Theme, Vol Target, RebalanceMacro Momentum — 4-Theme, Vol Target, Rebalance
Purpose. A macro-aware strategy that blends four economic “themes”—Business Cycle, Trade/USD, Monetary Policy, and Risk Sentiment—into a single, smoothed Composite signal. It then:
gates entries/exits with hysteresis bands,
enforces optional regime filters (200-day bias), and
sizes the position via volatility targeting with caps for long/short exposure.
It’s designed to run on any chart (index, ETF, futures, single stocks) while reading external macro proxies on a chosen Signal Timeframe.
How it works (high level)
Build four theme signals from robust macro proxies:
Business Cycle: XLI/XLU and Copper/Gold momentum, confirmed by the chart’s price vs a long SMA (default 200D).
Trade / USD: DXY momentum (sign-flipped so a rising USD is bearish for risk assets).
Monetary Policy: 10Y–2Y curve slope momentum and 10Y yield trend (steepening & falling 10Y = risk-on; rising 10Y = risk-off).
Risk Sentiment: VIX momentum (bearish if higher) and HYG/IEF momentum (bullish if credit outperforms duration).
Normalize & de-noise.
Optional Winsorization (MAD or stdev) clamps outliers over a lookback window.
Optional Z-score → tanh mapping compresses to ~ for stable weighting.
Theme lines are SMA-smoothed; the final Composite is LSMA-smoothed (linreg).
Decide direction with hysteresis.
Enter/hold long when Composite ≥ Entry Band; enter/hold short when Composite ≤ −Entry Band.
Exit bands are tighter than entry bands to avoid whipsaws.
Apply regime & direction constraints.
Optional Long-only above 200MA (chart symbol) and/or Short-only below 200MA.
Global Direction control (Long / Short / Both) and Invert switch.
Size via volatility targeting.
Realized close-to-close vol is annualized (choose 9-5 or 24/7 market profile).
Target exposure = TargetVol / RealizedVol, capped by Max Long/Max Short multipliers.
Quantity is computed from equity; futures are rounded to whole contracts.
Rebalance cadence & execution.
Trades are placed on Weekly / Monthly / Quarterly rebalance bars or when the sign of exposure flips.
Optional ATR stop/TP for single-stock style risk management.
Inputs you’ll actually tweak
General
Signal Timeframe: Where macro is sampled (e.g., D/W).
Rebalance Frequency: Weekly / Monthly / Quarterly.
ROC & SMA lengths: Defaults for theme momentum and the 200D regime filter.
Normalization: Z-score (tanh) on/off.
Winsorization
Toggle, lookback, multiplier, MAD vs Stdev.
Risk / Sizing
Target Annualized Vol & Realized Vol Lookback.
Direction (Long/Short/Both) and Invert.
Max long/short exposure caps.
Advanced Thresholds
Theme/Composite smoothing lengths.
Entry/Exit bands (hysteresis).
Regime / Execution
Long-only above 200MA, Short-only below 200MA.
Stops/TP (optional)
ATR length and SL/TP multiples.
Theme Weights
Per-theme scalars so you can push/pull emphasis (e.g., overweight Policy during rate cycles).
Macro Proxies
Symbols for each theme (XLI, XLU, HG1!, GC1!, DXY, US10Y, US02Y, VIX, HYG, IEF). Swap to alternatives as needed (e.g., UUP for DXY).
Signals & logic (under the hood)
Business Cycle = ½ ROC(XLI/XLU) + ½ ROC(Copper/Gold), then confirmed by (price > 200SMA ? +1 : −1).
Trade / USD = −ROC(DXY).
Monetary Policy = 0.6·ROC(10Y–2Y) − 0.4·ROC(10Y).
Risk Sentiment = −0.6·ROC(VIX) + 0.4·ROC(HYG/IEF).
Each theme → (optional Winsor) → (robust z or scaled ROC) → tanh → SMA smoothing.
Composite = weighted average → LSMA smoothing → compare to bands → dir ∈ {−1,0,+1}.
Rebalance & flips. Orders fire on your chosen cadence or when the sign of exposure changes.
Position size. exposure = clamp(TargetVol / realizedVol, maxLong/Short) × dir.
Note: The script also exposes Gross Exposure (% equity) and Signed Exposure (× equity) as diagnostics. These can help you audit how vol-targeting and caps translate into sizing over time.
Visuals & alerts
Composite line + columns (color/intensity reflect direction & strength).
Entry/Exit bands with green/red fills for quick polarity reads.
Hidden plots for each Theme if you want to show them.
Optional rebalance labels (direction, gross & signed exposure, σ).
Background heatmap keyed to Composite.
Alerts
Enter/Inc LONG when Composite crosses up (and on rebalance bars).
Enter/Inc SHORT when Composite crosses down (and on rebalance bars).
Exit to FLAT when Composite returns toward neutral (and on rebalance bars).
Practical tips
Start higher timeframes. Daily signals with Monthly rebalance are a good baseline; weekly signals with quarterly rebalances are even cleaner.
Tune Entry/Exit bands before anything else. Wider bands = fewer trades and less noise.
Weights reflect regime. If policy dominates markets, raise Monetary Policy weight; if credit stress drives moves, raise Risk Sentiment.
Proxies are swappable. Use UUP for USD, or futures-continuous symbols that match your data plan.
Futures vs ETFs. Quantity auto-rounds for futures; ETFs accept fractional shares. Check contract multipliers when interpreting exposure.
Caveats
Macro proxies can repaint at the selected signal timeframe as higher-TF bars form; that’s intentional for macro sampling, but test live.
Vol targeting assumes reasonably stationary realized vol over the lookback; if markets regime-shift, revisit volLook and targetVol.
If you disable normalization/winsorization, themes can become spikier; expect more hysteresis band crossings.
What to change first (quick start)
Set Signal Timeframe = D, Rebalance = Monthly, Z-score on, Winsor on (MAD).
Entry/Exit bands: 0.25 / 0.12 (defaults), then nudge until trade count and turnover feel right.
TargetVol: try 10% for diversified indices; lower for single stocks, higher for vol-sell strategies.
Leave weights = 1.0 until you’ve inspected the four theme lines; then tilt deliberately.
MNQ 4H Swing// ====================================================================
// Strategy: MNQ 4H Swing — Independent Trades + Alerts + Trade Lines
// ====================================================================
// 1. Designed for MNQ futures on a strict 4-hour timeframe.
// 2. Timeframe guard ensures the code only runs on 4H charts.
// 3. User can configure risk per trade in USD and contract size limits.
// 4. Position size is calculated dynamically from entry–stop distance.
// 5. Stop-loss can be set by bar high/low or ATR multiplier.
// 6. Take-profit can be defined in points or as a risk multiple (R).
// 7. Multiple layered entries are supported, hedging is disabled.
// 8. SMA(9) acts as the main trend filter for signals.
// 9. Long entry = price above SMA + breakout after bearish bar.
// 10. Short entry = price below SMA + breakdown after bullish bar.
// 11. Candle size filters control validity of entry signals.
// 12. Trailing stop (Chandelier ATR) is available per trade layer.
// 13. Optionally move stop to breakeven at +1R profit.
// 14. Cooldown prevents immediate re-entry after flat conditions.
// 15. Alerts: both alertcondition() and alert() are included.
// 16. Alerts show entry, stop, TP, quantity, and timeframe details.
// 17. Each trade is tracked in arrays for multi-layer management.
// 18. Fixed horizontal lines (Entry/SL/TP) are drawn for 3 bars.
// 19. Debug markers visualize core long/short signals and bad bars.
// 20. Provides structured risk management, automation, and visuals.
// ====================================================================