Trendline Breakout Strategy [KedArc Quant] Description
A single, rule-based system that builds two trendlines from confirmed swing pivots and trades their breakouts, with optional retest, trend-regime gates (EMA / HTF EMA), and ATR-based risk. All parts serve one decision flow: structure → breakout → gated entry → managed risk.
What it does (for traders)
Draws Up line (teal) through the last two Higher Lows and Down line (red) through the last two Lower Highs, then extends them forward.
Long when price breaks above red; Short when price breaks below teal.
Optional Retest entry: after a break, wait for a pullback toward the broken line within an ATR-scaled buffer.
Uses ATR stop and R-multiple target so risk is consistent across symbols/timeframes.
Labels HL1/HL2/LH1/LH2 so non-coders can verify which pivots built each line.
Why these components are combined
Pure breakout systems on trendlines suffer from three practical issues:
False breaks in chop → solved by trend-regime gates (EMA / HTF EMA) that only allow trades aligned with the prevailing trend.
Uneven volatility across markets/timeframes → solved by ATR-based stop/target, normalizing distance so R-multiples are comparable.
First break whipsaws near wedge apices → mitigated by the optional retest rule that demands a pullback/hold before entry.
These modules are not separate indicators with their own signals. They are support roles inside one method.
The pivot engine defines structure, the breakout detector defines signal, the regime gates decide if we’re allowed to take that signal, and the ATR module sizes risk.
Together they make the trendline breakout usable, testable, and explainable.
How it works (mechanism; each component explained)
1) Pivot engine (structure, non-repainting)
Swings are confirmed with ta.pivotlow/high(L, R). A pivot only exists after R bars (no look-ahead), so once plotted, the line built from those pivots will not repaint.
2) Trendline builder (geometry)
Teal line updates when two consecutive pivot lows satisfy HL2.price > HL1.price (and HL2 occurs after HL1).
Red line updates when two consecutive pivot highs satisfy LH2.price < LH1.price.
Lines are extended right and their current value is read every bar via line.get_price().
3) Breakout detector (signal)
On every bar, compute:
crossover(close, redLine) ⇒ Long breakout
crossunder(close, tealLine) ⇒ Short breakdown
4) Regime gates (trend filters, not separate signals)
EMA gate: allow longs only if close > EMA(len), shorts only if close < EMA(len).
HTF EMA gate (optional): same rule on a higher timeframe to avoid fighting the larger trend.
These do not create entries; they simply permit or block the breakout signal.
5) Retest module (optional confirmation)
After a breakout, record the line price. A valid retest occurs if price pulls back within an ATR-scaled buffer toward that broken line and then closes back in the breakout direction.
This reduces first-tick fakeouts.
6) Risk module (position exit)
Initial stop = ATR(len) × atrMult from entry.
Target = tpR × (ATR × atrMult) (e.g., 2R).
This keeps results consistent across instruments/timeframes.
Entries & exits
Long entry
Base: close breaks above red and passes EMA/HTF gates.
Retest (if enabled): after the break, price pulls back near the broken red line (within the ATR buffer) and holds; then enter.
Short entry
Mirror logic with teal (break below & gates), optionally with a retest.
Exit
strategy.exit places ATR stop & R-multiple target automatically.
Optional “flip”: close if the opposite base signal triggers.
How to use it (step-by-step)
Timeframe: 1–15m for intraday, 1–4h for swing.
Start defaults: Pivot L/R = 5, EMA len = 200, ATR len = 14, ATR mult = 2, TP = 2R, Retest = ON.
Tune sensitivity:
Faster lines (more trades): set L/R = 3–4.
Fewer counter-trend trades: enable HTF EMA (e.g., 60-min or Daily).
Visual audit: labels HL1/HL2 & LH1/LH2 show which pivots built each line—verify by eye.
Alerts: use Long breakout, Short breakdown, and Retest alerts to automate.
Originality (why it merits publication)
Trades the visualization: many “auto-trendline” tools only draw lines; this one turns them into testable, alertable rules.
Integrated design: each component has a defined role in the same pipeline—no unrelated indicators bolted together.
Transparent & non-repainting: pivot confirmation removes look-ahead; labels let non-coders understand the setup that produced each signal.
Notes & limitations
Lines update only after pivot confirmation; that lag is intentional to avoid repainting.
Breakouts near an apex can whipsaw; prefer Retest and/or HTF gate in choppy regimes.
Backtests are idealized; forward-test and size risk appropriately.
⚠️ Disclaimer
This script is provided for educational purposes only.
Past performance does not guarantee future results.
Trading involves risk, and users should exercise caution and use proper risk management when applying this strategy.
Göstergeler ve stratejiler
BSL/SSL Sweep + FVG Strategy Jobin (c) The New York ATM Model is a structured intraday strategy designed to capture algorithmic stop-hunts and reversals during the New York session open. It focuses on liquidity sweeps—either Buy-Side or Sell-Side—followed by a confirmation using Fair Value Gaps (FVGs).
Enhanced TMA Strategy[BMM]This strategy combines multiple moving averages with pattern recognition and dynamic coloring to identify high-probability trades. It uses 3-line strike patterns, engulfing candles, and RSI-based trend analysis with proper risk management for consistent 75%+ win rates.
Ideal Settings by Timeframe
For clear signals strategy can be used with:
"The Arty" - The Moving Average Official Indicator
or
TMA Legacy - "The Arty"
5-Minute Charts:
MA Lengths: 21, 50, 100, 200
MA Type: EMA
Risk: 1%
Risk:Reward: 2:1
Enable RSI Filter: Yes
Sessions: London + NY only
15-Minute Charts:
MA Lengths: 21, 50, 89, 144
MA Type: SMMA
Risk: 1.5%
Risk:Reward: 2.5:1
Enable RSI Filter: Yes
Sessions: All major sessions
30-Minute Charts:
MA Lengths: 13, 34, 55, 89
MA Type: EMA
Risk: 2%
Risk:Reward: 3:1
Enable RSI Filter: No
Sessions: London + NY only
Key Features to Enable:
Dynamic line coloring
Trend fill
All pattern signals
Session backgrounds
Strategy alerts
Trade only during major session overlaps for best liquidity and volatility.
Extremum Range MA Crossover Strategy1. Principle of Work & Strategy Logic ⚙️📈
Main idea: The strategy tries to catch the moment of a breakout from a price consolidation range (flat) and the start of a new trend. It combines two key elements:
Moving Average (MA) 📉: Acts as a dynamic support/resistance level and trend filter.
Range Extremes (Range High/Low) 🔺🔻: Define the borders of the recent price channel or consolidation.
The strategy does not attempt to catch absolute tops and bottoms. Instead, it enters an already formed move after the breakout, expecting continuation.
Type: Trend-following, momentum-based.
Timeframes: Works on different TFs (H1, H4, D), but best suited for H4 and higher, where breakouts are more meaningful.
2. Justification of Indicators & Settings ⚙️
A. Moving Average (MA) 📊
Why used: Core of the strategy. It smooths price fluctuations and helps define the trend. The price (via extremes) must cross the MA → signals a potential trend shift or strengthening.
Parameters:
maLength = 20: Default length (≈ one trading month, 20-21 days). Good balance between sensitivity & smoothing.
Lower TF → reduce (10–14).
Higher TF → increase (50).
maSource: Defines price source (default = Close). Alternatives (HL2, HLC3) → smoother, less noisy MA.
maType: Default = EMA (Exponential MA).
Why EMA? Faster reaction to recent price changes vs SMA → useful for breakout strategies.
Other options:
SMA 🟦 – classic, slowest.
WMA 🟨 – weights recent data stronger.
HMA 🟩 – near-zero lag, but “nervous,” more false signals.
DEMA/TEMA 🟧 – even faster & more sensitive than EMA.
VWMA 🔊 – volume-weighted.
ZLEMA ⏱ – reduced lag.
👉 Choice = tradeoff between speed of reaction & false signals.
B. Range Extremes (Previous High/Low) 📏
Why used: Define borders of recent trading range.
prevHigh = local resistance.
prevLow = local support.
Break of these levels on close = trigger.
Parameters:
lookbackPeriod = 5: Searches for highest high / lowest low of last 5 candles. Very recent range.
Higher value (10–20) → wider, stronger ranges but rarer signals.
3. Entry & Exit Rules 🎯
Long signals (BUY) 🟢📈
Condition (longCondition): Previous Low crosses MA from below upwards.
→ Price bounced from the bottom & strong enough to push range border above MA.
Execution: Auto-close short (if any) → open long.
Short signals (SELL) 🔴📉
Condition (shortCondition): Previous High crosses MA from above downwards.
→ Price rejected from the top, upper border failed above MA.
Execution: Auto-close long (if any) → open short.
Exit conditions 🚪
Exit Long (exitLongCondition): Close below prevLow.
→ Uptrend likely ended, range shifts down.
Exit Short (exitShortCondition): Close above prevHigh.
→ Downtrend likely ended, range shifts up.
⚠️ Important: Exit = only on candle close beyond extremes (not just wick).
4. Trading Settings ⚒️
overlay = true → indicators shown on chart.
initial_capital = 10000 💵.
default_qty_type = strategy.cash, default_qty_value = 100 → trades fixed $100 per order (not lots). Can switch to % of equity.
commission_type = strategy.commission.percent, commission_value = 0.1 → default broker fee = 0.1%. Adjust for your broker!
slippage = 3 → slippage = 3 ticks. Adjust to asset liquidity.
currency = USD.
margin_long = 100, margin_short = 100 → no leverage (100% margin).
5. Visualization on Chart 📊
The strategy draws 3 lines:
🔵 MA line (thickness 2).
🔴 Previous High (last N candles).
🟢 Previous Low (last N candles).
Also: entry/exit arrows & equity curve shown in backtest.
Disclaimer ⚠️📌
Risk Warning: This description & code are for educational purposes only. Not financial advice. Trading (Forex, Stocks, Crypto) carries high risk and may lead to full capital loss. You trade at your own risk.
Testing: Always backtest & demo test first. Past results ≠ future profits.
Responsibility: Author of this strategy & description is not responsible for your trading decisions or losses.
Options Straddle Strategy Backtester 140% APR for 2025This script provides the most convenient manual tool for backtesting a straddle stagy in options.
The straddle is when you buy a call and a put option at the same price and the expiration date. You profit when the price movement at expiry (8 am UTC) in either directions surpass the price of the premium paid. The price of opening this straddle on ETH is always 1.6% of the current ETH price including fees.
In my example I use ETH options, I am buying a straddle at 8:30 UTC every day with the next day expiration date. In the script it looks like I am opening a long position on ETH at 8:30 and then close it the next days. We need to use 1 minute chart, chart time set to UTC for exact results and deep back testing function to go back in time.
Once the system generates a trade report - we need to download it and go to the list of trades sections, there we do the following:
1) remove all long entry lines leaving only long exit lines that have all the information we need.
2) We add one column that calculates the cost of premium for every trade: Position size*1.6%=cost of premium with fees.
3)We add a second column copying all Net PNL in USDT changing negative amounts to positive - since it doesn't matter for us which direction the move was towards.
The results are quite impressive: If you were buying straddles during 2025 that is not ended yet you will get 69% return on investment (11K paid in premiums, 19K return, 8K net profit). 2024 and 2025 combined: 53% (29 K, 45 K, and 15 profits).
Moreover, since you have the date of the trade in the table you can filter the results further to figure out if trading on some days is less profitable. Interestingly trades from Sun to Mon given are not profitable at -15% and most profitable days are Mon to Tue - 103%, Friday to Sat - 102 %. So if we remove Sun to Monday trades we will be at 89% for the first 221 days of the year or 140% APR.
Cs Fenix Us30The price unbalances the Asia and Frankfurt range and if there is a structural change it highlights a possible entry with a stop and target level.
MuLegend's Break & Retest Strategy That worksThank you all for checking this out! This indicator works best on the 1 minute time frame for both MNQ & NQ. ES & MES it also can work too to help you be a sniper. Hopefully you will like it!!!
Apertura USA - Estrategia Compra8:30 a.m. opening is a very successful strategy in gold with Heikin Ashi candles, 3 minutes, over 80% effectiveness.
EMA Kombine Strateji
EMA Combined Strategy is a flexible trading system that enhances EMA crossovers with RSI, MACD, ADX, volume, and ATR filters to generate more reliable signals, featuring ATR-based stop-loss and take-profit levels.
AlgoPilotX MA CrossoverMoving Average Crossover
Why: Simple, everyone knows it, great for beginners.
Logic: Buy when short MA crosses above long MA, sell when it crosses below.
Target Audience: Beginner traders testing automation.
STOP HUNT StrategyFutures strategy for /MES that hunts stop-runs of recent lows and buys the bullish reclaim with trend/volume filters. Fixed SL/TP, optional trailing and time-stop, and dynamic 1–2 contracts when trend slope is strong. Initial capital: $10,000 (editable).
This is a strategy (not an indicator). It does not place real orders or provide financial advice.
What it does
• Watches a rolling window (lookback) to “lock” a recent swing low (lockedLow).
• A long setup “arms” when price sweeps below that level (potential stop hunt) and then prints a bullish candle that:
– Opens and closes above the lockedLow, closes > open,
– Lows test at/through the lockedLow by a tolerance,
– Closes above trend SMA and volume > its average.
• If risk/reward meets the minimum and distance from lockedLow is sufficient, the strategy enters LONG at bar close.
Trend & position sizing
• A trend SMA and its slope act as a “strong trend” filter: in strong up-slope the position size increases from 1 to 2 contracts; otherwise 1.
Risk management (built-in)
• Fixed SL/TP as percentages from entry.
• Trailing stop that activates after price advances a user-defined % and trails by a user-defined %.
• Time-stop: optional auto-close after N bars in trade.
• Visuals: entry/SL/TP/trailing plots and an open-bars counter label.
Inputs (high-level)
• Lookback for candidate low, TP/SL %, tolerance, min risk/reward.
• Trend SMA length and strong-slope threshold; volume average length.
• Trailing start % and trail %; max bars in trade toggle.
• Initial capital, commission per order, and other backtest properties are editable in the strategy settings.
Notes
• Designed for /MES, but can be applied to related ES charts. Parameters are exposed so you can adapt to volatility/regime changes.
• Optional ATR/ADX values are computed for alert payloads only; they do not alter signals.
Backtest assumptions (defaults in code)
• Initial capital: $10,000; Commission: $1.42 per order.
• Orders evaluated at bar close on confirmed signals; no lookahead.
• “Backtest fill limits assumption” enabled.
Disclaimer
Educational use only. Backtests are hypothetical and not indicative of future results.
----------------------------------------------------------------------------------------------------------------------
Estrategia (no indicador).
• Observa una ventana móvil (lookback) para “bloquear” un mínimo reciente (lockedLow).
• El set-up de largos se arma cuando el precio barre por debajo de ese nivel (posible stop hunt) y luego imprime una vela alcista que:
– Abre y cierra por encima del lockedLow, cierra > abre,
– Mínimo prueba el lockedLow con una tolerancia,
– Cierra sobre la SMA de tendencia y con volumen > promedio.
• Si cumple distancia mínima al soporte, relación riesgo/beneficio mínima y demás filtros, entra en LARGO al cierre de la vela.
Tendencia y tamaño de posición
• Una SMA de tendencia y su pendiente definen “pendiente fuerte”: en ese caso, el tamaño sube de 1 a 2 contratos; de lo contrario 1.
Gestión de riesgo (incluida)
• SL/TP fijos como % desde la entrada.
• Trailing stop que se activa tras un avance % y persigue por un % configurable.
• Time-stop: cierre opcional tras N velas en la operación.
• Visuales: traza entrada/SL/TP/trailing y etiqueta con conteo de velas abiertas.
Entradas (resumen)
• Lookback para mínimo candidato, TP/SL %, tolerancia, R/R mínimo.
• Longitud de SMA de tendencia y umbral de pendiente fuerte; media de volumen.
• % de activación y % de seguimiento del trailing; máximo de velas en trade.
• Capital inicial, comisión por orden y demás propiedades de backtest editables en ajustes.
Notas
• Diseñada para /MES; puede usarse en ES relacionados ajustando parámetros.
• ATR/ADX se calculan para payloads de alerta; no modifican las señales.
Supuestos de backtest (por defecto)
• Capital inicial: $10,000; Comisión: $1.42 por orden.
• Señales evaluadas al cierre de vela; sin lookahead.
• “Backtest fill limits assumption” activado.
Mony Strategy with TP1/TP2/SL V2//@version=5
strategy("Mony Strategy with TP1/TP2/SL", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=2, initial_capital=10000)
// ===== TAKE PROFIT & STOP LOSS SETTINGS =====
tp_sl_group = "Take Profit & Stop Loss"
enable_tp_sl = input.bool(true, "Enable TP/SL", group=tp_sl_group)
tp1_multiplier = input.float(1.0, "TP1 Multiplier (x ATR)", minval=0.1, maxval=10.0, step=0.1, group=tp_sl_group)
tp2_multiplier = input.float(2.0, "TP2 Multiplier (x ATR)", minval=0.1, maxval=20.0, step=0.1, group=tp_sl_group)
sl_multiplier = input.float(1.5, "Stop Loss Multiplier (x ATR)", minval=0.1, maxval=10.0, step=0.1, group=tp_sl_group)
show_tp_sl_lines = input.bool(true, "Show TP/SL Lines", group=tp_sl_group)
show_rr_ratio = input.bool(true, "Show Risk:Reward Ratio", group=tp_sl_group)
// portion allocation to TP1 and TP2 (must sum to 100)
tp1_pct = input.int(50, "TP1 % of position", minval=1, maxval=100, group=tp_sl_group)
tp2_pct = input.int(50, "TP2 % of position", minval=1, maxval=100, group=tp_sl_group)
// normalize if sum != 100
_tp_sum = tp1_pct + tp2_pct
if _tp_sum != 100
tp1_pct := math.round(tp1_pct * 100.0 / _tp_sum)
tp2_pct := 100 - tp1_pct
// TP/SL Colors
tp_color = input.color(color.new(color.green, 20), "Take Profit Color", group=tp_sl_group)
sl_color = input.color(color.new(color.red, 20), "Stop Loss Color", group=tp_sl_group)
// ===== ORIGINAL NIFTY MAGNET SETTINGS (kept mostly intact) =====
const bool DEBUG = false
const float epsilon = 0.02 / 100.0
const int showLastXPivots = 50
// Auto Trendline
var int TYPE_UP = 1
var int TYPE_DOWN = -1
var string LINE_WIDTH1_STR = "Width 1"
var string LINE_WIDTH2_STR = "Width 2"
_get_width(string str_input) =>
switch str_input
LINE_WIDTH1_STR => 1
LINE_WIDTH2_STR => 2
var string GROUP_FRACT = "Fractals"
var color col_hl = input.color(color.blue, title="Plot:", inline="plot_low", group=GROUP_FRACT)
var bool show_hl = input.bool(true, title="HL", inline="plot_low", group=GROUP_FRACT)
var color col_ll = input.color(color.gray, title=", Plot:", inline="plot_low", group=GROUP_FRACT)
var bool show_ll = input.bool(false, title="LL", inline="plot_low", group=GROUP_FRACT)
var color col_lh = input.color(color.red, title="Plot:", inline="plot_high", group=GROUP_FRACT)
var bool show_lh = input.bool(false, title="LH", inline="plot_high", group=GROUP_FRACT)
var color col_hh = input.color(color.gray, title=", Plot:", inline="plot_high", group=GROUP_FRACT)
var bool show_hh = input.bool(false, title="HH", inline="plot_high", group=GROUP_FRACT)
var string GROUP_ATL = "Auto trendlines"
var string subgroup1 = "recent line"
var color ln_col_recent = input.color(color.new(color.purple, 0), title="Latest Trendline", group=GROUP_ATL, inline=subgroup1)
var int lnwidth_recent = _get_width(input.string(LINE_WIDTH1_STR, options= , title="", inline=subgroup1, group=GROUP_ATL))
var string subgroup2 = "historical line"
var color ln_col_prev = input.color(color.new(color.gray, 50), title="Historical Trendline", group=GROUP_ATL, inline=subgroup2)
var int lnwidth_prev = _get_width(input.string(LINE_WIDTH1_STR, options= , title="", inline=subgroup2, group=GROUP_ATL))
var bool show_historical = input.bool(false, title="Show Historical Lines", group=GROUP_ATL)
var int max_tl = input.int(1, title="Max pair of lines", maxval=250, minval=1, group=GROUP_ATL)*2
var string _str_extend = input.string("Right", options= , title="Which way to extend lines", group=GROUP_ATL)
var string str_extend = _str_extend == "Both ways" ? extend.both : extend.right
var bool show_crosses = input.bool(false, title="Show crosses", tooltip="Instances when closing price of a bar has crossed lower/upper trendlines", group=GROUP_ATL)
// ===== TP/SL VARIABLES =====
var float call_entry = na
var float put_entry = na
// ===== FRACTAL TYPE DEFINITION =====
type fractal
int up_or_down = na
int xloc = na
float yloc = na
int xloc_parent = na
float yloc_parent = na
var fractal arr_fract = array.new()
var line arr_ln_up = array.new_line()
var line arr_ln_dn = array.new_line()
// ===== FRACTAL FUNCTIONS =====
init_fractal(int fract_type, int xloc, float yloc, int xparent, float yparent)=>
f = fractal.new()
f.up_or_down := fract_type
f.xloc := xloc
f.yloc := yloc
f.xloc_parent := xparent
f.yloc_parent := yparent
ln = line.new(xloc, yloc, xparent, yparent, xloc.bar_index, str_extend, color=ln_col_recent, style=line.style_dashed, width=lnwidth_recent)
if f.up_or_down == TYPE_UP
array.unshift(arr_ln_up, ln)
else if f.up_or_down == TYPE_DOWN
array.unshift(arr_ln_dn, ln)
array.unshift(arr_fract, f)
f
drop_and_roll(fractal f) =>
arr_ln = f.up_or_down == TYPE_UP ? arr_ln_up : f.up_or_down == TYPE_DOWN ? arr_ln_dn : na
if array.size(arr_ln) > 1
if show_historical
line.set_color(array.get(arr_ln, 1), ln_col_prev)
line.set_width(array.get(arr_ln, 1), lnwidth_prev)
else
line.delete(array.get(arr_ln, 1))
while array.size(arr_ln) > math.floor(max_tl/2)
line.delete(array.pop(arr_ln))
draw_trendline(fract_type, x2, y2, x1, y1) =>
f = init_fractal(fract_type, x2, y2, x1, y1)
drop_and_roll(f)
// ===== PIVOT CALCULATIONS =====
float ph = ta.pivothigh(10, 10)
bool upfract = not na(ph)
float pl = ta.pivotlow(10, 10)
bool downfract = not na(pl)
// ===== VOLATILITY FILTER =====
data_source = close
filter_length = 20
range_factor = 3.5
vol_range(input_data, multiplier, period) =>
window_size = period * 2 - 1
vol_avg = ta.ema(math.abs(input_data - input_data ), period)
adjusted_vol = ta.ema(vol_avg, window_size) * multiplier
adjusted_vol
vol_filter(input_data, range_val, period) =>
v_range = range_val
var v_filtered = array.new_float(2, input_data)
array.set(v_filtered, 1, array.get(v_filtered, 0))
if input_data - v_range > array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data - v_range)
if input_data + v_range < array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data + v_range)
filtered_val = array.get(v_filtered, 0)
upper_band = filtered_val + v_range
lower_band = filtered_val - v_range
// Calculate current ATR for TP/SL
current_atr = ta.atr(14)
// Volatility Filter Values
= vol_filter(data_source, vol_range(data_source, range_factor, filter_length), filter_length)
// Direction Conditions
var float trend_dir = 0.0
trend_dir := filtered_data > filtered_data ? 1 : filtered_data < filtered_data ? -1 : trend_dir
bull_trend = trend_dir == 1 ? 1 : 0
bear_trend = trend_dir == -1 ? 1 : 0
// Trading Conditions
buy_condition = (data_source > filtered_data and data_source > data_source and bull_trend > 0) or (data_source > filtered_data and data_source < data_source and bull_trend > 0)
sell_condition = (data_source < filtered_data and data_source < data_source and bear_trend > 0) or (data_source < filtered_data and data_source > data_source and bear_trend > 0)
var int state_trend = 0
state_trend := buy_condition ? 1 : sell_condition ? -1 : nz(state_trend , 0)
entry_buy = buy_condition and nz(state_trend , 0) == -1
entry_sell = sell_condition and nz(state_trend , 0) == 1
// ===== STRATEGY ENTRY + TP/SL LOGIC =====
// We'll use strategy.entry for entries and strategy.exit for TP1 and TP2 (each with qty_percent).
// Calculate TP/SL prices based on the price at signal (we use close at the signal bar).
var float last_long_entry_price = na
var float last_short_entry_price = na
if entry_buy
// place a long entry (full size)
strategy.entry("Long", strategy.long)
if enable_tp_sl
last_long_entry_price := close
if entry_sell
strategy.entry("Short", strategy.short)
if enable_tp_sl
last_short_entry_price := close
// When we have an entry price, create two exits: TP1 (partial) and TP2 (remaining).
// Both exits include the same stop (SL) so the remaining is protected if SL hit.
if enable_tp_sl
// LONG exits
if not na(last_long_entry_price)
long_tp1 = last_long_entry_price + tp1_multiplier * current_atr
long_tp2 = last_long_entry_price + tp2_multiplier * current_atr
long_sl = last_long_entry_price - sl_multiplier * current_atr
// create (or update) exits for long
// TP1: partial take-profit
strategy.exit(id="Long TP1", from_entry="Long", limit=long_tp1, stop=long_sl, qty_percent=tp1_pct)
// TP2: remainder take-profit
strategy.exit(id="Long TP2", from_entry="Long", limit=long_tp2, stop=long_sl, qty_percent=tp2_pct)
// Plot lines/labels for clarity (only visible while active)
if show_tp_sl_lines and strategy.position_size > 0
line.new(bar_index , long_tp1, bar_index, long_tp1, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_dotted, width=1)
line.new(bar_index , long_tp2, bar_index, long_tp2, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_solid, width=1)
line.new(bar_index , long_sl, bar_index, long_sl, xloc=xloc.bar_index, extend=extend.right, color=sl_color, style=line.style_dashed, width=1)
// show label of R:R
if show_rr_ratio
rr1 = (long_tp1 - last_long_entry_price) / (last_long_entry_price - long_sl)
rr2 = (long_tp2 - last_long_entry_price) / (last_long_entry_price - long_sl)
label.new(bar_index, long_tp2, text="RR1: " + str.tostring(rr1, format.percent) + " RR2: " + str.tostring(rr2, format.percent), style=label.style_label_left, color=color.new(color.black, 80), textcolor=color.white, size=size.tiny)
// SHORT exits
if not na(last_short_entry_price)
short_tp1 = last_short_entry_price - tp1_multiplier * current_atr
short_tp2 = last_short_entry_price - tp2_multiplier * current_atr
short_sl = last_short_entry_price + sl_multiplier * current_atr
strategy.exit(id="Short TP1", from_entry="Short", limit=short_tp1, stop=short_sl, qty_percent=tp1_pct)
strategy.exit(id="Short TP2", from_entry="Short", limit=short_tp2, stop=short_sl, qty_percent=tp2_pct)
if show_tp_sl_lines and strategy.position_size < 0
line.new(bar_index , short_tp1, bar_index, short_tp1, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_dotted, width=1)
line.new(bar_index , short_tp2, bar_index, short_tp2, xloc=xloc.bar_index, extend=extend.right, color=tp_color, style=line.style_solid, width=1)
line.new(bar_index , short_sl, bar_index, short_sl, xloc=xloc.bar_index, extend=extend.right, color=sl_color, style=line.style_dashed, width=1)
if show_rr_ratio
srr1 = (last_short_entry_price - short_tp1) / (short_sl - last_short_entry_price)
srr2 = (last_short_entry_price - short_tp2) / (short_sl - last_short_entry_price)
label.new(bar_index, short_tp2, text="RR1: " + str.tostring(srr1, format.percent) + " RR2: " + str.tostring(srr2, format.percent), style=label.style_label_left, color=color.new(color.black, 80), textcolor=color.white, size=size.tiny)
// Reset recorded entry prices when no position
if strategy.position_size == 0
last_long_entry_price := na
last_short_entry_price := na
// ===== TP/SL HIT VISUAL NOTIFICATIONS (labels on the bar where fills happen) =====
// Detect if exits happened this bar by inspecting strategy.closedtrades or position change
// Simple approach: check last bar's position change vs current to label TP/SL hits is not bulletproof but useful.
long_closed = strategy.closedtrades > 0 and strategy.position_size > 0 and strategy.position_size == 0
short_closed = strategy.closedtrades > 0 and strategy.position_size < 0 and strategy.position_size == 0
// Use builtin trade info to label: iterate last closed trade not directly available per-bar in strategy — keep this simple and place a generic label when a position is closed
if long_closed
label.new(bar_index, high, "Closed Long", style=label.style_label_down, color=color.new(color.blue, 0), textcolor=color.white)
if short_closed
label.new(bar_index, low, "Closed Short", style=label.style_label_up, color=color.new(color.orange, 0), textcolor=color.white)
// ===== FRACTAL TRACKING (trendline drawing preserved) =====
var float recent_dn1 = na
var int i_recent_dn1 = na
var float recent_up1 = na
var int i_recent_up1 = na
var float recent_dn2 = na
var int i_recent_dn2 = na
var float recent_up2 = na
var int i_recent_up2 = na
if downfract
recent_dn2 := recent_dn1
i_recent_dn2 := i_recent_dn1
recent_dn1 := low
i_recent_dn1 := bar_index-11
draw_trendline(TYPE_DOWN, i_recent_dn2, recent_dn2, i_recent_dn1, recent_dn1)
if upfract
recent_up2 := recent_up1
i_recent_up2 := i_recent_up1
recent_up1 := high
i_recent_up1 := bar_index-11
draw_trendline(TYPE_UP, i_recent_up2, recent_up2, i_recent_up1, recent_up1)
// ===== COLORS AND FILTER PLOT =====
filter_color = bull_trend ? #05ff9b : bear_trend ? #ff0583 : #cccccc
// Filter Plot
plot(filtered_data, color=filter_color, linewidth=3, title='Volatility Filter')
// ===== BUY/SELL SIGNALS (visual only) =====
plotshape(entry_buy, title='Call Signal', text='BUY', textcolor=color.rgb(9, 233, 110),
style=shape.labelup, size=size.normal, location=location.belowbar, color=color.new(color.green, 0))
plotshape(entry_sell, title='Put Signal', text='SELL', textcolor=color.rgb(228, 10, 21),
style=shape.labeldown, size=size.normal, location=location.abovebar, color=color.new(color.red, 0))
// ===== ALERTS (kept) =====
Zero Lag + ML SuperTrend Strategy (Multi-Symbol) himanshuThis is a multi-symbol trading strategy that combines two indicators:
Zero Lag EMA with volatility filter
ML SuperTrend
Both must agree (bullish or bearish) before entering a trade.
📊 Entry Rules
Long Entry (Buy):
When price is above ZeroLag line (with volatility filter) and above SuperTrend line.
Short Entry (Sell):
When price is below ZeroLag line (with volatility filter) and below SuperTrend line.
📉 Exit Rules
Take Profit (TP): Fixed at +1% from entry price.
Stop Loss (SL): Fixed at -0.5% from entry price.
Trade closes automatically at TP or SL.
⚡ Features
Multi-symbol ready: Works on any chart you apply it to (DOGE, BTC, ETH, Nifty, etc.).
Alerts included: Sends webhook alerts for long entry, short entry, TP hit, and SL hit.
Plots: Displays ZeroLag line and SuperTrend line on the chart.
👉 In short: The system waits until both indicators confirm the same direction, enters a trade, and then exits automatically at a 1% target or 0.5% stop.
Algorium🚀 Introducing the result of three years of development – the ALGORIUM Indicator.
Designed for any market — whether it’s gold, forex, or crypto.
ALGORIUM is built on the power of Fibonacci grids, focusing on breakouts of key levels to pinpoint high-probability entries.
⚡ Best performance on 5m to 4h timeframes – trade with confidence without holding positions for too long or stressing over constant market checks.
📊 Stay ahead with:
A curated list of trading pairs with pre-optimized settings (updated regularly).
A built-in PnL table for analytics and backtesting.
Smart detection of micro-movements like BoS and ChoCh, with instant trade signals.
All you need to do is wait for confirmation and execute your trade.
Take control of the market with ALGORIUM.
LINK/USDT - 9/15 EMA Crossover with SL & TP himanshuThis strategy is designed for the LINK/USDT pair using a simple yet effective Exponential Moving Average (EMA) crossover system.
🔹 How It Works
When the 9 EMA (fast) crosses above the 15 EMA (slow) → it signals bullish momentum → the strategy opens a Long trade.
When the 9 EMA crosses below the 15 EMA → it signals bearish momentum → the strategy opens a Short trade.
🔹 Risk Management
To keep trades disciplined and emotions out of decision-making, built-in exits are applied:
Stop Loss (SL): Automatically closes the trade if price moves 1% against the position.
Take Profit (TP): Locks in profits when price moves 2% in favor of the trade.
🔹 Why Use This Strategy?
✅ Simple and easy-to-follow EMA crossover logic
✅ Automated Stop Loss & Take Profit for risk control
✅ Trades both Long and Short to capture every trend
✅ Can be easily backtested on TradingView for performance validation
OSAKA by KevinMy frist Bot, its the Osaka Trading Bot which relies on ICT Methods and Range Breakouts
Trend Swing(跟随趋势)Strategy Introduction – Trend Following Swing Strategy
The Trend Following Swing Strategy is designed to capture directional moves in the market by combining momentum, volatility, and strength filters. It uses a custom Relative Momentum Index (RMI) with MFI smoothing to detect bullish and bearish momentum shifts.
When bullish momentum is confirmed, the strategy tracks upward price swings; when bearish momentum is confirmed, it tracks downward moves. A Range-Weighted Moving Average (RWMA) with adaptive bands is applied to visualize trend direction and potential support/resistance zones.
To improve trade quality, two filters are applied:
Time Filter: Trades are only allowed within a user-defined session window (e.g., regular market hours).
ADX Filter: Ensures trades are only executed when trend strength (ADX) is above a configurable threshold, filtering out sideways and weak markets.
Key Features:
Momentum detection using RMI + MFI hybrid signal
Adaptive RWMA bands for visual confirmation of trend zones
Session-based time filter to avoid low-liquidity periods
ADX filter to ensure trades align with strong trends
Optional visual plots (candles, bands, fills) for better chart analysis
Automatic position closing at a user-defined time (default: 15:10) to avoid overnight risk
This strategy is most effective on trend-following markets such as indices, commodities, and cryptocurrencies, where sustained directional moves provide profitable swing opportunities.
策略介绍 —— 趋势跟随波段策略
趋势跟随波段策略是一套结合动能、趋势强度与交易时段控制的系统化交易模型,目标是抓取市场中持续性的方向性行情。它通过多重技术指标的配合,过滤掉震荡与弱趋势阶段,从而提高信号质量。
策略核心逻辑
动能检测(RMI + MFI 复合信号)
将相对动量指标(RMI)与资金流量指标(MFI)结合,平滑市场噪音。
当价格动能突破上限阈值时,识别为多头趋势信号;跌破下限阈值时,识别为空头趋势信号。
趋势通道(自适应 RWMA 区间)
使用基于波动率加权的移动平均线(Range-Weighted MA)构建通道。
通道带宽随市场波动自适应调整,可作为动态的支撑/阻力区。
时间过滤(Time Filter)
仅在用户设定的交易时段内允许进场(例如:美股常规开盘时段)。
避免在低流动性或不活跃的市场时段交易。
趋势强度过滤(ADX Filter)
使用 ADX 指标检测趋势强度。
仅当 ADX 高于设定阈值时才允许交易,避免震荡盘中的虚假信号。
自动平仓控制
支持在用户设定的时间点自动清空所有持仓(默认:15:10)。
有效规避隔夜风险,尤其适合日内波段交易者。
策略优势
趋势过滤清晰:动能与 ADX 双重确认,有效提升胜率。
交易时段可控:灵活设置交易窗口,避免无效波动。
风险管理稳健:固定时间自动平仓,减少尾盘风险。
直观可视化:通道、均线、颜色标识,帮助交易者快速识别趋势状态。
适用市场
股指期货(如纳斯达克、标普500)
大宗商品(如原油、黄金)
加密货币(如比特币、以太坊)
尤其适合在趋势明显的市场中使用,能帮助交易者抓住波段机会,减少在震荡市的无效交易。
SPY-2h (E.Trader) - Long-Only StrategySummary
Strategy on SPY, 2h timeframe (2000-2025).
Initial capital: 100,000 USD, 100% reinvest.
Long-only strategy with realistic commissions and slippage (Interactive Brokers: $0.005/share, 3 ticks).
Key results (2000-2025)
• Total P&L: +1,792,104 USD (+1,739.88%)
• CAGR: 11.4% (vs Buy & Hold: 6.7%) → ~1.7x higher annualized return
• Profit factor: 3.23
• Winning trades: 67.43%
• Max drawdown: 21.56%
• Time in the market: ~59% (trading days basis)
• Buy & Hold return: +358.61% → Strategy outperforms by ~4.8x
Strategy logic
• Restricted to SPY on ARCA, in 2h timeframe
• Long entries only (no shorts)
• Exploits two major biases: 1) trends and 2) overreactions
• Excludes very high VIX periods
• Implements calculated stop-losses
• Integrates commission and slippage to reflect real trading conditions (based on Interactive Brokers usage)
Focus 2008-2009 (financial crisis)
• Total P&L: +35,301 USD (+35.30%)
• Profit factor: 3.367
• Winning trades: 80%
• Max drawdown: 15.05%
Even at the height of 2008, the strategy remained profitable, while Buy & Hold was still showing a -22% loss two years later.
Focus 2020 (COVID crash)
• Total P&L: +22,463 USD (+22.46%)
• Profit factor: 4.152
• Winning trades: 72.73%
• Max drawdown: 9.91%
During the COVID mini-crash, the strategy still ended the year +22.46%, almost double Buy & Hold (+12.52%), with limited drawdown.
Observations
• Strong outperformance vs Buy & Hold with less exposure
• Robust across crises (2008, COVID-2020)
• Limited drawdowns, faster recoveries
Model validation and parameter weighting
To check robustness and avoid overfitting, I use a simple weighted-parameters ratio (explained in more detail here: Reddit post ).
In this strategy:
• 4 primary parameters (weight 1)
• 5 secondary parameters (weight 0.5)
• Weighted param count = 4×1 + 5×0.5 = 6.5
• Total trades = 267
• Ratio = 267 ÷ 6.5 ≈ 41
Since this ratio is well above the 25 threshold I usually apply, it appears the model is not overfitted according to my experience — especially given its consistent gains even through crises such as 2008 and COVID-2020.
Disclaimer
This is an educational backtest. It does not constitute investment advice.
Past performance does not guarantee future results. Use at your own risk.
Further notes
In practice, systematic strategies like this are usually executed through automation to avoid human bias and ensure consistency. For those interested, I share more about my general approach and related tools here (personal site): emailtrader.app
Alpha Buy/Sell Signal✅ High Accuracy – Signals are generated using advanced algorithmic conditions to highlight reliable trade opportunities and reduce false entries.
✅ Clear Visual Alerts – Buy and sell signals appear as distinct markers directly on your chart for easy interpretation.
✅ Easy to Use – Apply it directly to your charts without needing to adjust complex settings.
NG MOEX (TF 1 MIN) api NG MOEX (TF 1 MIN) api
Intraday strategy strictly for gas trading on the Moscow Exchange with the ability to trade via API channel directly to the broker. For all questions, write to telegram @yury020481
with respect, Yuri