Pine Script: Code Your First ICT Indicator
Tired of manually spotting ICT setups? This guide bridges the gap between theory and practice. Learn to code your first Fair Value Gap (FVG) indicator using Pine Script v5 on TradingView to automate your analysis and trade with more precision.
Amara Okafor
Fintech Strategist

Imagine cutting through the noise of forex charts, not with endless manual analysis, but with a custom tool that highlights high-probability ICT setups for you. Many intermediate traders grasp the power of ICT concepts like Fair Value Gaps or Order Blocks, yet struggle with their subjective application and the sheer time it takes to identify them consistently. What if you could automate this precision, transforming theoretical knowledge into a practical, time-saving advantage? This isn't about replacing your trading decisions, but empowering them with objective data. In this guide, we'll bridge that gap, showing you how to harness TradingView's Pine Script v5 to code your very first ICT indicator. You'll learn to automate the identification of crucial price action patterns, reducing analysis time and bringing a new level of consistency to your forex strategy. Get ready to turn your ICT insights into actionable code.
Unlock Automated Precision: Pine Script v5 & ICT Foundations
Before we jump into writing code, let's set the stage. Why Pine Script? And what specific ICT concept are we targeting? Understanding the 'why' behind the tools and concepts is what separates a script-kiddie from a proficient trader who builds their own edge.
The Power of Pine Script v5 for Forex Automation
Think of Pine Script as a specialized language built for one purpose: creating custom trading tools on TradingView. It's designed to be more accessible than general-purpose programming languages like Python. Version 5, our focus today, introduced cleaner syntax and more powerful features, making it easier than ever to bring your trading ideas to life.
Key advantages for an ICT trader include:
- Objectivity: Code follows rules, period. It removes the emotional guesswork of "Is that really an FVG?" from your analysis.
- Efficiency: An indicator can scan every single candle for a setup in milliseconds, a task that would take you hours of manual scrolling.
- Backtesting: Once coded, you can visually assess how often your specific setups appeared in the past, giving you a better feel for their frequency and behavior.
If you've seen older Pine Script code, v5 made things much clearer. For instance, it introduced dedicated functions for drawing (box.new(), line.new()) and improved how variables are declared (var), making scripts more robust and readable.
Demystifying Key ICT Concepts: Fair Value Gaps (FVG)
We'll start with one of the most fundamental ICT concepts: the Fair Value Gap (FVG). It's a perfect candidate for automation because it has a clear, rule-based definition.

An FVG is a three-candle pattern that represents an inefficiency or imbalance in the market. Price moved so quickly in one direction that it left a 'gap' in the market delivery.
- Bullish FVG (or BISI - Buyside Imbalance Sellsise Inefficiency): The low of the third candle is above the high of the first candle. The gap is the space between the first candle's high and the third candle's low.
- Bearish FVG (or SIBI - Sellside Imbalance Buyside Inefficiency): The high of the third candle is below the low of the first candle. The gap is the space between the first candle's low and the third candle's high.
These zones often act like magnets for price, which tends to revisit them to 'rebalance' the inefficient price action. For a deeper dive into the different kinds of market gaps, check out our guide on mastering the 3 types of ICT gaps. For now, this simple, powerful pattern is all we need to start coding.
Your Coding Canvas: Setting Up TradingView for ICT Automation
Ready to get your hands dirty? Let's open up the workshop. TradingView makes this incredibly easy. You don't need to install any software; everything happens right in your browser.
Navigating the Pine Editor Interface
At the bottom of your TradingView chart, you'll see a tab labeled "Pine Editor." Click it. This is your command center. It might look a little intimidating, but it's straightforward.
- Open the Editor: Click the "Pine Editor" tab.
- Create a New Script: Click "Open" and select "New blank indicator."
TradingView will populate the editor with some basic starter code. Let's break it down.
Essential Pine Script v5 Syntax & Structure
Every Pine Script v5 indicator has a few core components. Here's the default template you'll see:
//@version=5
indicator("My script")
plot(close)//@version=5: This is mandatory. It tells TradingView to use the latest version of the language.indicator("My script"): This function declares your script as an indicator. You can change the name inside the quotes to something like "My ICT FVG Finder". Settingoverlay=trueinside the parentheses (indicator("My FVG", overlay=true)) will make your drawings appear on the main chart instead of in a separate panel below.plot(close): This is a simple function that draws a line plot of the closing price of each bar. We'll be removing this and replacing it with our own custom logic and drawings.
To build our FVG detector, we'll need two more concepts:

