Of course. You've correctly identified the weakness of the first script. Using a simple lookback period doesn't properly identify a true market "swing."
This improved script uses Pine Script's built-in ta.pivothigh and ta.pivotlow functions to identify significant turning points in the market. It then waits for a swing low followed by a swing high to define an upward impulse move. Only then does it draw the Fibonacci levels and wait for a retracement to the 0.618 level to trigger a long trade.
This approach is much more robust and closer to how a discretionary trader would identify and act on a Fibonacci setup.
The Improved Pine Script
Copy and paste this code directly into your Pine Editor.
//@version=5
strategy("Proper Swing Fib 0.618 Entry",
overlay=true,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=10,
comment_calc_orders=true)
// ================ INPUTS ================= //
leftBars = input.int(15, "Pivot Left Bars", "Number of bars to the left for pivot detection.")
rightBars = input.int(5, "Pivot Right Bars", "Number of bars to the right for pivot detection (controls confirmation lag).")
// ================ PIVOT DETECTION ================= //
// Find the price of the last confirmed pivot high and low.
// The [rightBars] offset is crucial to prevent the script from acting on a pivot before it's confirmed.
pivotHighPrice = ta.pivothigh(leftBars, rightBars)
pivotLowPrice = ta.pivotlow(leftBars, rightBars)
// ================ STATE MANAGEMENT (TRACKING THE SWING) ================= //
// We need to store the points of our last valid swing (low -> high for a long setup).
// 'var' ensures these variables hold their value across bars.
var float swingLow = na
var float swingHigh = na
var int swingLowBar = na
var int swingHighBar = na
// Logic to identify a new swing for a potential long trade (a low followed by a high)
if not na(pivotLowPrice)
// A new pivot low is found, store its price and bar index.
swingLow := pivotLowPrice
swingLowBar := bar_index - rightBars
if not na(pivotHighPrice) and not na(swingLow) and (bar_index - rightBars > swingLowBar)
// A new pivot high is found *after* our last low. This completes the upward swing.
swingHigh := pivotHighPrice
swingHighBar := bar_index - rightBars
// ================ FIBONACCI & RISK-REWARD CALCULATION ================= //
var float fib_618_level = na
var float fib_886_level_stop = na
var float take_profit_level = na
// Only calculate Fib levels if we have a valid, un-traded swing (low followed by high)
if not na(swingHigh) and not na(swingLow) and swingHighBar > swingLowBar
// Calculate the range of the impulse move
swingRange = swingHigh - swingLow
// Calculate Fibonacci and RR levels based on this specific swing
fib_618_level := swingHigh - (swingRange * 0.618)
fib_886_level_stop := swingHigh - (swingRange * 0.886)
risk = fib_618_level - fib_886_level_stop
take_profit_level := fib_618_level + (risk * 3)
else
// If we don't have a valid swing, reset the levels
fib_618_level := na
fib_886_level_stop := na
take_profit_level := na
// ================ STRATEGY ENTRY & EXIT LOGIC ================= //
// Entry Condition: We are not in a trade, we have a valid Fib level, and the price crosses down through it.
longCondition = strategy.position_size == 0 and not na(fib_618_level) and ta.crossunder(close, fib_618_level)
if longCondition
// Enter the long trade
strategy.entry("Long", strategy.long, comment="Enter @ 0.618")
// Set the stop loss and take profit for that entry
strategy.exit("TP/SL", from_entry="Long", limit=take_profit_level, stop=fib_886_level_stop, comment_profit="TP @ RR3", comment_loss="SL @ 0.886")
// IMPORTANT: Reset the swing points after entering a trade.
// This prevents the script from taking multiple trades on the same old swing.
swingLow := na
swingHigh := na
swingLowBar := na
swingHighBar := na
// ================ VISUALIZATION ================= //
// Plot the swing points that the script is using
plotshape(pivotHighPrice, style=shape.triangledown, location=location.abovebar, color=color.new(color.maroon, 0), size=size.small, offset=-rightBars, title="Confirmed Pivot High")
plotshape(pivotLowPrice, style=shape.triangleup, location=location.belowbar, color=color.new(color.teal, 0), size=size.small, offset=-rightBars, title="Confirmed Pivot Low")
// Plot the active Fib/RR levels only when a setup is present
plot(fib_618_level, "Fib 0.618 Entry", color.new(color.blue, 0), style=plot.style_linebr)
plot(fib_886_level_stop, "Fib 0.886 Stop Loss", color.new(color.red, 0), style=plot.style_linebr)
plot(take_profit_level, "Take Profit (RR:3)", color.new(color.green, 0), style=plot.style_linebr)
// --- How to use this strategy ---
// 1. Add to Chart.
// 2. Go to the "Strategy Tester" tab below your chart.
// 3. In the "Properties" tab of the strategy, you can adjust the "Pivot Left/Right Bars" to find swings that match your style.
// - Larger `leftBars` values will find more significant, longer-term swings.
// - `rightBars` determines the confirmation lag. A smaller value is faster but more prone to false signals.
Key Improvements and How It Works:
- Pivot-Based Swings: Instead of
ta.highest, it uses ta.pivothigh and ta.pivotlow. This is a much more accurate way to define a market turning point. You can control the "size" of the swing it looks for by changing the leftBars and rightBars inputs.
- State Management: The script now has a "memory" using
var variables (swingLow, swingHigh, etc.). It actively looks for a specific pattern: a confirmed low pivot followed by a confirmed high pivot.
- Non-Repainting Logic: The
[rightBars] offset is critical. It ensures the script only recognizes a pivot after it has been confirmed, preventing it from making decisions based on future data.
- Clear Trade Logic:
- A trade setup is only active when a valid
low -> high swing is identified.
- The Fibonacci levels are calculated for that specific swing.
- An entry is triggered when the price crosses the 0.618 level.
- Once a trade is entered, the swing is considered "used," and the script resets itself to look for the next valid swing. This is crucial for clean backtesting.
- Enhanced Visualization: The plots for the Fib levels now only appear when a valid setup is being tracked, making the chart much cleaner. It also marks the actual pivots it's using with small triangles for easy verification.
This version should give you much more meaningful and reliable signals based on the classic Fibonacci retracement strategy. Remember to backtest thoroughly on different assets and timeframes.