OPEN-SOURCE SCRIPT

magic wand STSM

1 586
"Magic Wand STSM" Strategy: Trend-Following with Dynamic Risk Management

Overview:
The "Magic Wand STSM" (Supertrend & SMA Momentum) is an automated trading strategy designed to identify and capitalize on sustained trends in the market. It combines a multi-timeframe Supertrend for trend direction and potential reversal signals, along with a 200-period Simple Moving Average (SMA) for overall market bias. A key feature of this strategy is its dynamic position sizing based on a user-defined risk percentage per trade, and a built-in daily and monthly profit/loss tracking system to manage overall exposure and prevent overtrading.

How it Works (Underlying Concepts):

Multi-Timeframe Trend Confirmation (Supertrend):
The strategy uses two Supertrend indicators: one on the current chart timeframe and another on a higher timeframe (e.g., if your chart is 5-minute, the higher timeframe Supertrend might be 15-minute).
Trend Identification: The Supertrend's direction output is crucial. A negative direction indicates a bearish trend (price below Supertrend), while a positive direction indicates a bullish trend (price above Supertrend).
Confirmation: A core principle is that trades are only considered when the Supertrend on both the current and the higher timeframe align in the same direction. This helps to filter out noise and focus on stronger, more confirmed trends. For example, for a long trade, both Supertrends must be indicating a bearish trend (price below Supertrend line, implying an uptrend context where price is expected to stay above/rebound from Supertrend). Similarly, for short trades, both must be indicating a bullish trend (price above Supertrend line, implying a downtrend context where price is expected to stay below/retest Supertrend).
Trend "Readiness": The strategy specifically looks for situations where the Supertrend has been stable for a few bars (checking barssince the last direction change).

Long-Term Market Bias (200 SMA):
A 200-period Simple Moving Average is plotted on the chart.
Filter: For long trades, the price must be above the 200 SMA, confirming an overall bullish bias. For short trades, the price must be below the 200 SMA, confirming an overall bearish bias. This acts as a macro filter, ensuring trades are taken in alignment with the broader market direction.

"Lowest/Highest Value" Pullback Entries:
The strategy employs custom functions (LowestValueAndBar, HighestValueAndBar) to identify specific price action within the recent trend:
For Long Entries: It looks for a "buy ready" condition where the price has found a recent lowest point within a specific number of bars since the Supertrend turned bearish (indicating an uptrend). This suggests a potential pullback or consolidation before continuation. The entry trigger is a close above the open of this identified lowest bar, and also above the current bar's open.
For Short Entries: It looks for a "sell ready" condition where the price has found a recent highest point within a specific number of bars since the Supertrend turned bullish (indicating a downtrend). This suggests a potential rally or consolidation before continuation downwards. The entry trigger is a close below the open of this identified highest bar, and also below the current bar's open.
Candle Confirmation: The strategy also incorporates a check on the candle type at the "lowest/highest value" bar (e.g., closevalue_b < openvalue_b for buy signals, meaning a bearish candle at the low, suggesting a potential reversal before a buy).

Risk Management and Position Sizing:

Dynamic Lot Sizing: The lotsvalue function calculates the appropriate position size based on your Your Equity input, the Risk to Reward ratio, and your risk percentage for your balance % input. This ensures that the capital risked per trade remains consistent as a percentage of your equity, regardless of the instrument's volatility or price. The stop loss distance is directly used in this calculation.
Fixed Risk Reward: All trades are entered with a predefined Risk to Reward ratio (default 2.0). This means for every unit of risk (stop loss distance), the target profit is rr times that distance.
Daily and Monthly Performance Monitoring:
The strategy tracks todaysWins, todaysLosses, and res (daily net result) in real-time.
A "daily profit target" is implemented (day_profit): If the daily net result is very favorable (e.g., res >= 4 with todaysLosses >= 2 or todaysWins + todaysLosses >= 8), the strategy may temporarily halt trading for the remainder of the session to "lock in" profits and prevent overtrading during volatile periods.
A "monthly stop-out" (monthly_trade) is implemented: If the lres (overall net result from all closed trades) falls below a certain threshold (e.g., -12), the strategy will stop trading for a set period (one week in this case) to protect capital during prolonged drawdowns.

Trade Execution:

Entry Triggers: Trades are entered when all buy/sell conditions (Supertrend alignment, SMA filter, "buy/sell situation" candle confirmation, and risk management checks) are met, and there are no open positions.
Stop Loss and Take Profit:
Stop Loss: The stop loss is dynamically placed at the upTrendValue for long trades and downTrendValue for short trades. These values are derived from the Supertrend indicator, which naturally adjusts to market volatility.
Take Profit: The take profit is calculated based on the entry price, the stop loss, and the Risk to Reward ratio (rr).
Position Locks: lock_long and lock_short variables prevent immediate re-entry into the same direction once a trade is initiated, or after a trend reversal based on Supertrend changes.

Visual Elements:

The 200 SMA is plotted in yellow.
Entry, Stop Loss, and Take Profit lines are plotted in white, red, and green respectively when a trade is active, with shaded areas between them to visually represent risk and reward.
Diamond shapes are plotted at the bottom of the chart (green for potential buy signals, red for potential sell signals) to visually indicate when the buy_sit or sell_sit conditions are met, along with other key filters.
A comprehensive trade statistics table is displayed on the chart, showing daily wins/losses, daily profit, total deals, and overall profit/loss.
A background color indicates the active trading session.

Ideal Usage:

This strategy is best applied to instruments with clear trends and sufficient liquidity. Users should carefully adjust the Your Equity, Risk to Reward, and risk percentage inputs to align with their individual risk tolerance and capital. Experimentation with different ATR Length and Factor values for the Supertrend might be beneficial depending on the asset and timeframe.

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.