Liquidations by volume (spot/futures)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Thomas_Davison

//@version=5
indicator("Liquidations by volume")

// uses the difference in volume between a spot market and a futures market to determine possible liquidations that might have taken place

// the calculation is simple: histogram bar value = futures volume - spot volume

// NOTES:   - markets used should have the same volume equivalent i.e. volume for BTCUSDT should be measured in BTC for both spot and futures markets, some futures markets use contracts worth different amounts meaning values will differ greatly.
//          - negative values will been removed as they dont show relevant data to this indicator
//          - all values while calculated accurately, are given to interpretation, as not all of the volume difference seen on a futures market is due to liquidations. Traders making trades within a single candle time period will skew the data.


longLiqCol = input.color(title="Long liquidations", defval = color.red)
shortLiqCol = input.color(title="Short liquidations", defval = color.green)
removeBelowMean = input.bool(title="Remove below average volume differences?", defval = true)
timePeriodMean = input.int(title="bars used in mean calculation", defval = 100)
assetFutures = input.symbol(title="Futures symbol", defval = "binance:btcusdtperp")
plotFutures = input.bool(title="Plot futures market volume?", defval = false)
futuresVolCol = input.color(title="futures volume", defval = color.blue)
assetSpot = input.symbol(title="Spot symbol", defval = "binance:btcusdt")
plotSpot = input.bool(title="Plot spot market volume?", defval = false)
spotVolCol = input.color(title="spot volume", defval = color.yellow)
    
spotVolume = request.security(assetSpot,timeframe.period,volume)
futuresVolume = request.security(assetFutures,timeframe.period,volume)

difference = futuresVolume - spotVolume
direction = close > open ? shortLiqCol : longLiqCol

differenceSum = math.sum(difference, timePeriodMean)
differenceMean = differenceSum / timePeriodMean

if removeBelowMean and difference < differenceMean or difference < 0
    difference := 0
    
plot(difference, linewidth = 2, color = direction, style = plot.style_histogram)
plot(plotSpot ? spotVolume : na, color=spotVolCol)
plot(plotFutures ? futuresVolume: na, color=futuresVolCol)