- Variables: Storing data. For example,
is_bullish_fvg = low[2] > high. Here,[2]refers to the data from two candles ago.high(orhigh[0]) refers to the current, developing candle. - Conditional Logic: Making decisions. We'll use an
ifstatement:if is_bullish_fvg... then do something, like draw a box on the chart.
That's it for the setup. Now, let's write the logic.
From Theory to Code: Building Your First ICT FVG Indicator
This is where the magic happens. We're going to translate the FVG definition from plain English into Pine Script. Our goal is to create an indicator that automatically identifies and draws a box around every FVG.
Identifying FVG Patterns with Pine Script Logic
Let's start with a clean slate in your Pine Editor. Delete the default code and let's build this step-by-step.
First, the boilerplate setup:
//@version=5
indicator("FXNX ICT FVG Detector", overlay=true)Next, we define the conditions for both bullish and bearish FVGs. Remember the 3-candle rule. In Pine Script, high[1] refers to the high of the previous candle, low[1] the low of the previous candle, and so on.
// --- LOGIC --- //
// A bullish FVG exists if the low of the current bar is above the high of two bars ago.
bullish_fvg = high[2] < low
// A bearish FVG exists if the high of the current bar is below the low of two bars ago.
bearish_fvg = low[2] > highPro Tip: The logic checks
high[2]and the currentlow(orlow[0]). This means the FVG is only confirmed once the third candle in the pattern closes. The gap itself is on the middle candle, which is candle[1].
Visualizing ICT Zones on Your Chart
Now that we have our bullish_fvg and bearish_fvg variables, which will be either true or false for each candle, we can tell the script to draw something when they are true.
We'll use an if statement and the box.new() function. This function draws a rectangle on the chart.
// --- DRAWING --- //
// If a bullish FVG is detected, draw a green box.
if bullish_fvg
box.new(
left = bar_index[1],
top = high[2],
right = bar_index,
bottom = low,
bgcolor = color.new(color.green, 80),
border_color = color.new(color.green, 80)
)
// If a bearish FVG is detected, draw a red box.
if bearish_fvg
box.new(
left = bar_index[1],
top = high,
right = bar_index,
bottom = low[2],
bgcolor = color.new(color.red, 80),
border_color = color.new(color.red, 80)
)Let's break down box.new():
left&right: The x-coordinates (time).bar_index[1]is the start of the middle candle, andbar_indexis the end.

