Scalping with Fair Value Gap (python)

Scalping with Fair Value Gap (python)

Python script to identify Fair Value Gaps (FVG) in forex data and generate trading signals. The script uses historical forex data (with columns like Open, High, Low, Close) to locate FVGs and signal potential buy or sell opportunities when the price enters the FVG zone.


Code to Identify FVG and Generate Signals

import pandas as pd

# Load forex data (CSV with 'Open', 'High', 'Low', 'Close' columns)
data = pd.read_csv('forex_data.csv')

# Ensure data has the correct format
if not all(col in data.columns for col in ['Open', 'High', 'Low', 'Close']):
    raise ValueError("Data must contain 'Open', 'High', 'Low', 'Close' columns.")

# Create empty columns for signals and FVG zones
data['FVG_Upper'] = None
data['FVG_Lower'] = None
data['Signal'] = None

# Threshold for FVG size as a percentage of the candle range (e.g., 0.5 = 50%)
FVG_THRESHOLD = 0.5

# Function to calculate FVG size
def is_valid_fvg(high1, low1, high2, low2, threshold):
    fvg_size = abs(high1 - low2)  # Size of the gap
    avg_candle_size = (high1 - low1 + high2 - low2) / 2  # Average candle size
    return fvg_size >= threshold * avg_candle_size  # Check if the gap meets the threshold

# Function to identify FVGs
def identify_fvg(data, threshold):
    for i in range(2, len(data)):
        # Previous two candles
        prev_candle_1 = data.iloc[i - 2]
        prev_candle_2 = data.iloc[i - 1]
        curr_candle = data.iloc[i]

        # FVG conditions with threshold
        if prev_candle_2['Low'] > prev_candle_1['High'] and curr_candle['Low'] > prev_candle_2['High']:
            # Bullish FVG
            if is_valid_fvg(prev_candle_1['High'], prev_candle_1['Low'], prev_candle_2['High'], prev_candle_2['Low'], threshold):
                data.loc[i, 'FVG_Upper'] = prev_candle_1['High']
                data.loc[i, 'FVG_Lower'] = prev_candle_2['Low']
        elif prev_candle_2['High'] < prev_candle_1['Low'] and curr_candle['High'] < prev_candle_2['Low']:
            # Bearish FVG
            if is_valid_fvg(prev_candle_1['Low'], prev_candle_1['High'], prev_candle_2['Low'], prev_candle_2['High'], threshold):
                data.loc[i, 'FVG_Upper'] = prev_candle_2['High']
                data.loc[i, 'FVG_Lower'] = prev_candle_1['Low']
    return data

# Apply FVG identification
data = identify_fvg(data, FVG_THRESHOLD)

# Function to generate signals based on FVG
def generate_signals(data):
    for i in range(len(data)):
        # If price re-enters the FVG zone
        if pd.notna(data.loc[i, 'FVG_Upper']) and pd.notna(data.loc[i, 'FVG_Lower']):
            current_price = data.loc[i, 'Close']

            # Buy Signal: Price enters a bullish FVG
            if data.loc[i, 'FVG_Upper'] >= current_price >= data.loc[i, 'FVG_Lower']:
                data.loc[i, 'Signal'] = 'Buy'

            # Sell Signal: Price enters a bearish FVG
            elif data.loc[i, 'FVG_Upper'] <= current_price <= data.loc[i, 'FVG_Lower']:
                data.loc[i, 'Signal'] = 'Sell'

    return data

# Generate signals
data = generate_signals(data)

# Save or display results
print(data[['Open', 'High', 'Low', 'Close', 'FVG_Upper', 'FVG_Lower', 'Signal']])
data.to_csv('fvg_signals.csv', index=False)

Explanation of the Code

  1. Fair Value Gap Detection:
    • The script looks for gaps between the High and Low of consecutive candles.
    • A bullish FVG occurs when the second candle's Low is higher than the first candle's High.
    • A bearish FVG occurs when the second candle's High is lower than the first candle's Low.
  2. Signal Generation:
    • A Buy signal is generated when the current price (Close) enters a bullish FVG zone.
    • A Sell signal is generated when the current price enters a bearish FVG zone.
  3. FVG Zones:
    • FVG_Upper and FVG_Lower columns store the boundaries of the detected FVGs.
  4. Output:
    • The script outputs a CSV file (fvg_signals.csv) containing FVG zones and the corresponding signals for each candle.

With Threshold:

  1. Added is_valid_fvg Function:
    • Checks if the FVG size exceeds a certain percentage (FVG_THRESHOLD) of the average size of the candles forming the gap.
    • This ensures only significant FVGs are considered.
  2. Threshold Parameter:
    • The FVG_THRESHOLD parameter controls the minimum size of FVGs as a percentage of the average candlestick size.
    • For example, FVG_THRESHOLD = 0.5 means the FVG must be at least 50% of the average candlestick size.
  3. Dynamic Validation:
    • FVGs are now filtered dynamically based on size, improving the quality of signals.

Threshold Application:

  • FVG_THRESHOLD = 0.5:
    • Only FVGs that are at least 50% of the average size of the candles forming the gap are considered valid.
  • Output Example:

This ensures that only significant gaps are highlighted and reduces false positives caused by small or insignificant gaps. Adjust the FVG_THRESHOLD based on your trading strategy.

Disclaimer: Trading in forex involves significant risk and may not be suitable for all investors. The content on this website is for informational purposes only and does not constitute financial advice.