How to get the Spread in Pine Script

This lesson demonstrates how to reference the current spread between bid ask prices in Pine Script version 6 and create a conditional filter out of it.

Check out my other free lessons!

Source Code

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// @version=6
indicator("TheArtOfTrading.com", overlay=true)

// Import library
import ZenAndTheArtOfTrading/ZenLibrary/9 as zen

// User input 
float maxSpread = input.float(2.0, "Max Spread")

// Get spread data
float askPrice = request.security(syminfo.tickerid, "1T", ask)
float bidPrice = request.security(syminfo.tickerid, "1T", bid)
float spread = zen.toWhole(askPrice - bidPrice)

// Check spread 
bool isSpreadHigh = spread > maxSpread

// Display spread data
plot(askPrice, color=color.red)
plot(bidPrice, color=color.lime)
plot(spread, display=display.status_line)

// Highlight chart 
bgcolor(isSpreadHigh ? color.new(color.red, 50) : na)