top&bottom: The y-coordinates (price). For a bullish FVG, the box spans from the high of the first candle (high[2]) to the low of the third (low).bgcolor&border_color: We set the color and transparency (80 is quite transparent).
Here is the complete, copy-paste-ready script:
//@version=5
indicator("FXNX ICT FVG Detector", overlay=true)
// --- LOGIC --- //
// A bullish FVG is a 3-bar pattern where there's a gap between the 1st candle's high and the 3rd candle's low.
bullish_fvg = high[2] < low
// A bearish FVG is a 3-bar pattern where there's a gap between the 1st candle's low and the 3rd candle's high.
bearish_fvg = low[2] > high
// --- DRAWING --- //
// If a bullish FVG is detected on the close of the 3rd bar, draw a green box.
if bullish_fvg
box.new(
left = bar_index[1], // Start the box at the FVG candle
top = high[2], // Top of the gap
right = bar_index, // End the box at the current candle
bottom = low, // Bottom of the gap
bgcolor = color.new(color.green, 80), // Set background color and transparency
border_color = color.new(color.green, 80) // Set border color
)
// If a bearish FVG is detected on the close of the 3rd bar, draw a red box.
if bearish_fvg
box.new(
left = bar_index[1], // Start the box at the FVG candle
top = high, // Top of the gap
right = bar_index, // End the box at the current candle
bottom = low[2], // Bottom of the gap
bgcolor = color.new(color.red, 80), // Set background color and transparency
border_color = color.new(color.red, 80) // Set border color
)Paste this into your Pine Editor and click "Add to Chart". Congratulations, you've just coded your first ICT indicator!
Actionable Insights: Applying Your ICT Indicator on Forex Charts
Having a tool is one thing; knowing how to use it is another. Your chart is now populated with green and red boxes, but what do they actually mean for your trading?
Adding and Configuring Your Custom Indicator
Once you click "Add to Chart" in the Pine Editor, your FVG detector will appear on your selected forex pair, like EUR/USD. You can toggle its visibility or access its settings by clicking the indicator's name in the top-left corner of your chart. For this simple script, there are no settings to configure yet, but this is where they would live if you added user inputs.
Interpreting Signals for Trade Opportunities
Your new indicator is a map of market inefficiencies, not a traffic light for entries. It highlights areas of interest where you should pay closer attention.
- FVGs as Support/Resistance: Bullish (green) FVGs often act as support. When price retraces back into a green box, it may find buying pressure. Conversely, bearish (red) FVGs can act as resistance.
- FVGs as Targets: If you are in a short trade and price is moving down, a nearby bullish FVG could be a logical place to take profit, as price may stall or reverse there.
- Context is King: A bullish FVG appearing in a clear downtrend is far less reliable than one that forms after a major shift in market structure. Always combine the indicator's signals with your broader analysis. Is price bullish or bearish on higher timeframes? Your indicator provides objectivity, but you provide the context. Understanding the interplay between concepts like FVGs and other structures is key; a tool like an order block vs breaker decision tree can help build this contextual awareness.
Warning: Never take a trade based solely on an indicator's signal. This FVG detector is a powerful tool for confluence, helping to confirm trade ideas that are already supported by your overall market analysis.
Beyond the Basics: Refining Your ICT Indicator & Best Practices
Your first indicator is a huge step, but it's just the beginning. Like any tool, it can be improved and refined. It's also important to be aware of the common pitfalls, both in coding and in application.
Common Coding & ICT Implementation Mistakes

