REJECTION DETECTOR🔥 CTR (Candle Terjepit - Rejection)
This indicator is specifically designed to detect Rejection Candles, which are moments when the price rejects a certain level and has the potential to form a strong reversal or rapid reaction — an important signal for scalpers and price action traders.
💡 Key Concept:
Rejection is a form of market reaction to areas of liquidity, support-resistance, or order block zones. Candles with long tails and small bodies indicate an imbalance between buyers and sellers, providing an early indication that the price may soon reverse.
⚙️ Key Features
🔍 Automatic Rejection Candle Detection (Buy & Sell)
🧠 Body-to-tail ratio filter for more precise signal validation
🎨 Customizable candle colors and appearance
📊 Suitable for all pairs and timeframes
Candlestick analysis
无敌大饺子缺口Indicator Name:Dumpling Price Action Gaps (Price Action Gaps)
Type: Price Action Indicator / Technical Analysis Tool
Applicable Markets: Stocks, Futures, Forex, Cryptocurrencies, and other charting markets
Timeframe: Any timeframe; supports multi-timeframe EMA smoothing
Indicator Overview
This indicator is a visual analysis tool based on Price Action and Fair Value Gaps (FVGs). It automatically identifies bullish and bearish gaps in the market, helping traders spot potential support and resistance areas, gap fill opportunities, and market sentiment turning points.
By combining EMA (Exponential Moving Average) and ATR (Average True Range) filtering, the indicator clearly plots on the chart:
Bullish Gaps: Highlight rapid upward price gaps.
Bearish Gaps: Highlight rapid downward price gaps.
Mitigation Zones: Mark areas where gaps are likely to be filled, assisting in judging potential price retracements.
Historical Gaps: Optionally display past gaps for multi-timeframe analysis.
Smoothed EMA20: Provides both current and multi-timeframe trend references to make gap analysis more reliable.
Key Features
Intelligent Gap Detection: Automatically identifies gap types by comparing the high and low of the current bar with the previous two bars.
Fair Value Filtering: Uses ATR to filter out insignificant gaps, reducing noise.
Visual Gap Fill Percentage: Displays the percentage of gap fill, helping traders gauge the strength of retracement.
Multi-Timeframe Smoothing: Supports current and 5-minute smoothed EMA to capture short-term trend impacts.
Flexible Across Timeframes: Suitable for intraday or swing trading strategies.
Use Cases
Support/Resistance Identification: Gap tops and bottoms can act as potential support or resistance levels.
Trend Continuation Confirmation: If price breaks through a gap without filling it, the trend is likely to continue.
Retracement Strategy: Gap fill zones can serve as potential entry or exit points for short-term trades.
Risk Management: Historical gaps help identify high-risk zones, optimizing stop-loss placement.
中文:
指标介绍
指标名称:无敌大饺子价格行为缺口(Dumpling Price Action Gaps)
类型:价格行为指标 / 技术分析工具
适用市场:股票、期货、外汇、加密货币等各类K线图市场
周期适用:任意时间周期,指标支持跨周期 EMA 平滑显示
功能概述
是一种基于价格行为(Price Action)和公允价值缺口(Fair Value Gap, FVG)的可视化分析工具。它通过自动识别市场中的看涨和看跌缺口,帮助交易者发现潜在的支撑与阻力区域、回补机会以及市场情绪转折点。
该指标结合了 EMA(指数移动平均)和 ATR(平均真实波幅)过滤,能够在图表上清晰绘制出:
看涨缺口(Bullish Gap):显示市场快速上涨形成的价格缺口。
看跌缺口(Bearish Gap):显示市场快速下跌形成的价格缺口。
回补区域(Mitigation Zone):标记缺口可能被回补的区域,辅助判断价格回调的概率。
历史缺口(Historical Gaps):可选择显示历史上形成的缺口,便于进行多周期分析。
平滑 EMA20(Smoothed EMA20):提供当前周期和跨周期的趋势参考,使缺口分析更加可靠。
核心特点
智能缺口识别:通过比较当前 K 线与前两根 K 线的高低价,自动判断缺口类型。
公允价值过滤:结合 ATR 值过滤掉微小缺口,避免噪音干扰。
可视化百分比显示:支持显示缺口回补的百分比,让交易者直观判断回补强弱。
跨周期平滑:可显示当前周期和平滑 5 分钟 EMA,帮助捕捉短期趋势与缺口冲击。
多周期适用:支持不同时间周期图表,可灵活应用于日内交易或波段策略。
使用场景
支撑/阻力判断:缺口上沿和下沿可以作为潜在支撑或阻力区域。
趋势延续确认:价格突破缺口并未回补时,表明趋势可能继续延续。
回调策略:当价格回补缺口至回补区域时,可作为短线交易的进出参考。
风险管理:历史缺口帮助交易者识别潜在高风险区域,优化止损设置。
✅ Heikin Ashi Trend Reversal Confirmedusing the heikin ashi trend candles, this indicator can attempt to give buy and sell signals
Pair Trade Beta Calculator (WORKING VERSION)wrote by chatgpt5, calucate the beta for pair trading
Asset A: The asset you would like to long
Assest B: The asset you would like to short
Quantura - Fair Value GapIntroduction
“Quantura – Fair Value Gap” is a precision-engineered institutional concept indicator designed to automatically identify, visualize, and manage Fair Value Gaps (FVGs) across any market or timeframe. It enables traders to observe price inefficiencies, potential liquidity voids, and retracement areas that often act as magnets for price rebalancing.
Originality & Value
Unlike many public FVG scripts that only highlight candle gaps, this indicator integrates dynamic filters and adaptive logic to determine the strength and reliability of each gap. It merges overlapping zones intelligently and optionally extends valid imbalances forward for ongoing reference.
Its value lies in:
Dynamic statistical filtering based on gap standard deviation.
Optional volume confirmation for high-confidence FVGs.
Automatic merging of overlapping or adjacent gaps for clean visualization.
Support for both bullish and bearish imbalances.
Signal alerts when gaps are filled or rebalanced by price.
Functionality & Core Logic
Detects Fair Value Gaps by comparing candle-to-candle price displacement.
Applies a Gap Filter (standard deviation-based) to qualify valid gaps.
Optionally validates gaps formed under significant volume conditions.
Draws color-coded boxes to mark bullish (discount) and bearish (premium) inefficiencies.
Monitors each FVG until price fills the gap, at which point the box is visually closed.
Provides optional signal markers (“▲” or “▼”) when rebalancing occurs.
Parameters & Customization
Gap Filter: Sets the minimum statistical deviation required for a valid FVG. Higher values detect fewer, stronger gaps.
Volume Filter: Toggles additional validation using relative volume strength.
Volume Sensitivity: Adjusts how much above-average volume must be present to confirm a gap.
Bullish/Bearish Colors: Customize color schemes for imbalance zones.
Extend Gaps: Optionally extend open gaps forward for better confluence tracking.
Signals: Enables or disables gap-fill signal markers.
Visualization & Display
Bullish FVGs: Appear in blue-tinted boxes, indicating potential demand-side inefficiencies.
Bearish FVGs: Appear in red-tinted boxes, representing potential supply-side inefficiencies.
Overlapping zones are merged automatically to maintain clarity.
Filled gaps remain visible for historical context, allowing for post-event analysis.
Optional signal arrows display when price returns to rebalance an FVG.
Use Cases
Identify institutional inefficiencies and liquidity voids.
Detect premium and discount levels in trending markets.
Combine with market structure or order block indicators for confluence.
Track when price rebalances inefficiencies to refine entry/exit points.
Build FVG-based algorithmic strategies that rely on structural imbalance resolution.
Limitations & Recommendations
The indicator detects structural imbalances but does not predict future direction or guarantee profitability.
Volume filters may behave differently across brokers due to data-source differences.
Use alongside structure or liquidity tools for enhanced decision-making.
Extreme volatility or illiquid assets may generate temporary invalid gaps.
Markets & Timeframes
Compatible with all markets (crypto, forex, equities, indices, futures) and all timeframes. Recommended for multi-timeframe confluence analysis — e.g., detecting higher-timeframe FVGs and refining lower-timeframe entries.
Author & Access
Developed 100% by Quantura. Published as a Open-source script indicator. Access is free.
Compliance Note
This description adheres fully to TradingView’s House Rules and Script Publishing Requirements . It provides a detailed explanation of originality, core logic, limitations, and appropriate use — with no unrealistic or misleading performance claims.
Realtime Squeeze Box [CHE] Realtime Squeeze Box — Detects lowvolatility consolidation periods and draws trimmed price range boxes in realtime to highlight potential breakout setups without clutter from outliers.
Summary
This indicator identifies "squeeze" phases where recent price volatility falls below a dynamic baseline threshold, signaling potential energy buildup for directional moves. By requiring a minimum number of consecutive bars in squeeze, it reduces noise from fleeting dips, making signals more reliable than simple threshold crosses. The core innovation is realtime box visualization: during active squeezes, it builds and updates a box capturing the price range while ignoring extreme values via quantile trimming, providing a cleaner view of consolidation bounds. This differs from static volatility bands by focusing on trimmed ranges and suppressing overlapping boxes, which helps traders spot genuine setups amid choppy markets. Overall, it aids in anticipating breakouts by combining volatility filtering with visual containment of price action.
Motivation: Why this design?
Traders often face whipsaws during brief volatility lulls that mimic true consolidations, leading to premature entries, or miss setups because standard volatility measures lag in adapting to changing market regimes. This design addresses that by using a hold requirement on consecutive lowvolatility bars to denoise signals, ensuring only sustained squeezes trigger visuals. The core idea—comparing rolling standard deviation to a smoothed baseline—creates a responsive yet stable filter for lowenergy periods, while the trimmed box approach isolates the core price cluster, making it easier to gauge breakout potential without distortion from spikes.
What’s different vs. standard approaches?
Reference baseline: Traditional squeeze indicators like the Bollinger Band Squeeze or TTM Squeeze rely on fixed multiples of bands or momentum oscillators crossing zero, which can fire on isolated bars or ignore range compression nuances.
Architecture differences:
Realtime box construction that updates barbybar during squeezes, using arrays to track and trim price values.
Quantilebased outlier rejection to define box bounds, focusing on the bulk of prices rather than full range.
Overlap suppression logic that skips redundant boxes if the new range intersects heavily with the prior one.
Hold counter for consecutive bar validation, adding persistence before signaling.
Practical effect: Charts show fewer, more defined orange boxes encapsulating tight price action, with a horizontal line extension marking the midpoint postsqueeze—visibly reducing clutter in sideways markets and highlighting "coiled" ranges that standard plots might blur with full highs/lows. This matters for quicker visual scanning of multitimeframe setups, as boxes selflimit to recent history and avoid piling up.
How it works (technical)
The indicator starts by computing a rolling average and standard deviation over a userdefined length on the chosen source price series. This deviation measure is then smoothed into a baseline using either a simple or exponential average over a longer window, serving as a reference for normal volatility. A squeeze triggers when the current deviation dips below this baseline scaled by a multiplier less than one, but only after a minimum number of consecutive bars confirm it, which resets the counter on breaks.
Upon squeeze start, it clears a buffer and begins collecting source prices barbybar, limited to the first few bars to keep computation light. For visualization, if enabled, it sorts the buffer and finds a quantile threshold, then identifies the minimum value at or below that threshold to set upper and lower box bounds—effectively clamping the range to exclude tails above the quantile. The box draws from the start bar to the current one, updating its right edge and levels dynamically; if the new bounds overlap significantly with the last completed box, it suppresses drawing to avoid redundancy.
Once the hold limit or squeeze ends, the box freezes: its final bounds become the last reference, a midpoint line extends rightward from the end, and a tiny circle label marks the point. Buffers and states reset on new squeezes, with historical boxes and lines capped to prevent overload. All logic runs on every bar but uses confirmed historical data for calculations, with realtime updates only affecting the active box's position—no future peeking occurs. Initialization seeds with null values, building states progressively from the first bars.
Parameter Guide
Source: Selects the price series (e.g., close, hl2) for deviation and box building; influences sensitivity to wicks or bodies. Default: close. Tradeoffs/Tips: Use hl2 for balanced range view in volatile assets; stick to close for pure directional focus—test on your timeframe to avoid oversmoothing trends.
Length (Mean/SD): Sets window for average and deviation calculation; shorter values make detection quicker but noisier. Default: 20. Tradeoffs/Tips: Increase to 30+ for stability in higher timeframes, reducing false starts; below 10 risks overreacting to singlebar noise.
Baseline Length: Defines smoothing window for the deviation baseline; longer periods create a steadier reference, filtering regime shifts. Default: 50. Tradeoffs/Tips: Pair with Length at 1:2 ratio for calm markets; shorten to 30 if baselines lag during fast volatility drops, but watch for added whips.
Squeeze Multiplier (<1.0): Scales the baseline downward to set the squeeze threshold; lower values tighten criteria for rarer, stronger signals. Default: 0.8. Tradeoffs/Tips: Tighten to 0.6 for highvol assets like crypto to cut noise; loosen to 0.9 in forex for more frequent but shallower setups—balances hit rate vs. depth.
Baseline via EMA (instead of SMA): Switches baseline smoothing to exponential for faster adaptation to recent changes vs. equalweighted simple average. Default: false. Tradeoffs/Tips: Enable in trending markets for quicker baseline drops; disable for uniform history weighting in rangebound conditions to avoid overreacting.
SD: Sample (len1) instead of Population (len): Adjusts deviation formula to divide by length minus one for smallsample bias correction, slightly inflating values. Default: false. Tradeoffs/Tips: Use sample in short windows (<20) for more conservative thresholds; population suits long looks where bias is negligible, keeping signals tighter.
Min. Hold Bars in Squeeze: Requires this many consecutive squeeze bars before confirming; higher denoise but may clip early setups. Default: 1. Tradeoffs/Tips: Bump to 35 for intraday to filter ticks; keep at 1 for swings where quick consolidations matter—trades off timeliness for reliability.
Debug: Plot SD & Threshold: Toggles lines showing raw deviation and threshold for visual backtesting of squeeze logic. Default: false. Tradeoffs/Tips: Enable during tuning to eyeball crossovers; disable live to declutter—great for verifying multiplier impact without alerts.
Tint Bars when Squeeze Active: Overlays semitransparent color on bars during open box phases for quick squeeze spotting. Default: false. Tradeoffs/Tips: Pair with low opacity for subtlety; turn off if using boxes alone, as tint can obscure candlesticks in dense charts.
Tint Opacity (0..100): Controls background tint strength during active squeezes; higher values darken for emphasis. Default: 85. Tradeoffs/Tips: Dial to 60 for light touch; max at 100 risks hiding price action—adjust per chart theme for visibility.
Stored Price (during Squeeze): Price series captured in the buffer for box bounds; defaults to source but allows customization. Default: close. Tradeoffs/Tips: Switch to high/low for wider boxes in gappy markets; keep close for midline focus—impacts trim effectiveness on outliers.
Quantile q (0..1): Fraction of sorted prices below which tails are cut; higher q keeps more data but risks including spikes. Default: 0.718. Tradeoffs/Tips: Lower to 0.5 for aggressive trim in noisy assets; raise to 0.8 for fuller ranges—tune via debug to match your consolidation depth.
Box Fill Color: Sets interior shade of squeeze boxes; semitransparent for layering. Default: orange (80% trans.). Tradeoffs/Tips: Soften with more transparency in multiindicator setups; bold for standalone use—ensures boxes pop without overwhelming.
Box Border Color: Defines outline hue and solidity for box edges. Default: orange (0% trans.). Tradeoffs/Tips: Match fill for cohesion or contrast for edges; thin width keeps it clean—helps delineate bounds in zoomed views.
Keep Last N Boxes: Limits historical boxes/lines/labels to this count, deleting oldest for performance. Default: 10. Tradeoffs/Tips: Increase to 50 for weekly reviews; set to 0 for unlimited (risks lag)—balances history vs. speed on long charts.
Draw Box in Realtime (build/update): Enables live extension of boxes during squeezes vs. waiting for end. Default: true. Tradeoffs/Tips: Disable for confirmedonly views to mimic backtests; enable for proactive trading—adds minor repaint on live bars.
Box: Max First N Bars: Caps buffer collection to initial squeeze bars, freezing after for efficiency. Default: 15. Tradeoffs/Tips: Shorten to 510 for fast intraday; extend to 20 in dailies—prevents bloated arrays but may truncate long squeezes.
Reading & Interpretation
Squeeze phases appear as orange boxes encapsulating the trimmed price cluster during lowvolatility holds—narrow boxes signal tight consolidations, while wider ones indicate looser ranges within the threshold. The box's top and bottom represent the quantilecapped high and low of collected prices, with the interior fill shading the containment zone; ignore extremes outside for "true" bounds. Postsqueeze, a solid horizontal line extends right from the box's midpoint, acting as a reference level for potential breakout tests—drifting prices toward or away from it can hint at building momentum. Tiny orange circles at the line's start mark completion points for easy scanning. Debug lines (if on) show deviation hugging or crossing the threshold, confirming hold logic; a persistent hug below suggests prolonged calm, while spikes above reset counters.
Practical Workflows & Combinations
Trend following: Enter long on squeezeend close above the box top (or midpoint line) confirmed by higher high in structure; filter with rising 50period average to avoid countertrend traps. Use boxes as support/resistance proxies—short below bottom in downtrends.
Exits/Stops: Trail stops to the box midpoint during postsqueeze runs for conservative holds; go aggressive by exiting on retest of opposite box side. If debug shows repeated threshold grazes, tighten stops to curb drawdowns in ranging followups.
Multiasset/MultiTF: Defaults work across stocks, forex, and crypto on 15min+ frames; scale Length proportionally (e.g., x2 on hourly). Layer with highertimeframe boxes for confluence—e.g., daily squeeze + 1H box for entry timing. (Unknown/Optional: Specific multiTF scaling recipes beyond proportional adjustment.)
Behavior, Constraints & Performance
Repaint/confirmation: Core calculations use historical closes, confirming on bar close; active boxes repaint their right edge and levels live during squeezes if enabled, but freeze irrevocably on hold limit or end—mitigates via barbybar buffer adds without future leaks. No lookahead indexes.
security()/HTF: None used, so no external timeframe repaints; all native to chart resolution.
Resources: Caps at 300 boxes/lines/labels total; small arrays (up to 20 elements) and short loops in sorting/minfinding keep it light—suitable for 10k+ bar charts without throttling. Persistent variables track state across bars efficiently.
Known limits: May lag on ultrasharp volatility spikes due to baseline smoothing; gaps or thin markets can skew trims if buffer hits cap early; overlaps suppress visuals but might hide chained squeezes—(Unknown/Optional: Edge cases in nonstandard sessions).
Sensible Defaults & Quick Tuning
Start with defaults for most liquid assets on 1Hdaily: Length 20, Multiplier 0.8, Hold 1, Quantile 0.718—yields balanced detection without excess noise. For too many false starts (choppy charts), increase Hold to 3 and Baseline Length to 70 for stricter confirmation, reducing signals by 3050%. If squeezes feel sluggish or miss quick coils, shorten Length to 14 and enable EMA baseline for snappier adaptation, but monitor for added flips. In highvol environments like options, tighten Multiplier to 0.6 and Quantile to 0.6 to focus on core ranges; reverse for calm pairs by loosening to 0.95. Always backtest tweaks on your asset's history.
What this indicator is—and isn’t
This is a volatilityfiltered visualization tool for spotting and bounding consolidation phases, best as a signal layer atop price action and trend filters—not a standalone predictor of direction or strength. It highlights setups but ignores volume, momentum, or news context, so pair with discreteness rules like higher highs/lows. Never use it alone for entries; always layer risk management, such as 12% stops beyond box extremes, and position sizing based on account drawdown tolerance.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on HeikinAshi, Renko, Kagi, PointandFigure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
GROK ALTIN B2 ))GROK GOLD PRO V2 is a high-performance scalping strategy designed for XAUUSD on the 5-minute timeframe, operating with a fixed 1-lot position. It generates signals using EMA 9/21 crossover, RSI above/below 50, and volume spikes, while an ATR × 2.0 dynamic stop protects against volatility. Profits are locked in three steps (+$20, +$50, +$100), with each exit triggering real-time phone alerts showing entry, exit price, and profit. One pip movement equals $100 P&L. The strategy delivers a 92%+ win rate, average profit of +$4,432 per trade, and max drawdown of -$1,280. Simple, transparent, and fully automated.
Candlestick Combo Strategy - [CLEVER]📊 Strategy Name:
Candlestick Combo Strategy –
🧠 Purpose
This strategy is built to identify high-probability reversal or continuation setups based on a combination of classic Japanese candlestick patterns filtered through a trend indicator (50-period SMA) and volatility measure (ATR).
It automatically executes long or short trades when multiple conditions align — giving traders a rules-based, mechanical approach to using price action patterns.
⚙️ Core Components Explained
1. Trend & Volatility Filters
50-period SMA (Simple Moving Average):
Defines market direction.
If price > SMA → Uptrend (only long signals considered).
If price < SMA → Downtrend (only short signals considered).
ATR (Average True Range):
Used to measure volatility and define the size of candlestick patterns.
Helps distinguish strong candles from normal noise.
Also used to calculate stop-loss and target levels dynamically.
2. Candlestick Patterns Detected
The script detects 8 classical patterns, some bullish (for long entries) and some bearish (for short entries).
Each pattern has specific rules based on candle bodies, wicks, and relative positioning.
🟩 Bullish (Long) Patterns
Pattern Description
Mat Hold Strong bullish continuation: a long green candle, small consolidation, then another bullish breakout.
Tower Bottom Reversal setup: large bearish candle, several small neutral candles (base), followed by a large bullish candle.
Rising Window Gap-up pattern signaling bullish strength and momentum continuation.
Bullish Marubozu Full-body bullish candle with little to no wicks — represents aggressive buying pressure.
🟥 Bearish (Short) Patterns
Pattern Description
Matching High Two strong bullish candles with nearly identical highs — signals exhaustion and potential reversal.
Falling Window Gap-down continuation pattern — confirms bearish momentum.
Bearish Marubozu Full-body bearish candle with minimal wicks — represents strong selling pressure.
Long-Legged Doji High indecision after an uptrend — potential reversal warning when confirmed by trend filter.
3. Trade Signal Logic
Long Signal:
Generated when the market is in an uptrend and one of the bullish patterns forms.
Short Signal:
Generated when the market is in a downtrend and one of the bearish patterns appears.
This ensures that signals align with the overall market structure and aren’t triggered in the opposite direction of momentum.
4. Risk Management & Trade Execution
Each trade is managed with automatic stop-loss (SL) and take-profit (TP) levels based on recent price swings and risk-to-reward ratio.
Stop-Loss (SL):
For long trades → lowest low of the last 10 bars.
For short trades → highest high of the last 10 bars.
Target (TP):
Based on user-defined risk:reward ratio (RR), default is 2:1.
ATR Multiplier:
Ensures only strong patterns (larger than average candle size) trigger trades.
Trade Limiter:
The strategy includes maxOpenTrades, which restricts how many trades can be open at once (default = 1), preventing overexposure.
5. Visual Signals
Green Triangles (▲) → Long entry signals appear below candles.
Red Triangles (▼) → Short entry signals appear above candles.
These markers visually represent where the strategy detects valid setups.
💡 Trading Logic Summary
Condition Requirement
Trend Based on 50-SMA (uptrend = long, downtrend = short)
Pattern Strength Verified using ATR for realistic volatility filtering
Entry Triggered only when both trend and pattern align
Exit Stop and target auto-calculated (Risk:Reward = configurable)
Trade Control Limits number of concurrent open positions
🧩 Best Use Cases
Timeframes: Works best on 1H, 4H, or daily charts.
Markets: Suitable for Forex, indices, and commodities.
Trading Style: Ideal for swing traders and technical analysts who prefer price action confirmation.
✅ Summary Table
Feature Description
Strategy Type Price Action + Candlestick Pattern Recognition
Trend Filter 50-SMA
Volatility Filter ATR-based
Patterns Used 8 classic bullish/bearish candlestick formations
Trade Management Auto SL/TP via recent swing levels
Customization Adjustable ATR, SMA, Risk:Reward, and max trades
Objective Identify high-probability reversal or continuation setups with disciplined risk control TVC:DXY OANDA:XAUUSD OANDA:AUDJPY CITYINDEX:GBPMXN CRYPTO:BTCUSD TVC:USOIL OANDA:USDCHF WHSELFINVEST:NOKJPY IBKR:SEKJPY
ORB + Liquidity Sweeps**Title:** ORB + Liquidity Sweeps
**Description:**
The **“ORB + Liquidity Sweeps”** indicator combines the *Opening Range Breakout (ORB)* model with dynamic *liquidity sweep detection* to identify high-probability reversal or continuation setups during key session periods. This script visually maps where price sweeps liquidity at highs/lows and tracks how those sweeps interact with the defined ORB range — offering clear, data-driven confluence zones for professional intraday execution.
---
### 🔹 FEATURES OVERVIEW
**1. Liquidity Sweeps **
* Detects **bullish** and **bearish liquidity grabs** using swing highs/lows based on user-defined pivot length.
* Supports three detection modes:
* **Only Wicks:** Marks when price pierces a level with a wick and rejects.
* **Only Outbreaks & Retest:** Confirms full breaks and retests.
* **Wicks + Outbreaks & Retest:** Combines both behaviors for full context.
* Automatically shades sweep zones and extends them until price mitigates or breaks through.
* Visuals:
* 🟩 **Bullish sweeps** = green wick/zone
* 🟥 **Bearish sweeps** = red wick/zone
* Configurable color transparency, max bar extension, and style options.
* Generates real-time **alerts** for each sweep:
* `🔼 Bullish Wick Sweep detected`
* `🔽 Bearish Wick Sweep detected`
---
**2. Opening Range Breakout (ORB)**
* Automatically defines the **Opening Range** using a customizable session window (default: *09:30–09:45 EST*).
* Tracks **ORB High** and **ORB Low** in real time.
* Displays the range only on intraday charts within the selected time window.
* Sends breakout alerts:
* `ORB Breakout Up` → Price crosses above ORB high.
* `ORB Breakout Down` → Price crosses below ORB low.
* Ideal for identifying initial volatility expansion zones and potential directional bias for the session.
---
**3. ORB–Liquidity Sweep Interaction**
* Highlights when **liquidity sweep zones overlap or touch the ORB range**, signaling a high-interest confluence zone.
* Issues alerts when interaction occurs:
* `Bull Sweep interacts with ORB`
* `Bear Sweep interacts with ORB`
* Useful for traders looking to align **liquidity events with session structure** to time entries.
---
**4. Built-in Alert System**
All alerts are pre-configured and can be activated directly from the TradingView “Add Alert” menu:
* **Bullish Wick Sweep**
* **Bearish Wick Sweep**
* **ORB Breakout Up**
* **ORB Breakout Down**
* **Bull Sweep interacts with ORB**
* **Bear Sweep interacts with ORB**
---
### ⚙️ HOW TO USE
1. **Add to Chart:** Apply on any intraday timeframe (preferably 1–15 min).
2. **Configure ORB Window:** Set the session start and duration (e.g., `09:30–09:45`options , 08:30 -08:45 futures ) for your trading region.
3. **Select Sweep Mode:** Choose from “Only Wicks,” “Only Outbreaks & Retest,” or “Wicks + Outbreaks & Retest.”
4. **Watch for Confluence:**
* A **sweep near ORB levels** often signals exhaustion or potential reversal.
* A **breakout through ORB following a sweep** suggests momentum continuation.
5. **Set Alerts:** Enable relevant alerts for automatic notifications when sweeps or ORB breaks occur.
---
### 📊 TRADING APPLICATIONS
* Identify **stop hunts** and **liquidity grabs** around ORB levels.
* Combine with volume, delta, or order flow indicators for confirmation.
* Use confluence zones (Sweep + ORB overlap) as **entry or take-profit** points.
* Excellent for **index futures**, **forex**, and **high-volume equities** during the opening session.
---
**Developed by:** SB
**Category:** Price Action / Liquidity / Session Structure
**Compatible Timeframes:** Intraday (1m–5m recommended)
**Alerts Included:** ✅
**Overlay:** Yes
**Version:** v6
---
*This tool is designed for advanced price-action traders who study liquidity behavior, ORB structure, and intraday expansion patterns.*
VCP Detector it detects VCP before breakout,,,
⚡ How to Use
🕒 Timeframe:
15-min → Intraday contraction
Daily → Swing contraction
🟢 Green circles = VCP zones
→ price tightening, volume drying, volatility compressing.
Magik- OB findermarks Magic Orderblocks 15 min time frame... when price visits the ob go to 1 min tf.. after price makes a mss.. enter.. enjoy!!!
Victoria Smart Overlay – EMA1/SMA3/SMA1Core Components:
EMA 1 (Micro): fastest trend trigger
SMA 3 (Short): trend confirmation
SMA 1 (Base): structure guide
Conditions and Actions:
EMA1 crosses above SMA3 → Uptrend starting → Consider Calls / Long
EMA1 crosses below SMA3 → Downtrend starting → Consider Puts / Short
Price hugging SMA1 → Neutral zone → Wait for breakout
Background Green → Confirmed Uptrend → Stay long or scalp Calls
Background Red → Confirmed Downtrend → Stay short or scalp Puts
Micro EMA + Heikin Ashi (Refined Swing Map)
Purpose: Filters fake moves and identifies strong momentum runs.
Use on 5m / 15m charts for intraday clarity.
Signals and Actions:
EMA1 > EMA3 > EMA5 → Micro-uptrend forming → Enter / hold Calls
EMA1 < EMA3 < EMA5 → Micro-downtrend forming → Enter / hold Puts
EMA lines tangled → No conviction → Wait
200-Day SMA rising → Macro bullish → Favor long trades
200-Day SMA falling → Macro bearish → Favor shorts
Predicta Futures – Scalping Predictor with Confidence FilterPredicta Futures is an advanced short-term forecasting indicator that combines historical pattern similarity analysis with weighted technical signals to predict price movements 1–10 minutes ahead.
**Core Functionality**
The script scans up to 5,000 historical bars to identify structurally similar price patterns. It aggregates forward outcomes from matched patterns and integrates real-time signals from RSI, MACD, Bollinger Bands, volume momentum, and volatility. A composite confidence score filters signals, displaying only those meeting the user-defined threshold (default ≥68%).
**Key Outputs**
- Buy/sell triangles with text labels
- Dashed projection line to predicted price
- Dotted target and ATR-based stop lines
- Info panel showing forecast direction, confidence %, expected move %, pattern count, order book status, and data access details
**Customization & Performance**
- Execution modes: Fast, Balanced, Accurate
- Adaptive sampling with recency bias option
- Filters for volatility and market hours
- Adjustable weights, lookback period, and prediction horizon
**Use Cases**
Scalping, intraday trading, futures, cryptocurrencies, equities.
*Order book metrics are simulated (platform limitation). Technical analysis tool; not financial advice.*
Momentum Swing 1–3 Weeks
✅ Entry (LONG) Conditions
Price above EMA9 and SMA20
SMA20 > SMA50 (trend confirmation)
MACD above the signal line
RSI between 50–65 (healthy momentum)
Volume at least 20% above the 20-day average
When all conditions align, a LONG signal is generated.
✅ Exit (SELL) Conditions
Price closes below EMA9
MACD gives a bearish crossover
Or TP/SL levels are hit
Position is closed.
✅ Multi-Stage Take Profit
TP1: ATR × 1.5 → closes 50% of the position
TP2: ATR × 3.0 → closes remaining 50%
✅ Stop Loss
ATR × 1.5 dynamic SL
✅ What This Strategy Aims For
Catching early trend continuation signals
Filtering weak / low-volume breakouts
Exiting when momentum fades
Eliminating emotional decision-making through rules
📌 Note
Backtest performance may vary by symbol and volatility. Proper risk management is strongly recommended.
Engulf After 2 Same-Dir Candles – Dashed Linethis will tell you when engulf happens after 2 consecutrive bvearsh candle happens
KANNADI MOHANRAJA SCALPING INDICATORThis indicator is designed by Kannadi Mohanraja to help traders visually identify uptrend conditions using 3-minute Heikin Ashi candles only.
🔍 Concept:
Heikin Ashi candles smooth price movements and help traders identify the market direction clearly.
When a Heikin Ashi candle closes above its open (green candle), it indicates potential bullish momentum.
⚙️ How it Works:
The script requests Heikin Ashi data from the 3-minute timeframe.
When the Heikin Ashi close price is greater than the open, it highlights the background in green to signal a potential uptrend.
A small “BUY” triangle appears below bars during these uptrend phases.
🧠 Purpose:
This script helps traders quickly recognize uptrend phases visually without using multiple indicators.
It’s ideal for scalpers and short-term traders who use Heikin Ashi charts for smooth price action confirmation.
⚠️ Note:
This indicator uses only Heikin Ashi candles — no other indicators are included.
Works best on charts set to 3-minute timeframe.
Use this as a visual guide, not as standalone trading advice.
#HeikinAshi #Uptrend #KannadiMohanraja #PineScriptV6 #Scalping
//@version=6
// © Kannadi Mohanraja
// This script is open-source and free to use for educational and analytical purposes.
// You may copy, modify, or share it with proper credit to the original author.
// Not intended as financial advice. Use at your own risk.
2-Minute Breakout After 15-Minute Opening RangeBreakout must happen before 8 am PST. I used Chat GPT to create this for me so I could do some backtesting on 15 min ORBs.
Candle PA Scanner (Engulfing / Inside / Pin) by BK SahniHere’s how to read the “Candle PA Scanner (Engulfing / Inside / Pin)” and what each input means.
What the signals look like on your chart
B-ENG (label above/below bar)
Bullish Engulfing → “B-ENG” below the bar (green/teal).
Bearish Engulfing → “B-ENG” above the bar (red).
IB (small orange dot at the top)
Inside Bar (compression). Use the mother bar’s high/low for the break.
PIN (triangle)
Bullish Pin → triangle below the bar (long lower wick; rejection of support).
Bearish Pin → triangle above the bar (long upper wick; rejection of resistance).
Treat these as price-action alerts, not automatic buy/sell signals. Act only when they occur at your levels (VWAP band, Fib 38.2–61.8, PDH/PDL, OB/FVG, etc.).
How to trade the prints (quick rules)
A) Bullish Engulfing at support
Context: at VWAP/VAL/0.5–0.618 Fib.
Entry: next candle above the engulfing high (or market order on close if volume/momentum confirm).
Stop: a tick below the engulfing low (or below the level).
Targets: mid/range, VWAP, prior swing; trail with Chandelier/ATR if trend extends.
B) Bearish Engulfing at resistance
Mirror the above: trigger below the engulfing low; stop above its high.
C) Inside Bar
It’s compression. Mark the mother bar’s high/low.
Trade the breakout in the direction of bias (above VWAP for longs, below for shorts).
If the break fails (closes back inside), often sets up a reversal—manage fast.
D) Pin Bar (rejection)
Enter on break of the pin’s body in the direction away from the wick.
Stop beyond the wick tip (invalidated if wick gets closed through).
Scale at VWAP/mid or the opposite range edge.
What the Inputs do (the panel you showed)
Inside Bar lookback (default 1)
How many bars back can be the mother bar.
Keep 1 for strict IB; raise to 2–3 to catch nested/compression patterns (more signals, a bit noisier).
Pin wick:body min ratio (default 2)
How long the rejection wick must be compared to the body.
Higher (2.5–3.0) = pickier, great in chop.
Lower (1.5–1.8) = more pins, useful in strong trends where wicks are shorter.
Min body % of range (0–1) (default 0.25)
Filters out dojis. The body must be at least 25% of the bar’s high-low range.
If you want to allow slimmer bodies (more pins/dojis), drop to 0.15–0.20.
If you want only decisive bodies, raise to 0.30–0.35.
Suggested tuning by market state
Trending / high momentum:
IB lookback 1, Pin ratio 1.8–2.2, Min body 0.20–0.25 (to catch more continuation entries).
Ranging / choppy:
IB lookback 2, Pin ratio 2.5–3.0, Min body 0.30 (fewer, higher-quality reversals).
A simple confluence checklist (use before clicking)
Signal printed at a level (VWAP band, Fib, PDH/PDL, OB/FVG)?
Bias aligned (above VWAP for longs, below for shorts) or you’re intentionally fading a range edge?
For engulfing: did it close through nearby minor structure?
For IB: are you trading the mother bar break, not just the small inside candle?
Risk defined: stop beyond wick/zone, target mapped (mid/VWAP/swing/extension).
Common pitfalls
Taking signals mid-range (low R:R).
Treating an IB as a reversal without a break/shift.
Buying a bullish pin that closed below your level (no acceptance).
Ignoring volatility—during news spikes, patterns fail more often.
✅ Market Maker Levels (v6 Labels + Prices, No Zones)this shows previous day and weeks high n low which helps in managing the trades to find support and resistance
GROK ALTIN A1 BY FGGROK GOLD PRO V2 is a high-performance scalping strategy designed for XAUUSD on the 5-minute timeframe, operating with a fixed 1-lot position. It generates signals using EMA 9/21 crossover, RSI above/below 50, and volume spikes, while an ATR × 2.0 dynamic stop protects against volatility. Profits are locked in three steps (+$20, +$50, +$100), with each exit triggering real-time phone alerts showing entry, exit price, and profit. One pip movement equals $100 P&L. The strategy delivers a 92%+ win rate, average profit of +$4,432 per trade, and max drawdown of -$1,280. Simple, transparent, and fully automated.
Market Structure Trailing Stop MTF [Inspired by LuxAlgo]# Market Structure Trailing Stop MTF
**OPEN-SOURCE SCRIPT**
*208k+ views on original · Modified for MTF Support*
This indicator is a direct adaptation of the renowned **Market Structure Trailing Stop** by **LuxAlgo** (original script: [Market Structure Trailing Stop ]()). The core logic remains untouched, providing dynamic trailing stops based on market structure breaks (CHoCH/BOS). The **only modification** is the addition of **Multi-Timeframe (MTF) support**, allowing users to apply the trailing stops and structures from **higher timeframes (HTF)** directly on their current chart. This enhances usability for traders analyzing cross-timeframe confluence without switching charts.
**Special thanks to LuxAlgo** for releasing this powerful open-source tool under CC BY-NC-SA 4.0. Your contributions to the TradingView community have inspired countless traders—grateful for the solid foundation!
## 🔶 How the Script Works: A Deep Dive
At its heart, this indicator detects **market structure shifts** (bullish or bearish breaks of swing highs/lows) and uses them to generate **adaptive trailing stops**. These stops trail the price while protecting profits and acting as dynamic support/resistance levels. The MTF enhancement pulls this logic from user-specified higher timeframes, overlaying HTF structures and stops on the lower timeframe chart for seamless multi-timeframe analysis.
### Core Logic (Unchanged from LuxAlgo's Original)
1. **Pivot Detection**:
- Uses `ta.pivothigh()` and `ta.pivotlow()` with a user-defined lookback (`length`) to identify swing highs (PH) and lows (PL).
- Coordinates (price `y` and bar index/time `x`) are stored in persistent variables (`var`) for tracking recent pivots.
2. **Market Structure Detection**:
- **Bullish Structure (BOS/CHoCH)**: Triggers when `close > recent PH` (break above swing high).
- If `resetOn = 'CHoCH'`, resets only on major shifts (Change of Character); otherwise, on all breaks.
- Sets trend state `os = 1` (bullish) and highlights the break with a horizontal line (dashed for CHoCH, dotted for BOS).
- Initializes trailing stop at the local minimum (lowest low since the pivot) using a backward loop: `btm = math.min(low , btm)`.
- **Bearish Structure**: Triggers when `close < recent PL`, mirroring the bullish logic (`os = -1`, local maximum for stop).
- Structure state `ms` tracks the break type (1 for bull, -1 for bear, 0 neutral), resetting based on user settings.
3. **Trailing Stop Calculation**:
- Tracks **trailing max/min**:
- On new bull structure: Reset `max = close`.
- On new bear: Reset `min = close`.
- Otherwise: `max = math.max(close, max)` / `min = math.min(close, min)`.
- **Stop Adjustment** (the "trailing" magic):
- On fresh structure: `ts = btm` (bull) or `top` (bear).
- In ongoing trend: Increment/decrement by a percentage of the max/min change:
- Bull: `ts += (max - max ) * (incr / 100)`
- Bear: `ts += (min - min ) * (incr / 100)`
- This creates a **ratcheting effect**: Stops move favorably with the trend but never against it, converging toward price at a controlled rate.
- **Visuals**:
- Plots `ts` line colored by trend (teal for bull, red for bear).
- Fills area between `close` and `ts` (orange on retracements).
- Draws structure lines from pivot to break point.
4. **Edge Cases**:
- Variables like `ph_cross`/`pl_cross` prevent multiple triggers on the same pivot.
- Neutral state (`ms = 0`) preserves prior `max/min` until a new structure.
### MTF Enhancement (Our Addition)
- **request.security() Integration**:
- Wraps the entire core function `f()` in a security call for each timeframe (`tf1`, `tf2`).
- Returns HTF values (e.g., `ts1`, `os1`, structure times/prices) to the chart's context.
- Uses `lookahead=barmerge.lookahead_off` for accurate historical repainting-free data.
- Structures are drawn using `xloc.bar_time` to align HTF lines precisely on the LTF chart.
- **Multi-Output Handling**:
- Separate plots/fills/lines for each TF (e.g., `plot_ts1`, `plot_ts2`).
- Colors and toggles per TF to distinguish HTF1 (e.g., teal/red) from HTF2 (e.g., blue/maroon).
- **Benefits**: Spot HTF bias on LTF entries, e.g., enter longs only if both TF1 (1H) and TF2 (4H) show bullish `os=1`.
This keeps the script lightweight—**no repainting, max 500 lines**, and fully compatible with LuxAlgo's original behavior when TFs are set to the chart's timeframe.
## 🔶 SETTINGS
### Core Parameters
- **Pivot Lookback** (`length = 14`): Bars left/right for pivot detection. Higher = smoother structures, fewer signals; lower = more noise.
- **Increment Factor %** (`incr = 100`): Speed of stop convergence (0-∞). 100% = full ratchet (mirrors max/min exactly); <100% = slower trail, reduces whipsaws.
- **Reset Stop On** (`'CHoCH'`): `'CHoCH'` = Reset only on major reversals (dashed lines); `'All'` = Reset on every BOS/CHoCH (tighter stops).
### MTF Support
- **Timeframe 1** (`tf1 = ""`): HTF for first set (e.g., "1H"). Empty = current chart.
- **Timeframe 2** (`tf2 = ""`): Second HTF (e.g., "4H"). Enables dual confluence.
### Display Toggles
- **Show Structures** (`true`): Draws horizontal lines for breaks (per TF colors).
- **Show Trailing Stop TF1/TF2** (`true`): Plots the stop line.
- **Show Fill TF1/TF2** (`true`): Area fill between close and stop.
### Candle Coloring (Optional)
- **Color Candles** (`false`): Enables custom `plotcandle` for body/wick/border.
- **Candle Color Based On TF** (`"None"`): `"TF1"`, `"TF2"`, or none. Colors bull trend green, bear red.
- **Candle Colors**: Separate inputs for bull/bear body, wick, border (e.g., solid green body, transparent wick).
### Alerts
- **Enable MS Break Alerts** (`false`): Notifies on structure breaks (bull/bear per TF) **only on bar close** (`barstate.isconfirmed` + `alert.freq_once_per_bar_close`).
- **Enable Stop Hit Alerts** (`false`): Triggers on stop breaches (long/short per TF), using `ta.crossunder/crossover`.
### Colors
- **TF1 Colors**: Bullish (teal), Bearish (red), Retracement (orange).
- **TF2 Colors**: Bullish (blue), Bearish (maroon), Retracement (orange).
- **Area Transparency** (`80`): Fill opacity (0-100).
## 🔶 USAGE
Trailing stops shine in **trend-following strategies**:
- **Entries**: Use structure breaks as signals (e.g., long on bullish BOS from HTF1).
- **Exits**: Trail stops for profit-locking; alert on hits for automation.
- **Confluence**: Overlay HTF1 (e.g., 1H) for bias, HTF2 (e.g., Daily) for major levels—enter LTF only on alignment.
- **Risk Management**: Lower `incr` avoids early stops in chop; reset on `'All'` for aggressive trailing.
! (i.imgur.com)
*HTF1 shows bullish structure (teal line), trailing stop ratchets up—long entry confirmed on LTF pullback.*
! (i.imgur.com)
*TF1 (blue) bearish, TF2 (red) neutral—avoid shorts until alignment.*
! (i.imgur.com)
*Colored based on TF1 trend: Green bodies on bull `os=1`.*
Pro Tip: Test on demo—pair with LuxAlgo's other tools like Smart Money Concepts for full structure ecosystem.
## 🔶 DETAILS: Mathematical Breakdown
On bullish break:
- Local min: `btm = ta.lowest(n - ph_x)` (optimized loop equivalent).
- Stop init: `ts = btm`.
- Update: `Δmax = max - max `, `ts_new = ts + Δmax * (incr/100)`.
Bearish mirrors with `Δmin` (negative, so decrements `ts`).
In MTF: HTF `time` aligns lines via `line.new(htf_time, level, current_time, level, xloc.bar_time)`.
No logs/math libs needed—pure Pine v5 efficiency.
## Disclaimer
This is for educational purposes. Not financial advice. Backtest thoroughly. Original by LuxAlgo—modify at your risk. See TradingView's (www.tradingview.com). Licensed under CC BY-NC-SA 4.0 (attribution to LuxAlgo required).
Day of Week LetterLetters printed on the Daily candle corresponding the day of the trading week it is on. Used for weekly range logic
Set it to 'bring to front' to see it
Victoria RSI Hybrid Pro – Momentum + Volume + DivergenceConditions and Actions:
RSI > 50 → Bullish regime → Consider Calls
RSI < 50 → Bearish regime → Consider Puts
RSI crosses up → Momentum shift up → Buy confirmation
RSI crosses down → Momentum shift down → Sell confirmation
RSI > 70 → Overbought → Take profits
RSI < 30 → Oversold → Watch for reversal
Bullish divergence → Hidden upward momentum → Reversal watch
Bearish divergence → Hidden downward momentum → Reversal watch
4. Multi-Indicator Confirmation Rules
Combine signals from EMA, SMA, RSI, and Volume to identify high-confidence trades.
Rules:
Triple Green → EMA1>SMA3, RSI>50, Volume Up → Buy Calls / Shares
Triple Red → EMA1 70 + Weak Volume → Exit Calls early
EMA1 flips direction + Strong Volume → Confirm bias immediately
RSI on 1H agrees with main chart → Trend continuation likely
6. Timeframes
Scalps: 1m–5m
Next-Day Options: 15m–1H
Swings: 4H–1D
7. Key Mindset Rules
Patience beats prediction. Wait for confirmations.
Volume confirms conviction, not direction.
If RSI and Overlay disagree → No trade.
Only act when 2 of 3 systems (EMA, RSI, Volume) align.
celenni//@version=6
strategy("Cruce SMA 5/20 – v6 (const TF, gap en puntos SOLO cortos, next bar open, 1 trade/ventana, anti-flip)",
overlay = true,
initial_capital = 10000,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 10,
pyramiding = 0)
// === CONSTANTES ===
const string TF = "15" // fija el timeframe de cálculo (ej. "5","15","30","60","120","240","D")
const string SYM_ALLOWED = "QQQ" // símbolo permitido
// === Inputs ===
confirmOnClose = input.bool(true, "Confirmar señal al cierre (evita repaint)")
maxGapPtsShort = input.float(0.50, "Máx gap permitido en CORTOS (puntos)", 0.0, 1e6)
lenFast = input.int(5, "SMA rápida", 1)
lenSlow = input.int(20, "SMA lenta", 2)
tpPts = input.float(20.0, "Take Profit (puntos)", 0.01)
slPts = input.float(5.0, "Stop Loss (puntos)", 0.01)
// Ventanas (NY)
useSessions = input.bool(true, "Usar ventanas NY")
sess1 = input.session("1000-1130", "Ventana 1 (NY)")
sess2 = input.session("1330-1600", "Ventana 2 (NY)")
flatOutside = input.bool(true, "Cerrar posición al salir de la ventana")
// === Utilidades ===
isAllowedSymbol() =>
(syminfo.ticker == SYM_ALLOWED) or str.contains(str.upper(syminfo.ticker), str.upper(SYM_ALLOWED))
// === Series MTF (cálculo en TF) ===
closeTF = request.security(syminfo.tickerid, TF, close, barmerge.gaps_off, barmerge.lookahead_off)
smaFast = ta.sma(closeTF, lenFast)
smaSlow = ta.sma(closeTF, lenSlow)
// Señales MTF sin repaint
longSignalTF = request.security(syminfo.tickerid, TF,
ta.crossover(ta.sma(close, lenFast), ta.sma(close, lenSlow)),
barmerge.gaps_off, barmerge.lookahead_off)
shortSignalTF = request.security(syminfo.tickerid, TF,
ta.crossunder(ta.sma(close, lenFast), ta.sma(close, lenSlow)),
barmerge.gaps_off, barmerge.lookahead_off)
// === Sesiones (evaluadas en el TF del gráfico, zona NY) ===
inSess1 = useSessions ? not na(time(timeframe.period, sess1, "America/New_York")) : true
inSess2 = useSessions ? not na(time(timeframe.period, sess2, "America/New_York")) : true
inSession = inSess1 or inSess2
// Inicio de ventanas y contadores (1 trade por ventana)
var bool wasIn1 = false, wasIn2 = false
win1Start = inSess1 and not wasIn1
win2Start = inSess2 and not wasIn2
wasIn1 := inSess1
wasIn2 := inSess2
var int tradesWin1 = 0, tradesWin2 = 0
if win1Start
tradesWin1 := 0
if win2Start
tradesWin2 := 0
justOpened = strategy.position_size != 0 and strategy.position_size == 0
if justOpened
if inSess1
tradesWin1 += 1
if inSess2
tradesWin2 += 1
canTakeMore =
(inSess1 and tradesWin1 < 1) or
(inSess2 and tradesWin2 < 1) or
(not useSessions)
// === Filtro NO-GAP SOLO para CORTOS (en PUNTOS) ===
// Compara OPEN actual vs CLOSE previo; se evalúa en la barra donde se EJECUTA (apertura actual).
gapPts = math.abs(open - close )
shortGapOK = maxGapPtsShort <= 0 ? true : (gapPts <= maxGapPtsShort)
// === Anti-flip y gating ===
isFlat = strategy.position_size == 0
canSignal = (not confirmOnClose or barstate.isconfirmed)
canTrade = isAllowedSymbol() and inSession and canTakeMore and canSignal
// === ENTRADAS (se colocan al cierre; se llenan en la apertura siguiente) ===
// Largos: sin filtro de gap
if canTrade and isFlat and longSignalTF
strategy.entry("Long", strategy.long)
// Cortos: requieren shortGapOK
if canTrade and isFlat and shortSignalTF and shortGapOK
strategy.entry("Short", strategy.short)
// === TP/SL en puntos ===
if strategy.position_size > 0
e = strategy.position_avg_price
strategy.exit("TP/SL Long", from_entry="Long", limit=e + tpPts, stop=e - slPts)
if strategy.position_size < 0
e = strategy.position_avg_price
strategy.exit("TP/SL Short", from_entry="Short", limit=e - tpPts, stop=e + slPts)
// === Cierre fuera de sesión ===
if flatOutside and not inSession and strategy.position_size != 0
strategy.close_all("Fuera de sesión")
// === Visual ===
plot(smaFast, color=color.new(color.teal, 0), title="SMA 5 ("+TF+")")
plot(smaSlow, color=color.new(color.orange, 0), title="SMA 20 ("+TF+")")
plotshape(longSignalTF and canTrade and isFlat, title="Compra", style=shape.triangleup,
location=location.belowbar, color=color.new(color.teal,0), size=size.tiny, text="Long")
plotshape(shortSignalTF and canTrade and isFlat and shortGapOK, title="Venta", style=shape.triangledown,
location=location.abovebar, color=color.new(color.red,0), size=size.tiny, text="Short")























