PROTECTED SOURCE SCRIPT
Atualizado

ACE FVG & IFVG Trading System

1 235
1. What the Script Does
The "ACE FVG & IFVG Trading System " is a TradingView Pine Script (version 5) that identifies and trades Fair Value Gaps (FVGs) and Inverse Fair Value Gaps (IFVGs). It offers:

Detection of bullish/bearish FVGs and IFVGs with customizable parameters.

Multiple entry types: regular FVG retracement, Break of Structure (BOS), breakaway gaps, and Immediate/Retrace IFVG entries.

A pending setup system showing potential trades before they trigger.

Risk management with configurable stop loss (SL) and take profit (TP) based on FVG levels, swing points, or risk-reward ratios.

Market structure analysis using swing highs/lows, BOS, and Market Structure Shifts (MSS).

Time filters to restrict trading to specific sessions.

Visualizations including FVG boxes, trade boxes, pivot lines, and labels.

Entry and performance tables displaying trade details and metrics like win rates and P&L by entry type.

2. How It Works
The script is organized into modular sections for efficient execution:

Inputs: Extensive customization options (e.g., FVG size, entry types, SL/TP modes, time filters) grouped for clarity.

Data Structures: Custom types (FVGData, SwingPoint, EntryData) store FVG, pivot, and trade data in arrays.

Utility Functions: Handle calculations like risk-reward ratios, time validation, and trade size filtering.

Swing Point Detection: Uses ta.pivothigh/ta.pivotlow to identify pivots, supporting BOS/MSS and SL/TP calculations.

FVG Detection: Identifies regular FVGs (low > high[2] or high < low[2]) and IFVGs (mitigated FVGs with immediate or retrace signals).

Entry Logic: Triggers trades based on user-enabled conditions (e.g., retracement, BOS, breakaway gaps) with dynamic SL/TP.

Trade Management: Tracks active/pending trades, updates visualizations (boxes, lines, labels), and handles cancellations/invalidations.

Main Logic: Executes on each bar to detect FVGs, process entries, update trades, and manage visualizations.

Tables: Displays recent trades and performance stats (e.g., win rates by entry type) on the last bar.

Pivot Visualization: Plots swing points with dynamic extensions and mitigation status (solid/dotted lines).

3. How to Use It
Add to TradingView:

Open Pine Editor, paste the script, save it, and add to chart.

Configure Inputs:
Access settings via chart (right-click indicator > Settings).
Adjust:
fvgMinSize for market volatility (e.g., 5 for forex).
Entry types (e.g., enable IFVG, disable breakaway gaps).
SL/TP modes and minimum R:R (e.g., 2.0 for 1:2).
Time filters for active sessions (e.g., 09:30-16:00).
Visual settings (box transparency, table positions).

Interpret Output:

FVG Boxes: Green (bullish), red (bearish), purple (IFVG/mitigated).
Trade Boxes: Gray-green/red-gray (pending), green/red (active), updated for win/loss.
Pivot Lines: Solid (unmitigated), dotted (mitigated).
Tables: Entry table shows trade details; performance table shows win rates/P&L.
Trading:

Monitor pending setups for entry signals.
Enter manually at active trade levels, following SL/TP.
Use performance stats to refine settings.
Test on demo charts and adjust for market/timeframe.

Best Practices:
Use higher timeframes (e.g., 1H, 4H) for less noise.

Combine with other analysis (e.g., support/resistance).

Backtest using TradingView’s replay feature.

Originality
The script is original due to its unique combination of features:
Enhanced IFVG Strategy: Dual Immediate/Retrace IFVG modes with a novel “Immediate Then Retrace” preference.

Pending Setup System: Proactive visualization of potential trades with auto-cancellation.

Granular Performance Tracking: Detailed breakdown of win rates/P&L by entry type (regular FVG, IFVG, breakaway).

Dynamic Pivot Visualization: Real-time mitigation updates (solid to dotted lines).

Modular Design: Custom types and organized logic for extensibility. It builds on general FVG concepts (e.g., from ICT) but implements unique logic and features not found in standard
TradingView FVG scripts, distinguishing it from both open-source and premium indicators.

Credit of Concepts to ICT
Collaborations with JMAC and Timeless
Notas de Lançamento
1. Fixed Premature TP Triggering

