本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("Liquidity Gravity", "LG", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 1, pyramiding = 0, calc_on_every_tick = false, max_lines_count = 100, max_labels_count = 100)
// Liquidity Gravity
// Every untaken swing high or low is a liquidity pool. Each pool pulls on price, weighted by the
// swings that share it, its distance in ATR, and its age. The balance between upward and downward
// pull is the imbalance, from -1 to +1. The strategy trades toward the heavier side and targets
// the nearest pool there. Educational tool, not financial advice.
// ── Inputs ─────────────────────────────────────────────────────────────────────
string G1 = "Pools"
int pivLen = input.int(5, "Swing length", minval = 2, maxval = 50, group = G1)
float eqTol = input.float(0.10, "Equal-level tolerance (ATR, 0 = off)", minval = 0.0, maxval = 1.0, step = 0.05, group = G1, tooltip = "Swings this close to an existing pool join it and raise its weight.")
int maxPools = input.int(40, "Pools kept per side", minval = 5, maxval = 200, group = G1)
string G2 = "Gravity and entries"
float decay = input.float(4.0, "Distance decay (ATR)", minval = 0.5, maxval = 20.0, step = 0.5, group = G2, tooltip = "Higher: far pools still pull. Lower: only nearby pools matter.")
int ageScale = input.int(100, "Age scale (bars)", minval = 10, maxval = 2000, group = G2, tooltip = "A pool this old carries half the weight of a fresh one.")
int smooth = input.int(3, "Imbalance smoothing", minval = 1, maxval = 50, group = G2)
string entryMode = input.string("Cross", "Entry mode", options = ["Cross", "Level"], group = G2, tooltip = "Cross: only on the bar the imbalance crosses the threshold. Level: any flat bar beyond the threshold and still strengthening (many more trades).")
float entryThr = input.float(0.30, "Entry threshold", minval = 0.05, maxval = 0.95, step = 0.05, group = G2)
float exitThr = input.float(0.30, "Flip-exit threshold", minval = 0.0, maxval = 0.95, step = 0.05, group = G2, tooltip = "Close early when the imbalance swings this far the other way.")
float minPull = input.float(0.4, "Min total pull", minval = 0.0, maxval = 20.0, step = 0.1, group = G2, tooltip = "Ignores readings built on very little liquidity.")
bool needMom = input.bool(false, "Require a candle in trade direction", group = G2)
int cooldown = input.int(10, "Cooldown after exit (bars)", minval = 0, maxval = 100, group = G2)
bool useTrend = input.bool(false, "Trade with EMA trend only", group = G2)
int trendLen = input.int(100, "Trend EMA length", minval = 5, maxval = 500, group = G2)
string G3 = "Risk and exits"
float riskPct = input.float(1.0, "Risk per trade (% of equity)", minval = 0.05, maxval = 10.0, step = 0.05, group = G3)
float maxLev = input.float(2.0, "Max position value (x equity)", minval = 0.1, maxval = 50.0, step = 0.1, group = G3)
string stopMode = input.string("ATR", "Stop mode", options = ["ATR", "Pool"], group = G3, tooltip = "ATR: fixed distance. Pool: just beyond the nearest pool behind price, falling back to ATR if it is too far.")
float stopAtr = input.float(1.2, "ATR stop distance", minval = 0.25, maxval = 10.0, step = 0.25, group = G3)
float maxStop = input.float(3.0, "Max pool-stop distance (ATR)", minval = 0.5, maxval = 10.0, step = 0.25, group = G3)
float stopBuf = input.float(0.20, "Pool-stop buffer (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G3)
float minRR = input.float(1.5, "Min reward:risk to target pool", minval = 0.25, maxval = 5.0, step = 0.05, group = G3, tooltip = "The target is the nearest pool at least this many R away.")
float maxRR = input.float(4.0, "Max reward:risk", minval = 1.0, maxval = 15.0, step = 0.5, group = G3)
bool useFall = input.bool(true, "Fixed-R target when no pool is far enough", group = G3)
float fallRR = input.float(1.5, "Fallback reward:risk", minval = 0.5, maxval = 10.0, step = 0.25, group = G3)
bool beOn = input.bool(true, "Move stop to breakeven", group = G3)
float beR = input.float(1.5, "Breakeven trigger (R)", minval = 0.25, maxval = 5.0, step = 0.25, group = G3)
int maxBars = input.int(60, "Time stop (bars, 0 = off)", minval = 0, maxval = 1000, group = G3)
bool allowLong = input.bool(true, "Allow longs", group = G3)
bool allowShort = input.bool(true, "Allow shorts", group = G3)
string G4 = "Visuals"
bool showCloud = input.bool(true, "Gravity ribbon", group = G4, tooltip = "A line that leans toward the heavier side, with a soft cloud back to the price average.")
float gravMult = input.float(1.0, "Ribbon reach (ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G4)
bool showTrade = input.bool(true, "Draw trade levels (only while a trade is open)", group = G4)
bool tradeLbl = input.bool(false, "Label trade levels", group = G4)
bool showPools = input.bool(true, "Nearest pool lines", group = G4)
bool poolLbl = input.bool(false, "Label nearest pools", group = G4)
bool colBars = input.bool(false, "Colour candles by imbalance", group = G4)
bool showTbl = input.bool(true, "Show panel", group = G4)
string tblPos = input.string("Top right", "Panel corner", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G4)
color colUp = input.color(#00E5FF, "Pull up", group = G4, inline = "c")
color colDn = input.color(#FF4081, "Pull down", group = G4, inline = "c")
color colNeu = input.color(#546E7A, "Neutral", group = G4, inline = "c")
// ── State ──────────────────────────────────────────────────────────────────────
float atr = ta.atr(14)
float emaT = ta.ema(close, trendLen)
var array<float> hiLv = array.new<float>()
var array<int> hiBr = array.new<int>()
var array<int> hiEq = array.new<int>()
var array<float> loLv = array.new<float>()
var array<int> loBr = array.new<int>()
var array<int> loEq = array.new<int>()
var float slL = na
var float tpL = na
var float r0L = na
var float slS = na
var float tpS = na
var float r0S = na
var int lastExit = -1000
// ── Helpers ────────────────────────────────────────────────────────────────────
// Remove pools that price has traded through
f_take(array<float> lv, array<int> bs, array<int> eqs, bool isHigh) =>
if lv.size() > 0
for i = lv.size() - 1 to 0
if isHigh ? high > lv.get(i) : low < lv.get(i)
lv.remove(i)
bs.remove(i)
eqs.remove(i)
true
// Add a confirmed swing: join a nearby pool or start a new one
f_add(array<float> lv, array<int> bs, array<int> eqs, float p, int b, bool isHigh) =>
int j = -1
if eqTol > 0 and not na(atr) and lv.size() > 0
for i = 0 to lv.size() - 1
if math.abs(lv.get(i) - p) <= eqTol * atr
j := i
break
if j >= 0
lv.set(j, isHigh ? math.max(lv.get(j), p) : math.min(lv.get(j), p))
bs.set(j, b)
eqs.set(j, eqs.get(j) + 1)
else
lv.push(p)
bs.push(b)
eqs.push(1)
if lv.size() > maxPools
lv.remove(0)
bs.remove(0)
eqs.remove(0)
true
// Total pull of one side on a reference price
f_pull(array<float> lv, array<int> bs, array<int> eqs, float ref) =>
float s = 0.0
if lv.size() > 0 and atr > 0
for i = 0 to lv.size() - 1
float d = math.abs(lv.get(i) - ref) / (decay * atr)
float a = 1.0 + (bar_index - bs.get(i)) / (ageScale * 1.0)
s += eqs.get(i) * math.exp(-d) / a
s
// Nearest pool above or below ref that is at least minDist away
f_nearMin(array<float> lv, float ref, bool above, float minDist) =>
float r = na
if lv.size() > 0
for i = 0 to lv.size() - 1
float p = lv.get(i)
if above and p - ref >= minDist and (na(r) or p < r)
r := p
else if not above and ref - p >= minDist and (na(r) or p > r)
r := p
r
// Position size from a fixed risk share of equity, capped by position value
f_qty(float riskDist) =>
float cash = strategy.equity * riskPct / 100.0
float byRisk = riskDist > 0 ? cash / (riskDist * syminfo.pointvalue) : 0.0
float byCap = strategy.equity * maxLev / (close * syminfo.pointvalue)
math.max(0.0, math.min(byRisk, byCap))
// Black or white text, whichever reads on the plate colour
f_txt(color plate) =>
(0.299 * color.r(plate) + 0.587 * color.g(plate) + 0.114 * color.b(plate)) > 140 ? color.black : color.white
// Eight-segment bar
f_bar(float val) =>
int filled = math.round(math.min(math.abs(val), 1.0) * 8)
string s = ""
for i = 1 to 8
s += i <= filled ? "█" : "░"
s
// ── Pools and gravity ──────────────────────────────────────────────────────────
f_take(hiLv, hiBr, hiEq, true)
f_take(loLv, loBr, loEq, false)
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
if not na(ph)
f_add(hiLv, hiBr, hiEq, ph, bar_index - pivLen, true)
if not na(pl)
f_add(loLv, loBr, loEq, pl, bar_index - pivLen, false)
float pullUp = f_pull(hiLv, hiBr, hiEq, close)
float pullDn = f_pull(loLv, loBr, loEq, close)
float total = pullUp + pullDn
float raw = total > 0 ? (pullUp - pullDn) / total : 0.0
float imb = ta.ema(raw, smooth)
if strategy.position_size[1] != 0 and strategy.position_size == 0
lastExit := bar_index
// ── Signals ────────────────────────────────────────────────────────────────────
bool flat = strategy.position_size == 0
bool coolOk = bar_index - lastExit >= cooldown
bool enough = total >= minPull and not na(atr)
bool upTrig = entryMode == "Cross" ? (imb > entryThr and imb[1] <= entryThr) : (imb > entryThr and imb > imb[1])
bool dnTrig = entryMode == "Cross" ? (imb < -entryThr and imb[1] >= -entryThr) : (imb < -entryThr and imb < imb[1])
bool longSig = allowLong and flat and coolOk and enough and upTrig and (not needMom or close > open) and (not useTrend or close > emaT)
bool shortSig = allowShort and flat and coolOk and enough and dnTrig and (not needMom or close < open) and (not useTrend or close < emaT)
// ── Entries ────────────────────────────────────────────────────────────────────
if longSig
float stop = close - stopAtr * atr
if stopMode == "Pool"
float sp = f_nearMin(loLv, close, false, 0.0)
if not na(sp) and (close - (sp - stopBuf * atr)) <= maxStop * atr
stop := sp - stopBuf * atr
float risk = close - stop
float tgtP = f_nearMin(hiLv, close, true, minRR * risk)
float tp = na
if risk > 0
if not na(tgtP)
tp := math.min(tgtP, close + maxRR * risk)
else if useFall
tp := close + fallRR * risk
float q = not na(tp) ? f_qty(risk) : 0.0
if q > 0
strategy.entry("Long", strategy.long, qty = q)
slL := stop
tpL := tp
r0L := risk
strategy.exit("Long exit", "Long", stop = slL, limit = tpL)
alert("Liquidity Gravity: long, stop " + str.tostring(stop, format.mintick) + ", target " + str.tostring(tp, format.mintick), alert.freq_once_per_bar_close)
if shortSig
float stop = close + stopAtr * atr
if stopMode == "Pool"
float sp = f_nearMin(hiLv, close, true, 0.0)
if not na(sp) and ((sp + stopBuf * atr) - close) <= maxStop * atr
stop := sp + stopBuf * atr
float risk = stop - close
float tgtP = f_nearMin(loLv, close, false, minRR * risk)
float tp = na
if risk > 0
if not na(tgtP)
tp := math.max(tgtP, close - maxRR * risk)
else if useFall
tp := close - fallRR * risk
float q = not na(tp) ? f_qty(risk) : 0.0
if q > 0
strategy.entry("Short", strategy.short, qty = q)
slS := stop
tpS := tp
r0S := risk
strategy.exit("Short exit", "Short", stop = slS, limit = tpS)
alert("Liquidity Gravity: short, stop " + str.tostring(stop, format.mintick) + ", target " + str.tostring(tp, format.mintick), alert.freq_once_per_bar_close)
// ── Management ─────────────────────────────────────────────────────────────────
if strategy.position_size > 0
if beOn and not na(r0L) and high >= strategy.position_avg_price + beR * r0L
slL := math.max(slL, strategy.position_avg_price)
strategy.exit("Long exit", "Long", stop = slL, limit = tpL)
if imb < -exitThr
strategy.close("Long")
if strategy.position_size < 0
if beOn and not na(r0S) and low <= strategy.position_avg_price - beR * r0S
slS := math.min(slS, strategy.position_avg_price)
strategy.exit("Short exit", "Short", stop = slS, limit = tpS)
if imb > exitThr
strategy.close("Short")
if maxBars > 0 and strategy.opentrades > 0
if bar_index - strategy.opentrades.entry_bar_index(0) >= maxBars
strategy.close_all()
// ── Gravity ribbon ─────────────────────────────────────────────────────────────
float strength = math.min(math.abs(imb), 1.0)
color cDir = imb > 0 ? colUp : imb < 0 ? colDn : colNeu
color cGrad = color.from_gradient(strength, 0.0, 0.8, colNeu, cDir)
float gravLine = ta.ema(hlc3 + imb * atr * gravMult, 5)
float cloudRef = ta.sma(hlc3, 8)
pGrav = plot(showCloud ? gravLine : na, "Gravity line", cGrad, 2, plot.style_linebr)
pRef = plot(showCloud ? cloudRef : na, "Cloud reference", color.new(chart.fg_color, 100), display = display.none)
fill(pGrav, pRef, gravLine, cloudRef, showCloud ? color.new(cDir, 70) : na, showCloud ? color.new(cDir, 96) : na, title = "Gravity cloud")
barcolor(colBars and enough ? cGrad : na, title = "Imbalance candles")
// ── Trade levels: drawn only while a position is open, removed when flat ───────
var line slLn = na
var line enLn = na
var line tpLn = na
var label slLb = na
var label enLb = na
var label tpLb = na
var linefill rkFill = na
var linefill rwFill = na
bool posLong = strategy.position_size > 0
bool inTrade = strategy.position_size != 0
bool newTrade = inTrade and strategy.position_size[1] == 0
float lvSl = posLong ? slL : slS
float lvTp = posLong ? tpL : tpS
float lvEn = strategy.position_avg_price
if not inTrade and not na(slLn)
line.delete(slLn)
line.delete(enLn)
line.delete(tpLn)
label.delete(slLb)
label.delete(enLb)
label.delete(tpLb)
linefill.delete(rkFill)
linefill.delete(rwFill)
slLn := na
enLn := na
tpLn := na
slLb := na
enLb := na
tpLb := na
rkFill := na
rwFill := na
if showTrade and newTrade
slLn := line.new(bar_index, lvSl, bar_index + 1, lvSl, color = colDn, width = 2)
enLn := line.new(bar_index, lvEn, bar_index + 1, lvEn, color = color.new(chart.fg_color, 30), style = line.style_dashed, width = 1)
tpLn := line.new(bar_index, lvTp, bar_index + 1, lvTp, color = colUp, width = 2)
rkFill := linefill.new(slLn, enLn, color.new(colDn, 85))
rwFill := linefill.new(enLn, tpLn, color.new(colUp, 85))
if tradeLbl
slLb := label.new(bar_index + 1, lvSl, "SL", style = label.style_label_left, color = colDn, textcolor = color.white, size = size.tiny)
enLb := label.new(bar_index + 1, lvEn, "Entry", style = label.style_label_left, color = color.new(chart.fg_color, 30), textcolor = f_txt(chart.fg_color), size = size.tiny)
tpLb := label.new(bar_index + 1, lvTp, "TP", style = label.style_label_left, color = colUp, textcolor = color.black, size = size.tiny)
if showTrade and inTrade and not na(slLn)
line.set_xy2(slLn, bar_index, lvSl)
line.set_xy2(enLn, bar_index, lvEn)
line.set_xy2(tpLn, bar_index, lvTp)
if tradeLbl and not na(slLb)
label.set_xy(slLb, bar_index + 1, lvSl)
label.set_xy(enLb, bar_index + 1, lvEn)
label.set_xy(tpLb, bar_index + 1, lvTp)
// ── Nearest pools: last bar only ───────────────────────────────────────────────
var line upLn = na
var line dnLn = na
var label upLb = na
var label dnLb = na
float nearUp = f_nearMin(hiLv, close, true, 0.0)
float nearDn = f_nearMin(loLv, close, false, 0.0)
if barstate.islast and showPools
line.delete(upLn)
line.delete(dnLn)
label.delete(upLb)
label.delete(dnLb)
if not na(nearUp)
upLn := line.new(bar_index - 40, nearUp, bar_index + 3, nearUp, color = color.new(colUp, 40), style = line.style_dashed, width = 1)
if poolLbl
upLb := label.new(bar_index + 3, nearUp, str.tostring(nearUp, format.mintick), style = label.style_label_left, color = color.new(colUp, 15), textcolor = color.black, size = size.tiny)
if not na(nearDn)
dnLn := line.new(bar_index - 40, nearDn, bar_index + 3, nearDn, color = color.new(colDn, 40), style = line.style_dashed, width = 1)
if poolLbl
dnLb := label.new(bar_index + 3, nearDn, str.tostring(nearDn, format.mintick), style = label.style_label_left, color = color.new(colDn, 15), textcolor = color.white, size = size.tiny)
// ── Panel ──────────────────────────────────────────────────────────────────────
string tPos = switch tblPos
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
var table tbl = table.new(tPos, 2, 8, bgcolor = color.new(chart.bg_color, 10), border_width = 1, border_color = color.new(chart.fg_color, 88), frame_width = 1, frame_color = color.new(chart.fg_color, 75))
f_row(int r, string k, string v, color vc) =>
tbl.cell(0, r, k, text_color = color.new(chart.fg_color, 25), text_halign = text.align_left, text_size = size.tiny)
tbl.cell(1, r, v, text_color = vc, text_halign = text.align_right, text_size = size.tiny)
true
if barstate.islast and showTbl
int nTr = strategy.closedtrades
string pf = strategy.grossloss > 0 ? str.tostring(strategy.grossprofit / strategy.grossloss, "0.00") : "—"
string wr = nTr > 0 ? str.tostring(100.0 * strategy.wintrades / nTr, "0") + "%" : "—"
string bias = not enough ? "Neutral" : imb > 0 ? "Up" : imb < 0 ? "Down" : "Neutral"
string pos = strategy.position_size > 0 ? "Long" : strategy.position_size < 0 ? "Short" : "Flat"
tbl.cell(0, 0, "Liquidity Gravity", bgcolor = color.new(cDir, 25), text_color = f_txt(cDir), text_halign = text.align_left, text_size = size.tiny)
tbl.cell(1, 0, bias, bgcolor = color.new(cDir, 25), text_color = f_txt(cDir), text_halign = text.align_right, text_size = size.tiny)
f_row(1, "Imbalance", str.tostring(imb, "0.00") + " " + f_bar(imb), cGrad)
f_row(2, "Pool ▲", na(nearUp) ? "—" : str.tostring((nearUp - close) / atr, "0.0") + " ATR", colUp)
f_row(3, "Pool ▼", na(nearDn) ? "—" : str.tostring((close - nearDn) / atr, "0.0") + " ATR", colDn)
f_row(4, "Position", pos, strategy.position_size > 0 ? colUp : strategy.position_size < 0 ? colDn : color.new(chart.fg_color, 40))
f_row(5, "Net profit", str.tostring(strategy.netprofit, "#.##"), strategy.netprofit >= 0 ? colUp : colDn)
f_row(6, "Win / PF", wr + " / " + pf, chart.fg_color)
f_row(7, "Trades", str.tostring(nTr), chart.fg_color)