- Ignoring Context: The biggest mistake is treating every FVG as a high-probability setup. An FVG created by a high-impact news release is different from one formed in a quiet, ranging market. Your code can't see the news; you have to.
- Look-Ahead Bias: A common coding error is using data from the future. Our script correctly uses historical data (
[1],[2]) to make decisions, ensuring it doesn't 'cheat'. Always double-check your data references. - Over-Optimization: It's tempting to add dozens of filters to try and create a 'perfect' signal. This often leads to a useless indicator that is tailored to past data and fails in live markets. Start simple and add complexity only when you have a clear reason. Remember, consistent application of a good strategy is what leads to long-term compound growth, not a magic indicator.
Evolving Your Indicator: Next Steps for Customization
Think of your script as a foundation. Here are a few ideas to expand on it:
- Add User Inputs: Allow yourself to change the colors or turn bullish/bearish FVGs on and off from the settings menu using
input.color()andinput.bool(). - Create Alerts: Use the
alertcondition()function to get a notification whenever a new FVG is formed, so you don't have to stare at the charts all day. - Filter by Size: Add a condition to only show FVGs that are a certain number of pips in size, filtering out insignificant micro-gaps.
- Integrate Other Concepts: Could you modify the logic to detect Order Blocks? Or to only show FVGs that occur after a liquidity sweep?
For a comprehensive guide on Pine Script's capabilities, the official Pine Script v5 User Manual from TradingView is an invaluable resource. The journey into automating your analysis is a continuous process of learning, testing, and refining.
You've just taken a significant leap in your trading journey, moving beyond manual analysis to automate the identification of powerful ICT concepts using Pine Script v5. We've covered the essentials, from understanding Pine Script's capabilities and core ICT concepts like Fair Value Gaps, to setting up your development environment and coding your first custom indicator. The ability to objectively plot these critical zones on your charts reduces subjectivity, saves valuable time, and allows for more consistent analysis. Remember, automation is a tool to enhance your decision-making, not replace it. The next step is to experiment: modify parameters, add alerts, or even integrate other ICT concepts to build a truly personalized trading assistant. For further resources and advanced strategies to refine your automated trading edge, explore the comprehensive tools and educational content available on FXNX. How will automating your ICT analysis transform your trading approach?
Start coding your first ICT indicator today! Experiment with the provided Pine Script v5 concepts on TradingView and share your results in the comments below. For more advanced Pine Script tutorials and ICT strategies, explore the FXNX blog.
Frequently Asked Questions
What is a Fair Value Gap (FVG) in ICT?
A Fair Value Gap, or FVG, is a three-candle pattern indicating a market imbalance. It occurs when price moves rapidly, leaving a gap between the first candle's wick and the third candle's wick, an area price may later revisit to rebalance.
Is Pine Script difficult to learn for traders?
Pine Script is designed to be more accessible than general programming languages. If you can understand trading logic (e.g., "if the moving average crosses up, then..."), you can learn the basics of Pine Script. It has a supportive community and extensive documentation to help traders get started.
Can I use this Pine Script ICT indicator on MT4/MT5?
No, Pine Script is exclusive to the TradingView platform. MetaTrader 4 and 5 use a different programming language called MQL4/MQL5. The logic can be translated, but the code itself is not directly compatible.
How can I add alerts to my FVG indicator?
You can use the alert() or alertcondition() function in Pine Script. For example, after your if bullish_fvg block, you could add a line alert("Bullish FVG Detected on " + syminfo.tickerid, freq = alert.freq_once_per_bar_close) to create a customizable alert.
Ready to trade?
Join thousands of traders on NX One. 0.0 pip spreads, 500+ instruments.
About the Author

Amara Okafor
Fintech StrategistAmara Okafor is a Fintech Strategist at FXNX, bringing a unique perspective from her background in both London's financial district and Lagos's booming fintech scene. She holds an MBA from the London School of Economics and has spent 6 years working at the intersection of traditional finance and digital innovation. Amara specializes in emerging market currencies and African forex markets, writing with insight that bridges global finance with frontier market opportunities.
Related Articles
Continue reading

Order Block vs Breaker: Your Decision Tree
Confused by Order Blocks, Breakers, and Supply/Demand zones? This guide gives you a simple 'Decision Tree' to confidently identify the correct institutional setup, leading to better entries and risk management.

Mastering ICT Gaps: 3 Types Explained
Traditional gap trading doesn't work in forex. Discover how ICT's concept of Breakaway, Runaway, and Exhaustion Gaps—powerful Fair Value Gaps—can help you read institutional intent and trade trends with more confidence.

BOS vs CHoCH: Master Forex Structure Shifts
Distinguish between a genuine market structure shift (CHoCH) and a simple trend continuation (BOS). This guide unlocks the secrets of Smart Money Concepts to help you trade with precision.

Top SMC Indicators for TradingView (Free & Paid)
Overwhelmed by manually spotting SMC patterns? This guide cuts through the noise, revealing the best free and premium SMC indicators on TradingView to automate your analysis and boost consistency.

ADX Indicator: Master Trend Strength in Forex
Stop trading trends that fizzle out. The ADX indicator measures true trend strength, helping you confirm high-probability setups and avoid weak signals. This guide breaks down ADX, +DI, and -DI for smarter entries and exits.

Renko Charts: Cut Market Noise, See Clear Trends
Overwhelmed by whipsaws and false signals? Renko charts filter out market noise by focusing on price movement, not time. This guide shows you how to use them to see clearer trends, find better entries, and trade with more confidence.