Gronk-Style Lunar Cycle Projection (fixed 30m base)Based on the lunar cycle timing provided by Gronko Polo - A Bromance in Finance
Indicators and strategies
FVG & SMA @danciFVG zones with 200 SMA & daily dividers for intraday analysis, customizable and clear.
ST Fractals With Percentage DifferenceThis indicator identifies Williams Fractals on your price chart, helping traders spot potential reversal points and short-term highs and lows. This changes default value to 1 and adds percentage difference similar to ST Fractals option on MT5
How It Works:
Up Fractals (▲): Plotted above a candle that is higher than its surrounding candles — a potential short-term top.
Down Fractals (▼): Plotted below a candle that is lower than its surrounding candles — a potential short-term bottom.
Fractals are only drawn if the price difference from the next candle exceeds a minimum percentage, to avoid signals caused by small fluctuations.
The script ensures that both up and down fractals never appear on the same candle, keeping your chart clear.
Settings:
Periods (n): Determines how many candles before and after are considered to find a fractal. Default: 2.
Min % Difference: Filters out insignificant fractals by requiring a minimum difference from the next candle. Default: 0.01%.
Usage Tips:
Can be used to identify support and resistance levels.
Often combined with trend indicators or moving averages to confirm reversals.
Works best in markets with clear trends or volatility, rather than very flat markets.
Visuals:
Green triangle ▲ → Up Fractal (potential top)
Red triangle ▼ → Down Fractal (potential bottom)
ROV - Rising Only VolumeROV - Rising Only Volume
It will show the volume only if it is above the previous period
Prev Swing High/Low Before Session (TF 1H/4H)Higher Lows (HL) indicate weakening selling pressure and possible upward trends. Lower Highs (LH) show reduced buying strength and potential bearish trends.
Volume 2.0Volume with standard deviations.
Helps to identify moderately high/low volume and very high/low volume.
Low volume indicates less market participation. High volume indicates higher market participation.
It forecasts potential changes of sentiment.
Volume with standard deviations (n=14).
Helps to identify moderately high/low volume and very high/low volume. Low volume indicates less market participation. High volume indicates higher market participation.
It forecasts potential changes of sentiment. This indicator has to be used with others. It is an adjunct tool, but a powerful one.
NB:
My previous version "Volume" violated the Pine Code house rules, so it got shielded from public view. This is my first experience with writing in Pine Code and publishing. I suspect it was because I didn't publish with a clean chart without other indicators added. My apologies in advance if version 2.0 is again another violation, which will then get shielded again. I am only publishing out of good will to share that's all.
Custom TP/SL Levels (1%, 2%, 3%)Custom TP/SL Levels (1%, 2%, 3%) — TanTechTrades™
This indicator automatically plots percentage-based take-profit (TP) and stop-loss (SL) levels around the current price, making it easy to visualize risk/reward scenarios for both long and short trades.
🔹 Features
Three configurable TP/SL levels (default: 1%, 2%, 3%)
Separate plotting for long (green = TP, red = SL) and short (blue = TP, purple = SL) setups
Adjustable percentages for flexible strategy testing
Simple visual overlay to assist with trade planning and management
🔹 How It Works
Long setup: SL lines plotted below entry, TP lines above entry
Short setup: SL lines plotted above entry, TP lines below entry
All levels update dynamically as price moves
This tool is useful for traders who want a quick, no-fuss way to manage position exits and visualize multiple TP/SL levels directly on the chart.
⚠️ Disclaimer: For educational purposes only. Not financial advice.
SMA Crossover High/Low LinesSMA Crossover High/Low Lines (@version=5)
Purpose
This indicator plots horizontal lines and optional price labels on the high and low of candles where the price crosses a Simple Moving Average (SMA). It helps identify buy/sell signals visually on the chart.
Inputs
smaLength – Length of the SMA (default: 50).
showType – Which crossovers to show: "Both", "Buy Only", or "Sell Only".
lineLength – How many bars the horizontal line extends (default: 10).
showPriceLabels – Whether to show price labels at crossover points (true/false).
Logic
SMA Calculation – Computes a simple moving average of the closing price.
Crossover Detection:
crossUp → price crosses above SMA (buy signal).
crossDown → price crosses below SMA (sell signal).
Draw Horizontal Lines – At candle high and low of crossover:
Green for buy (crossUp)
Red for sell (crossDown)
Lines extend for lineLength bars
Optional Labels – Shows the high/low price at the end of the horizontal line if showPriceLabels is true.
Visualization
SMA line plotted in blue.
Buy crossovers → green horizontal lines and labels.
Sell crossovers → red horizontal lines and labels.
In short:
This indicator highlights buy/sell points where price crosses the SMA by marking candle highs/lows with colored lines and optional price labels for easy visual reference.
Elliott Wave Rule EngineWhat this tool does
The indicator scans price for two concurrent swing structures—a Small (shorter-degree) and a Large (higher-degree) set—then applies an Elliott/NeoWave rule engine to the most recent 5-swing motive (1-2-3-4-5) or 3-swing corrective (A-B-C). It produces:
Blue lines for Small swings and Orange lines for Large swings.
A rule dashboard (optional) showing PASS/FAIL/WARN for core rules & guidelines.
Buy/Sell labels when (a) a valid motive completes and (b) loop “consensus,” alignment, and scoring gates are satisfied.
Reading the chart
Small swings: thin blue segments, built from your Small settings.
Large swings: thicker orange segments, from your Large settings.
Background tint: faint green when a motive (impulse/diagonal) is valid right now on Small.
Labels (if enabled):
“1…5” or “A-B-C” markers on the latest detected structure.
Buy/Sell label at the last pivot when all gates pass; text may include a score %.
How it works
For both Small and Large degrees the script:
- Loops over all (left, right) combinations you specify (e.g., Small Left = 3..6, Right = 0..0) and calls ta.pivothigh/low.
- Aggregates the results:
- Keeps the most extreme pivot found in the loop (highest high or lowest low) that’s newer than the last accepted swing.
- Gates acceptance by minimum % change versus the last opposite swing (inside the loop) and a post-aggregation filter (Small Minimum swing %, Large Minimum swing %).
- Merges back-to-back same-type swings (HH or LL) by keeping only the more extreme one.
- Keeps only the last N=lookbackWaves swings (default 100).
- Consensus (used for signals) comes from the loop counts:
- sBuyConsensus = small L-count / total-combos (bullish bias)
- sSellConsensus = small H-count / total-combos (bearish bias)
(and the same for Large). This is a data-driven “how many combos agreed” measure.
2) Rule engine (Impulse/Diagonal vs. Corrective)
When there are at least 6 Small swings, the engine tests 1-2-3-4-5:
Hard rules (must pass for an Impulse):
- Wave-2 not > 100% of Wave-1 (no retrace beyond start of W1).
- Wave-3 not the shortest among 1,3,5.
- Wave-4 doesn’t overlap Wave-1 (if it does, structure may be a Diagonal).
- Diagonal eligibility: Rules 1 & 2 pass but Rule 3 fails ⇒ eligible as a Diagonal (
Guidelines (7 checks, count toward a threshold you set):
- W2 retraces a Fib level (within ±fibTol).
- W4 retraces a Fib level (within ±fibTol).
- W3 strongest momentum (speed = |Δprice| / bars).
- Alternation: W2 vs W4 have meaningfully different “sharpness” (price per bar), threshold altSlopeThr.
- Proportion (Price): |W1| and |W3| within propTolP× each other.
- Proportion (Time): W1W3 and W2W4 durations within propTolT×.
- W5 weaker than W3 (momentum divergence proxy).
A Motive is valid if:
- Impulse: all 3 hard rules pass and guideline passes ≥ Min guideline passes.
- Diagonal: diagonal-eligible and guideline passes ≥ Min guideline passes.
- if motive fails, the engine still evaluates ABC as Zigzag and Flat to populate the table:
- Zigzag: B shallower than ~0.618A; C ≈ A or 1.618A (±fibTol).
- Flat: B ≥ ~0.9A; expanded flat if B > 1.0A and C in *A; “running” note if C < A.
3) Signal logic (consensus-gated & scored)
Signals fire only on new Small pivots and only if a Small motive just validated:Direction comes from the motive’s W1 (up = bull, down = bear).
Consensus checks (from the loop):
Use Sell consensus if the last pivot is a High, or Buy consensus if it’s a Low.Require it ≥ Min SMALL loop consensus and ahead of the opposite side by at least Min consensus margin.If you also require Large quality: check the corresponding Large consensus ≥ Min LARGE loop consensus.
Alignment: If Require small/large directional alignment is ON, Small and Large directions must match (or the Large motive must be complete).
Score:
- If Large not required: finalScore = smallConsensus × smallQuality.
- If Large required: finalScore = smallConsensus × smallQuality × largeQuality.
- Need finalScore ≥ Min final score.
When all gates pass, you’ll see “Buy xx%” or “Sell xx%” at the pivot.
Inputs (explained):
- Smaller Wave Swing Detection (Looped)
- Small Left Min / Max (default 3..6): ta.pivot* left widths to scan.
- Small Right Min / Max (default 0..0): right widths to scan (0 = earliest confirmation).
- Small Minimum swing % (post-aggregation) (0.3%): filters out tiny swings after the loop.
- Larger Wave Swing Detection (Looped)
- Large Left Min / Max (100..200) and Right Min/Max (0..0): higher-degree scan (defaults are big; adjust for intraday).
- Large Minimum swing % (post-aggregation) (1.5%).
- Loop Filters (inside the loop)
- Small loop min % change (0.20%): a candidate pivot counts only if move vs. last opposite Small swing ≥ this.
- Large loop min % change (1.50%): same idea for Large.
Rule Engine Tolerances
- Fibonacci tolerance (±%) (0.05 = 5%): closeness to Fib levels.
-Same-degree TIME proportion max (x) (2.00×) and PRICE proportion max (x) (3.00×).
- Alternation slope ratio threshold (0.10): higher = stricter alternation.
- Min guideline passes (0–7) (5): threshold for motive validity.
- Signal Probability (Loop Consensus)
- Min SMALL loop consensus (0.60).
- Min LARGE loop consensus (0.50) (used only if Large validation matters).
- Min consensus margin vs opposite (0.10): e.g., 0.60 vs 0.45 fails (margin 0.15 passes).
Require LARGE 1–5 valid (or diagonal) for signal (off by default).
Min final score (0.20): gate on the composite score.
Annotate label with score % (on).
WARN (orange): guideline not met—pattern can still be valid if total passes ≥ Min guideline passes.
FAQ
Q: Why did I get a diagonal instead of an impulse?
A: Wave-4 overlapped Wave-1 (Rule 3). If Rules 1 & 2 pass and guidelines meet your minimum, it’s eligible as a Diagonal.
Q: Where do Buy/Sell labels come from?
A: Only after a valid Small motive at a new pivot, and only if consensus, alignment, and final score gates pass (per your settings).
Q: It “missed” a wave in hindsight.
A: Pivots require right bars to confirm; extremely tight settings can filter that swing; adjust Small min % or ranges.
Q: Are there repaints?
A: No, It uses standard pivot confirmation; until a pivot is confirmed, recent swings can evolve. After confirmation, lines/labels are stable.
Limitations & disclaimers
Elliott/NeoWave rules are heuristics; markets are messy. Treat outputs as structured context, not certainty.
Consensus is pattern-scan agreement, not probability of profit Not investment advice; always couple with risk management.
50% of Previous 1H Candle (Color Logic)📌 Script Title: 50% Midpoint of Previous 1H Candle (Color Coded)
📝 Description:
This indicator draws a horizontal line at the 50% (midpoint) of the most recently closed 1-hour candle, helping traders visualize intraday support/resistance and sentiment bias.
🔹 Key Features:
Plots the midpoint of the last 1H candle as a horizontal line.
Color-coded line and label:
🟢 Green: Previous candle was bullish
🔴 Red: Previous candle was bearish
⚪ Gray: Neutral (doji or equal open/close)
Displays the exact price level with a floating label.
Works on any lower timeframe chart (e.g., 5m, 15m, 30m).
Automatically updates every hour after the 1H candle closes.
📈 Use Cases:
Trade around the 1H midpoint as a dynamic pivot zone.
Confirm or fade price breakouts/rejections at this level.
Use it with trendlines, supply/demand zones, or VWAP.
🔍 Technical Notes:
The midpoint is calculated using:
Midpoint = (High + Low) / 2
from the most recent closed 1H candle.
Color logic is based on whether the 1H candle closed above or below its open.
🚀 Enhancement Ideas (future updates):
Add optional alerts on cross of the midpoint.
Show multiple historical midpoint levels.
Input toggle to enable/disable color coding.
Whether you’re scalping intraday or watching for reaction zones, this tool gives you a clean, real-time level to anchor your trades around.
Happy trading! 💹
— Built with ❤️ in Pine Script v6
RSI Crossover AlertRSI Crossover Alert Indicator - User Guide
The RSI Crossover Alert Indicator is a comprehensive technical analysis tool that detects multiple types of RSI crossovers and generates real-time alerts. It combines traditional RSI analysis with signal lines, divergence detection, and multi-level crossing alerts.
1. Multiple Crossover Detection
- RSI/Signal Line Cross: Signals a primary trend change.
- RSI/Second Signal Cross: Confirmation signals for stronger trends.
- Level Crossings: Crosses of Overbought 70, Oversold 30, and Midline 50.
- Divergence Detection: Hidden and regular divergences for reversal signals.
2. Alert Types
- Alert: RSI > Signal
Description: Bullish momentum is building.
Signal: Consider long positions.
- Alert: RSI < Signal
Description: Bearish momentum is building.
Signal: Consider short positions.
- Alert: RSI > 70
Description: Entering the overbought zone.
Signal: Prepare for a potential reversal.
- Alert: RSI < 30
Description: Entering the oversold zone.
Signal: Watch for a bounce opportunity.
- Alert: RSI crosses 50
Description: A shift in momentum.
Signal: Trend confirmation.
3. Visual Components
- Lines: RSI blue, Signal orange, Second Signal purple
- Histogram: Visualizes momentum by showing the difference between RSI and the Signal line.
- Background Zones: Red overbought, Green oversold
- Markers: Up/down triangles to indicate crossovers.
- Info Table: Real-time RSI values and status.
Strategy 1: Classic Crossover
- Entry Long: RSI crosses above the Signal Line AND RSI is below 50.
- Entry Short: RSI crosses below the Signal Line AND RSI is above 50.
- Take Profit: On the opposite signal.
- Stop Loss: At the recent swing high/low.
Strategy 2: Extreme Zone Reversal
- Entry Long: RSI is below 30 and crosses above the Signal Line.
- Entry Short: RSI is above 70 and crosses below the Signal Line.
- Risk Management: Higher win rate but fewer signals. Use a minimum 2:1 risk-reward ratio.
Strategy 3: Divergence Trading
- Setup: Enable divergence alerts and look for price/RSI divergence. Wait for an RSI crossover for confirmation.
- Entry: Enter on the crossover after the divergence appears. Place the stop loss beyond the starting point of the divergence.
Strategy 4: Multi-Timeframe Confirmation
1. Check the higher timeframe e.g. Daily to identify the main trend.
2. Use the current timeframe e.g. 4H/1H for your entry.
3. Only enter in the direction of the main trend.
4. Use the RSI crossover as the entry trigger.
Optimal Settings by Market
- Forex Major Pairs
RSI Length: 14, Signal Length: 9, Overbought/Oversold: 70/30
- Crypto High Volatility
RSI Length: 10-12, Signal Length: 6-8, Overbought/Oversold: 75/25
- Stocks Trending
RSI Length: 14-21, Signal Length: 9-12, Overbought/Oversold: 70/30
- Commodities
RSI Length: 14, Signal Length: 9, Overbought/Oversold: 80/20
Risk Management Rules
1. Position Sizing: Never risk more than 1-2% on a single trade. Reduce size in ranging markets.
2. Stop Loss Placement: Place stops beyond the recent swing high/low for crossovers. Using an ATR-based stop is also effective.
3. Profit Taking: Take partial profits at a 1:1 risk-reward ratio. Switch to a trailing stop after reaching 2:1.
1. Filtering Signals
- Combine with volume indicators.
- Confirm the trend on a higher timeframe.
- Wait for candlestick pattern confirmation.
2. Avoid Common Mistakes
- Don't trade every single crossover.
- Avoid taking signals against a strong trend.
- Do not ignore risk management.
3. Market Conditions
- Trending Market: Focus on midline 50 crosses.
- Ranging Market: Look for reversals from overbought/oversold levels.
- Volatile Market: Widen the overbought/oversold levels.
- If you get too many false signals:
Increase the signal line period, add other confirmation indicators, or use a higher timeframe.
- If you are missing major moves:
Decrease the RSI length, shorten the signal line period, or check your alert settings.
Recommended Combinations
1. RSI + MACD: For dual momentum confirmation.
2. RSI + Bollinger Bands: For volatility-adjusted signals.
3. RSI + Volume: To confirm the strength of a signal.
4. RSI + Moving Averages: To use as a trend filter.
This indicator provides a comprehensive RSI analysis. Success depends on proper configuration, risk management, and combining signals with the overall market context. Start with the default settings, then optimize based on your trading style and market conditions.
ORB with Fib Levels - TradingbrockOpening Range (OR) Indicator Overview
This TradingView indicator analyzes and displays the Opening Range - a popular day trading concept that tracks price movement during the first 30-60 minutes of the trading session.
Core Functionality:
Opening Range Detection: By default, it monitors the 9:30-10:00 AM ET period and tracks the highest high and lowest low during this time frame, creating upper and lower boundaries.
Fibonacci Retracement Levels: Inside the opening range, it displays five key Fibonacci levels:
0.236 (23.6% - shallow retracement)
0.382 (38.2% - standard retracement)
0.500 (50% - halfway point)
0.618 (61.8% - golden ratio)
0.786 (78.6% - deep retracement)
Extension Levels: The indicator projects additional levels beyond the opening range:
1x extension above/below the range
2x extension levels that only appear when price breaks the first extension
Trading Applications:
Support & Resistance: The opening range high/low often act as key levels throughout the trading day
Breakout Trading: Many traders watch for price to break above or below the opening range
Mean Reversion: The Fibonacci levels within the range can serve as potential reversal points
Risk Management: Helps define clear levels for stop losses and profit targets
The indicator essentially gives traders a framework to understand how price is behaving relative to the early session's established range, which often sets the tone for the entire trading day.
(Binance 10m binary contact signals(repainted)
BINANCE:BTCUSDT
Suggestion:use chart of spot instead of swap. using for binance binary contacts(事件合约)
This script is a 10-minute binary event contract trading strategy indicator designed for BTC and ETH on Binance. It combines multiple technical analysis tools with a unique market session filter to generate potential entry and exit signals. Here’s a breakdown of its core functions:
---
1. Market Session Visualization
· It highlights four major trading sessions (Tokyo, London, New York, and Sydney) with colored boxes or background zones.
· You can toggle each session on/off and customize its appearance.
· This helps traders quickly identify which financial market is currently active, as volatility and momentum often shift between sessions.
---
2. Trading Signals Generation
The indicator combines several technical factors to produce signals:
· Moving Average Crosses: Uses SMA (5) and SMA (9) for golden/death cross signals.
· RSI Momentum: Identifies overbought/oversold conditions and crossovers above/below the 50 level.
· Volume Confirmation: Checks if current volume is above its 20-period average to confirm strength.
· Price Deviation: Measures how far price has moved from its short-term average (SMA 5).
Signals are plotted as green upward triangles (buy) or red downward triangles (sell) below or above the bars.
---
3. Smart Session Filtering (Key Feature)
· A unique filter ensures signals are only generated during valid market hours (when only one major session is active).
· It avoids overlap periods (e.g., when London and New York are both open), which often bring erratic price action and false signals.
· This makes the strategy more robust by focusing on periods with clearer trends and higher predictability.
---
4. Anti-Repainting Options
· The script includes an option (show not strong signals) to reduce repainting:
· If enabled, it requires signal confirmation on the next candle for stronger, more reliable signals.
· If disabled, all signals are shown in real-time (but may be more prone to repainting).
---
5. Alerts and Timeframe Compatibility
· Built-in alert conditions allow you to get notified when new signals appear.
· It is designed specifically for 10-minute charts of BTC and ETH binary event contracts.
---
Summary:
This tool is best for traders who want to:
· Trade short-term binary options or event contracts based on 10-minute candles.
· Combine multi-session awareness with classic technical indicators.
· Filter out noisy market periods and focus on high-probability setups.
⚠️ Note: Since some signals may repaint, use the confirmation filter (show not strong signals) for more consistent results. Always test the strategy in a demo account before going live.
Let me know if you need help customizing or interpreting the signals.
ADX MTF mura visionOverview
ADX MTF — mura vision measures trend strength and visualizes a higher-timeframe (HTF) ADX on any chart. The current-TF ADX is drawn as a line; the HTF ADX is rendered as “step” segments to reflect closed HTF bars without repainting. Optional soft fills highlight the 20–25 (trend forming) and 40–50 (strong trend) zones.
How it works
ADX (current TF) : Classic Wilder formulation using DI components and RMA smoothing.
HTF ADX : Requested via request.security(..., lookahead_off, gaps_off).
When a new HTF bar opens, the previous value is frozen as a horizontal segment.
The current HTF bar is shown as a live moving segment.
This staircase look is expected on lower timeframes.
Auto timeframe mapping
If “Auto” is selected, the HTF is derived from the chart TF:
<30m → 60m, 30–<240m → 240m, 240m–<1D → 1D, 1D → 1W, 1W/2W → 1M, ≥1M → same.
Inputs
DI Length and ADX Smoothing — core ADX parameters.
Higher Time Frame — Auto or a fixed TF.
Line colors/widths for current ADX and HTF ADX.
Fill zone 20–25 and Fill zone 40–50 — optional light background fills.
Number of HTF ADX Bars — limits stored HTF segments to control chart load.
Reading the indicator
ADX < 20: typically range-bound conditions; trend setups require extra caution.
20–25: trend emergence; breakouts and continuation structures gain validity.
40–50: strong trend; favor continuation and manage with trailing stops.
>60 and turning down: possible trend exhaustion or transition toward range.
Note: ADX measures strength, not direction. Combine with your directional filter (e.g., price vs. MA, +DI/−DI, structure/levels).
Non-repainting behavior
HTF values use lookahead_off; closed HTF bars are never revised.
The only moving piece is the live segment for the current HTF bar.
Best practices
Use HTF ADX as a regime filter; time entries with the current-TF ADX rising through your threshold.
Pair with ATR-based stops and a MA/structure filter for direction.
Consider higher thresholds on highly volatile altcoins.
Performance notes
The script draws line segments for HTF bars. If your chart becomes heavy, reduce “Number of HTF ADX Bars.”
Disclaimer
This script is for educational purposes only and does not constitute financial advice. Trading involves risk.
Sentinel 5 — OHL daybreak signals [KedArc Quant]Overview
Sentinel 5 plots the first-bar high/low of each trading session and gives clean, rules-based signals in two ways:
1) OHL Setups at the close of the first bar (Open equals/near High for potential short; Open equals/near Low for potential long).
2) Breakout Signals later in the session when price breaks the first-bar High/Low, with optional body/penetration filters.
Basic workflow
1. Wait for the first session bar to finish.
*If O≈H (optionally by proximity) → short setup. •
*If O≈L → long setup. • If neither happens, optionally allow later breakouts.
2. Optional: Act only on breakouts that penetrate a minimum % of that bar’s range/body.
3. Skip the day automatically if the first bar is abnormally large (marubozu-like / extreme ATR / outsized vs yesterday).
Signals & Markers
Markers on the chart:
▲ O=L (exact) / O near L (proximity) – long setup at first-bar close.
▼ O=H (exact) / O near H (proximity) – short setup at first-bar close.
▲ Breakout Long – later bar breaks above first-bar High meeting your penetration rule.
▼ Breakout Short – later bar breaks below first-bar Low meeting your penetration rule.
ROC / VWAP / ATR / RSI / MACD Combo//@version=5
indicator("ROC / VWAP / ATR / RSI / MACD Combo", overlay=true)
// === INPUTS ===
showROC = input.bool(true, "Show ROC")
rocLength = input.int(14, "ROC Length")
showVWAP = input.bool(true, "Show VWAP")
showATR = input.bool(true, "Show ATR")
atrLength = input.int(14, "ATR Length")
showRSI = input.bool(true, "Show RSI")
rsiLength = input.int(14, "RSI Length")
showMACD = input.bool(true, "Show MACD")
fastLen = input.int(12, "MACD Fast Length")
slowLen = input.int(26, "MACD Slow Length")
sigLen = input.int(9, "MACD Signal Length")
// === CALCULATIONS ===
// ROC
roc = ta.roc(close, rocLength)
// VWAP
vwap = ta.vwap
// ATR
atr = ta.atr(atrLength)
// RSI
rsi = ta.rsi(close, rsiLength)
// MACD
macdLine = ta.ema(close, fastLen) - ta.ema(close, slowLen)
signal = ta.ema(macdLine, sigLen)
hist = macdLine - signal
// === PLOTTING ===
// ROC (separate scale)
plot(showROC ? roc : na, title="ROC", color=color.aqua, display=display.none)
// VWAP (on chart)
plot(showVWAP ? vwap : na, title="VWAP", color=color.orange, linewidth=2)
// ATR (separate scale)
plot(showATR ? atr : na, title="ATR", color=color.red, display=display.none)
// RSI (separate scale, 0-100)
plot(showRSI ? rsi : na, title="RSI", color=color.blue, display=display.none)
hline(70, "RSI Overbought", color=color.gray, linestyle=hline.style_dotted)
hline(30, "RSI Oversold", color=color.gray, linestyle=hline.style_dotted)
// MACD (separate scale)
plot(showMACD ? macdLine : na, title="MACD Line", color=color.green, display=display.none)
plot(showMACD ? signal : na, title="Signal Line", color=color.red, display=display.none)
plot(showMACD ? hist : na, title="MACD Histogram", style=plot.style_columns, color=hist>=0 ? color.new(color.green,50) : color.new(color.red,50), display=display.none)
ATR + Moving Average Indicator//@version=5
indicator("ATR + Moving Average Indicator", overlay=true)
// === Inputs ===
atrLength = input.int(14, "ATR Length")
maLength = input.int(50, "Moving Average Length")
maType = input.string("EMA", "Moving Average Type", options= )
// === ATR Calculation ===
atr = ta.atr(atrLength)
// === Moving Average Calculation ===
ma = switch maType
"SMA" => ta.sma(close, maLength)
"EMA" => ta.ema(close, maLength)
"WMA" => ta.wma(close, maLength)
// === Plot Moving Average ===
plot(ma, title="Moving Average", color=color.yellow, linewidth=2)
// === Show ATR on separate panel ===
plot(atr, title="ATR", color=color.red, linewidth=2, display=display.none) // hides ATR from chart
// To see ATR in a separate pane, enable this line instead:
// indicator("ATR + Moving Average Indicator", overlay=false)
Martingale Strategy Simulator [BackQuant]Martingale Strategy Simulator
Purpose
This indicator lets you study how a martingale-style position sizing rule interacts with a simple long or short trading signal. It computes an equity curve from bar-to-bar returns, adapts position size after losing streaks, caps exposure at a user limit, and summarizes risk with portfolio metrics. An optional Monte Carlo module projects possible future equity paths from your realized daily returns.
What a martingale is
A martingale sizing rule increases stake after losses and resets after a win. In its classical form from gambling, you double the bet after each loss so that a single win recovers all prior losses plus one unit of profit. In markets there is no fixed “even-money” payout and returns are multiplicative, so an exact recovery guarantee does not exist. The core idea is unchanged:
Lose one leg → increase next position size
Lose again → increase again
Win → reset to the base size
The expectation of your strategy still depends on the signal’s edge. Sizing does not create positive expectancy on its own. A martingale raises variance and tail risk by concentrating more capital as a losing streak develops.
What it plots
Equity – simulated portfolio equity including compounding
Buy & Hold – equity from holding the chart symbol for context
Optional helpers – last trade outcome, current streak length, current allocation fraction
Optional diagnostics – daily portfolio return, rolling drawdown, metrics table
Optional Monte Carlo probability cone – p5, p16, p50, p84, p95 aggregate bands
Model assumptions
Bar-close execution with no slippage or commissions
Shorting allowed and frictionless
No margin interest, borrow fees, or position limits
No intrabar moves or gaps within a bar (returns are close-to-close)
Sizing applies to equity fraction only and is capped by your setting
All results are hypothetical and for education only.
How the simulator applies it
1) Directional signal
You pick a simple directional rule that produces +1 for long or −1 for short each bar. Options include 100 HMA slope, RSI above or below 50, EMA or SMA crosses, CCI and other oscillators, ATR move, BB basis, and more. The stance is evaluated bar by bar. When the stance flips, the current trade ends and the next one starts.
2) Sizing after losses and wins
Position size is a fraction of equity:
Initial allocation – the starting fraction, for example 0.15 means 15 percent of equity
Increase after loss – multiply the next allocation by your factor after a losing leg, for example 2.00 to double
Reset after win – return to the initial allocation
Max allocation cap – hard ceiling to prevent runaway growth
At a high level the size after k consecutive losses is
alloc(k) = min( cap , base × factor^k ) .
In practice the simulator changes size only when a leg ends and its PnL is known.
3) Equity update
Let r_t = close_t / close_{t-1} − 1 be the symbol’s bar return, d_{t−1} ∈ {+1, −1} the prior bar stance, and a_{t−1} the prior bar allocation fraction. The simulator compounds:
eq_t = eq_{t−1} × (1 + a_{t−1} × d_{t−1} × r_t) .
This is bar-based and avoids intrabar lookahead. Costs, slippage, and borrowing costs are not modeled.
Why traders experiment with martingale sizing
Mean-reversion contexts – if the signal often snaps back after a string of losses, adding size near the tail of a move can pull the average entry closer to the turn
Behavioral or microstructure edges – some rules have modest edge but frequent small whipsaws; size escalation may shorten time-to-recovery when the edge manifests
Exploration and stress testing – studying the relationship between streaks, caps, and drawdowns is instructive even if you do not deploy martingale sizing live
Why martingale is dangerous
Martingale concentrates capital when the strategy is performing worst. The main risks are structural, not cosmetic:
Loss streaks are inevitable – even with a 55 percent win rate you should expect multi-loss runs. The probability of at least one k-loss streak in N trades rises quickly with N.
Size explodes geometrically – with factor 2.0 and base 10 percent, the sequence is 10, 20, 40, 80, 100 (capped) after five losses. Without a strict cap, required size becomes infeasible.
No fixed payout – in gambling, one win at even odds resets PnL. In markets, there is no guaranteed bounce nor fixed profit multiple. Trends can extend and gaps can skip levels.
Correlation of losses – losses cluster in trends and in volatility bursts. A martingale tends to be largest just when volatility is highest.
Margin and liquidity constraints – leverage limits, margin calls, position limits, and widening spreads can force liquidation before a mean reversion occurs.
Fat tails and regime shifts – assumptions of independent, Gaussian returns can understate tail risk. Structural breaks can keep the signal wrong for much longer than expected.
The simulator exposes these dynamics in the equity curve, Max Drawdown, VaR and CVaR, and via Monte Carlo sketches of forward uncertainty.
Interpreting losing streaks with numbers
A rough intuition: if your per-trade win probability is p and loss probability is q=1−p , the chance of a specific run of k consecutive losses is q^k . Over many trades, the chance that at least one k-loss run occurs grows with the number of opportunities. As a sanity check:
If p=0.55 , then q=0.45 . A 6-loss run has probability q^6 ≈ 0.008 on any six-trade window. Across hundreds of trades, a 6 to 8-loss run is not rare.
If your size factor is 1.5 and your base is 10 percent, after 8 losses the requested size is 10% × 1.5^8 ≈ 25.6% . With factor 2.0 it would try to be 10% × 2^8 = 256% but your cap will stop it. The equity curve will still wear the compounded drawdown from the sequence that led to the cap.
This is why the cap setting is central. It does not remove tail risk, but it prevents the sizing rule from demanding impossible positions
Note: The p and q math is illustrative. In live data the win rate and distribution can drift over time, so real streaks can be longer or shorter than the simple q^k intuition suggests..
Using the simulator productively
Parameter studies
Start with conservative settings. Increase one element at a time and watch how the equity, Max Drawdown, and CVaR respond.
Initial allocation – lower base reduces volatility and drawdowns across the board
Increase factor – set modestly above 1.0 if you want the effect at all; doubling is aggressive
Max cap – the most important brake; many users keep it between 20 and 50 percent
Signal selection
Keep sizing fixed and rotate signals to see how streak patterns differ. Trend-following signals tend to produce long wrong-way streaks in choppy ranges. Mean-reversion signals do the opposite. Martingale sizing interacts very differently with each.
Diagnostics to watch
Use the built-in metrics to quantify risk:
Max Drawdown – worst peak-to-trough equity loss
Sharpe and Sortino – volatility and downside-adjusted return
VaR 95 percent and CVaR – tail risk measures from the realized distribution
Alpha and Beta – relationship to your chosen benchmark
If you would like to check out the original performance metrics script with multiple assets with a better explanation on all metrics please see
Monte Carlo exploration
When enabled, the forecast draws many synthetic paths from your realized daily returns:
Choose a horizon and a number of runs
Review the bands: p5 to p95 for a wide risk envelope; p16 to p84 for a narrower range; p50 as the median path
Use the table to read the expected return over the horizon and the tail outcomes
Remember it is a sketch based on your recent distribution, not a predictor
Concrete examples
Example A: Modest martingale
Base 10 percent, factor 1.25, cap 40 percent, RSI>50 signal. You will see small escalations on 2 to 4 loss runs and frequent resets. The equity curve usually remains smooth unless the signal enters a prolonged wrong-way regime. Max DD may rise moderately versus fixed sizing.
Example B: Aggressive martingale
Base 15 percent, factor 2.0, cap 60 percent, EMA cross signal. The curve can look stellar during favorable regimes, then a single extended streak pushes allocation to the cap, and a few more losses drive deep drawdown. CVaR and Max DD jump sharply. This is a textbook case of high tail risk.
Strengths
Bar-by-bar, transparent computation of equity from stance and size
Explicit handling of wins, losses, streaks, and caps
Portable signal inputs so you can A–B test ideas quickly
Risk diagnostics and forward uncertainty visualization in one place
Example, Rolling Max Drawdown
Limitations and important notes
Martingale sizing can escalate drawdowns rapidly. The cap limits position size but not the possibility of extended adverse runs.
No commissions, slippage, margin interest, borrow costs, or liquidity limits are modeled.
Signals are evaluated on closes. Real execution and fills will differ.
Monte Carlo assumes independent draws from your recent return distribution. Markets often have serial correlation, fat tails, and regime changes.
All results are hypothetical. Use this as an educational tool, not a production risk engine.
Practical tips
Prefer gentle factors such as 1.1 to 1.3. Doubling is usually excessive outside of toy examples.
Keep a strict cap. Many users cap between 20 and 40 percent of equity per leg.
Stress test with different start dates and subperiods. Long flat or trending regimes are where martingale weaknesses appear.
Compare to an anti-martingale (increase after wins, cut after losses) to understand the other side of the trade-off.
If you deploy sizing live, add external guardrails such as a daily loss cut, volatility filters, and a global max drawdown stop.
Settings recap
Backtest start date and initial capital
Initial allocation, increase-after-loss factor, max allocation cap
Signal source selector
Trading days per year and risk-free rate
Benchmark symbol for Alpha and Beta
UI toggles for equity, buy and hold, labels, metrics, PnL, and drawdown
Monte Carlo controls for enable, runs, horizon, and result table
Final thoughts
A martingale is not a free lunch. It is a way to tilt capital allocation toward losing streaks. If the signal has a real edge and mean reversion is common, careful and capped escalation can reduce time-to-recovery. If the signal lacks edge or regimes shift, the same rule can magnify losses at the worst possible moment. This simulator makes those trade-offs visible so you can calibrate parameters, understand tail risk, and decide whether the approach belongs anywhere in your research workflow.
Trend Bars with Okuninushi Line Filter# Trend Bars with Okuninushi Line Filter: A Powerful Trading Indicator
##TrendSpider Hackathon 2025 Trend Bars with Okuninushi Filter
trendspider.com
##X
x.com
## Introduction
The **Trend Bars with Okuninushi Line Filter** is an innovative technical indicator that combines two powerful concepts: trend bar analysis and the Okuninushi Line filter. This indicator helps traders identify high-quality trending moves by analyzing candle body strength relative to the overall price range while ensuring the price action aligns with the dominant market structure.
## What Are Trend Bars?
Trend bars are candles where the body (distance between open and close) represents a significant portion of the total price range (high to low). These bars indicate strong directional momentum with minimal indecision, making them valuable signals for trend continuation.
### Key Characteristics:
- **Strong directional movement**: Large body relative to total range
- **Minimal upper/lower shadows**: Shows sustained pressure in one direction
- **High conviction**: Represents decisive market action
## The Okuninushi Line Filter
The Okuninushi Line, also known as the Kijun Line in Ichimoku analysis, is calculated as the midpoint of the highest high and lowest low over a specified period (default: 52 periods).
**Formula**: `(Highest High + Lowest Low) / 2`
This line acts as a dynamic support/resistance level and trend filter, helping to:
- Identify the overall market bias
- Filter out counter-trend signals
- Provide confluence for trade entries
## How the Indicator Works
The indicator combines these two concepts with the following logic:
### Bull Trend Bars (Green)
A candle is colored **green** when ALL conditions are met:
1. **Bullish candle**: Close > Open
2. **Strong body**: |Close - Open| ≥ Threshold × (High - Low)
3. **Above trend filter**: Close > Okuninushi Line
### Bear Trend Bars (Red)
A candle is colored **red** when ALL conditions are met:
1. **Bearish candle**: Close < Open
2. **Strong body**: |Close - Open| ≥ Threshold × (High - Low)
3. **Below trend filter**: Close < Okuninushi Line
### Neutral Bars (Gray)
All other candles that don't meet the complete criteria are colored **gray**.
## Customizable Parameters
### Trend Bar Threshold
- **Range**: 10% to 100%
- **Default**: 75%
- **Purpose**: Controls how "strong" a candle must be to qualify as a trend bar
**Threshold Effects:**
- **Low (10-30%)**: More sensitive, catches smaller trending moves
- **Medium (50-75%)**: Balanced approach, filters out most noise
- **High (80-100%)**: Very selective, only captures the strongest moves
### Okuninushi Line Length
- **Default**: 52 periods
- **Purpose**: Determines the lookback period for calculating the midpoint
- **Common Settings**:
- for 15m is 92, per 1 day as 23h*4(15m in 1h)
- for 1h is 115, per 1 week as 5d*23(23h in 1d)
- for 4h is 120, per 1 month as 20d*6
- for 1d is 65, per 3 months
- for 1w is 52, per 1 year
## Trading Applications
### 1. Trend Continuation Signals
- **Green bars**: Look for bullish continuation opportunities
- **Red bars**: Consider bearish continuation setups
- **Gray bars**: Exercise caution, mixed signals
### 2. Market Structure Analysis
- Clusters of same-colored bars indicate strong trends
- Alternating colors suggest choppy, indecisive markets
- Transition from red to green (or vice versa) may signal trend changes
### 3. Entry Timing
- Use colored bars as confirmation for existing trade setups
- Wait for color alignment with your market bias
- Avoid trading during predominantly gray periods
### 4. Risk Management
- Gray bars can serve as early warning signs of weakening trends
- Color changes might indicate appropriate exit points
- Use in conjunction with other risk management tools
## Advantages
1. **Dual Filtering**: Combines momentum (trend bars) with trend direction (Okuninushi Line)
2. **Visual Clarity**: Immediate visual feedback through candle coloring
3. **Customizable**: Adjustable parameters for different trading styles
4. **Versatile**: Works across multiple timeframes and instruments
5. **Objective**: Rule-based system reduces subjective interpretation
## Limitations
1. **Lagging Nature**: Based on historical price data
2. **False Signals**: Can produce whipsaws in choppy markets
3. **Parameter Sensitivity**: Requires optimization for different instruments
4. **Market Conditions**: May be less effective in ranging markets
## Best Practices
### Optimization Tips:
- **Volatile Markets**: Use higher thresholds (80-90%)
- **Steady Trends**: Use moderate thresholds (60-75%)
- **Short-term Trading**: Shorter Okuninushi Line periods (26)
- **Long-term Analysis**: Longer Okuninushi Line periods (104+)
### Combination Strategies:
- Pair with volume indicators for confirmation
- Use alongside support/resistance levels
- Combine with other trend-following indicators
- Consider market context and overall trend direction
## Conclusion
The Trend Bars with Okuninushi Line Filter offers traders a sophisticated yet intuitive way to identify high-quality trending moves. By combining the momentum characteristics of trend bars with the directional filter of the Okuninushi Line, this indicator helps traders focus on the most promising opportunities while avoiding low-probability setups.
Remember that no single indicator should be used in isolation. Always consider market context, risk management, and other technical factors when making trading decisions. The true power of this indicator lies in its ability to quickly highlight periods of strong, aligned price action – exactly what trend traders are looking for.
MA Availability ETA (SMA100/EMA200)This tool helps traders understand when long-term moving averages become available on any chosen timeframe.
Many new symbols, pairs, or timeframes don’t have enough price history to immediately plot long moving averages like SMA(100) and EMA(200). This script calculates and displays:
✅ Bars Remaining – how many bars are still needed before each moving average can be plotted reliably.
✅ ETA Duration – an estimate of how long (in chart time units) it will take until each MA is available.
✅ Status Table & Label – compact visual summary on the chart and in a table at the top-right corner.
✅ Vertical Marker – a dotted line showing exactly where both SMA(100) & EMA(200) first appear together.
✅ Alerts – optional alerts notify you the moment SMA(100) or EMA(200) become available.
🔑 Features
Works on any timeframe and instrument.
Highlights SMA(100) and EMA(200) on the chart for reference.
Lets you choose whether EMA(200) should be considered ready immediately, or only after a full 200-bar history.
Useful for traders who rely on long-term MA signals (golden cross, dynamic support/resistance, trend confirmation) and want to know when these tools will be ready on fresh charts.
🎯 Use Cases
New listings / low-history assets → See when SMA100 & EMA200 become usable.
Backtesting or forward-testing → Anticipate when long-term signals will first appear.
Trend-following strategies → Prepare in advance for crossovers or key support/resistance confluence zones.
⚠️ Note: ETAs are based on chart resolution and assume continuous data; real-world session gaps, weekends, or illiquid trading can make availability slightly later.
👉 Add this to your chart and you’ll always know when the big moving averages arrive — a critical moment for many upside moves and long-term strategies.
X-Scalp by LogicatX-Scalp by Logicat — Clean-Range MTF Scalper
Turn noisy intraday action into clear, actionable scalps. X-Scalp builds “Clean Range” zones only when three timeframes agree (default: M30/M15/M5), then waits for a single, high-quality M5 confirmation to print a BUY/SELL label. It’s fast, simple, and ruthlessly focused on precision.
What it does
Clean Range zones: Drawn from the last completed M30 candle only when M30/M15/M5 align (all green or all red).
Size filter (pips): Ignore tiny, low-value ranges with a configurable minimum height (auto-pip detection included).
Extend-until-mitigated: Zones stretch right and “freeze” on first mitigation (close inside or close beyond, your choice). Optional fade when mitigated.
Laser M5 entries (one per box):
Red M5 bar inside a green zone → SELL
Green M5 bar inside a red zone → BUY
Prints once per zone on the closed M5 candle—no spam.
Quality of life: Keep latest N zones, customizable colors, optional H4 reference lines, alert conditions for both zone creation and entries.
Why traders love it
Clarity: Filters chop; you see only aligned zones and one clean trigger.
Speed: Designed for scalpers on FX, XAU/USD, indices, and more.
Control: Tune lookback, pip threshold, mitigation logic, and visuals to fit your playbook.
Tips
Use on liquid sessions for best results.
Combine with your risk model (fixed R, partials at mid/edge, etc.).
Backtest different pip filters per symbol.
Disclaimer: No indicator guarantees profits. Trade responsibly and manage risk.
RSI Multi Time FrameWhat it is
A clean, two-layer RSI that shows your chart-timeframe RSI together with a higher-timeframe (HTF) RSI on the same pane. The HTF line is drawn as a live segment plus frozen “steps” for each completed HTF bar, so you can see where the higher timeframe momentum held during your lower-timeframe bars.
How it works
Auto HTF mapping (when “Auto” is selected):
Intraday < 30m → uses 60m (1-hour) RSI
30m ≤ tf < 240m (4h) → uses 240m (4-hour) RSI
240m ≤ tf < 1D → uses 1D RSI
1D → uses 1W RSI
1W or 2W → uses 1M RSI
≥ 1M → keeps the same timeframe
The HTF series is requested with request.security(..., gaps_off, lookahead_off), so values are confirmed bar-by-bar. When a new HTF bar begins, the previous value is “frozen” as a horizontal segment; the current HTF value is shown by a short moving segment and a small dot (so you can read the last value easily).
Visuals
Current RSI (chart TF): solid line (color/width configurable).
HTF RSI: same-pane line + tiny circle for the latest value; historical step segments show completed HTF bars.
Guides: dashed 70 / 30 bands, dotted 60/40 helpers, dashed 50 midline.
Inputs
Higher Time Frame: Auto or a fixed TF (1, 3, 5, 10, 15, 30, 45, 60, 120, 180, 240, 360, 480, 720, D, W, 2W, M, 3M, 6M, 12M).
Length: RSI period (default 14).
Source: price source for RSI.
RSI / HTF RSI colors & widths.
Number of HTF RSI Bars: how many frozen HTF segments to keep.
Reading it
Alignment: When RSI (current TF) and HTF RSI both push in the same direction, momentum is aligned across frames.
Divergence across frames: Current RSI failing to confirm HTF direction can warn about chops or early slowdowns.
Zones: 70/30 boundaries for classic overbought/oversold; 60/40 can be used as trend bias rails; 50 is the balance line.
This is a context indicator, not a signal generator. Combine with your entry/exit rules.
Notes & limitations
HTF values do not repaint after their bar closes (lookahead is off). The short “live” segment will evolve until the HTF bar closes — this is expected.
Very small panels or extremely long histories may impact performance if you keep a large number of HTF segments.
Credits
Original concept by LonesomeTheBlue; Pine v6 refactor and auto-mapping rules by trading_mura.
Suggested use
Day traders: run the indicator on 5–15m and keep HTF on Auto to see 1h/4h momentum.
Swing traders: run it on 1h–4h and watch the daily HTF.
Position traders: run on daily and watch the weekly HTF.
If you find it useful, a ⭐ helps others discover it.
2ATR / Close %Certainly. Here is the English version of the indicator description you requested.
---
### **2ATR Stop-Loss Ratio**
This indicator provides a straightforward calculation of **what percentage a 2ATR (Average True Range) move represents relative to the current price**. It's a specialized tool designed to help traders set dynamic, volatility-based stop-loss levels.
---
### **Purpose of the Indicator**
Many traders use a **2ATR** as their standard for setting a stop-loss, believing it's a good measure of a stock's typical movement. However, it can be difficult to quickly determine the exact percentage a 2ATR drop represents from the current price. This indicator solves that problem by giving you a clear, single number that shows the **anticipated percentage loss before you even enter a position**.
---
### **How It Works**
The indicator is calculated using a simple formula:
**(2 * ATR(20) / Current Price) * 100**
* `ATR(20)`: The Average True Range over the last 20 periods. This period can be customized in the indicator's settings.
* `Current Price`: The closing price at the time of calculation.
---
### **How to Use It**
* **Assess Risk**: A higher number on the indicator means greater volatility, indicating a wider stop-loss range.
* **Set a Stop-Loss**: If the indicator shows **3%**, it means a 2ATR move is roughly a 3% change from the current price. This gives you a clear understanding of the potential loss.
* **Adjust Position Size**: If the potential percentage loss is larger than you're comfortable with, you can use this information to reduce your position size, effectively managing your risk.
This tool is especially useful for trading highly volatile stocks, as it helps you establish a clear and effective risk management strategy.