Added tpTriggerType input (Wick vs Close)
Critical Fix: Only checks TP/SL on bars AFTER the entry bar (canCheckExit = bar_index > entry.entryBar)
Prevents same-candle false wins for retrace entries

2. Historical Price Level Validation

Added tracking fields to FVGData: highestSinceFormation, lowestSinceFormation, lastUpdateBar
Enhanced calculateTakeProfit() to validate TP targets against historical highs/lows
Automatically adjusts TP levels beyond any price already hit since FVG formation
Eliminates impossible scenarios where TP was already exceeded before entry

3. Enhanced Entry Logic

Fixed all "undeclared identifier" errors by keeping variables in proper scope
Updated createEntry() and createPendingSetup() to use new TP calculation
Added proper entry bar tracking for timing validation

4. Improved Trade Management

Enhanced updateEntryStatus() with proper entry timing checks
Better invalidation logic for pending setups
More accurate P&L calculation

🎯 Key Changes Summary:
Before (Broken):

FVG retrace at 100 → Candle goes to 110 → TP at 105 immediately triggered = False Win
Same-bar entry and exit causing impossible trade scenarios

After (Fixed):

FVG retrace at 100 → TP adjusted to 111+ (beyond historical high)
Entry validation only on subsequent candles
Realistic and achievable profit targets

📋 Recommended Settings:

SL Trigger: "Close" (more conservative)
TP Trigger: "Close" (ensures actual profit realization)
IFVG Entry Preference: "Immediate Then Retrace" (balanced approach)

This script should now provide accurate trade entries and exits without the premature TP triggering issues you were experiencing!
Notas de Lançamento
Hotfix buffer limits on lower timeframes:

Key Fixes Applied:

Added buffer limits to all swing point lookback functions (500 bars maximum for swing searches, 200 bars for structure checks)
Limited sweptLookback to maximum 100 bars and added overall 200 bar limit
Added safety check in detectRegularFVG() to ensure we have at least 3 bars before trying to access high[2] or low[2]
Constrained all historical data access to reasonable limits to prevent going beyond the 2400 bar buffer
Added barsBack calculations to ensure we don't access data too far in the past

Additional recommendations:

Reduce input parameters if you're still getting buffer errors:

Set sweptLookback to 20 or less
Set pivotLength to 3-5
Set lookback periods to smaller values
Notas de Lançamento
Enhanced Alert Features Added:
🔥 Profit Potential Calculations:

Position Size - Calculated based on account balance and risk percentage
Potential Profit - Exact dollar amount if TP is hit
Potential Loss - Exact dollar amount if SL is hit
Lot Size - For forex traders (standard/mini lots)

📊 Position Sizing Methods:

Point Value Method - Best for forex/futures (e.g., $10 per pip)
Percentage Method - Best for stocks/crypto

🎯 Distance Tracking:

Distance to Entry - For pending setups
Distance to TP/SL - For active trades
Entry execution confirmations

💰 Real Profit/Loss Reporting:

Shows actual dollar profit/loss when trades exit
Accounts for your position size and risk settings
Notas de Lançamento
Hopefully fixed the runtime issue on lower timeframes (1 minute)
Notas de Lançamento
Key updates:
-FVG Lookback
-Simplified Performance Table.

Input Parameter: fvgLookbackLimit - applies to all FVG entries (retrace, BOS, breakaway)
Comprehensive Coverage: The lookback limit now affects:

Bull FVG Retrace entries
Bear FVG Retrace entries
Bull FVG BOS entries
Bear FVG BOS entries
Breakaway Gap entries
Pending setup creation

How It Works:

All FVG Types: Whether it's a retrace, BOS, or breakaway - they all respect the same time limit
Consistent Behavior: No FVG can trigger an entry after the specified number of candles have passed
Clean Charts: Prevents old FVG levels from cluttering your chart with stale setups
Performance: Reduces processing load by ignoring very old FVGs

This is much cleaner and more logical - one universal setting that controls the "freshness" of all FVG setups!

Default set to 30. Max lookback 500.
Notas de Lançamento
updated 10. ENTRY TABLE DISPLAY to be in NY Timezone

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.