本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Moving Average Deviation Rate (Kairi) [Saikix]
// © Saikix
//@version=6
indicator("Moving Average Deviation Rate (Kairi) [Saikix]", shorttitle="Saikix-MA-Deviation", overlay=false, format=format.price, precision=2, max_lines_count=10, max_labels_count=10, behind_chart=false)
G_BASIC = "Basic settings"
maType = input.string("SMA", "Moving average", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "HMA", "VWMA"], inline="ma", group=G_BASIC, display=display.none)
maLen = input.int(20, "", minval=2, maxval=500, inline="ma", group=G_BASIC, display=display.none,
tooltip="Type and length. VWMA needs volume.")
tfIn = input.timeframe("", "Timeframe", group=G_BASIC, display=display.none,
tooltip="Timeframe of the MA. Empty = chart timeframe. A higher timeframe MA is built from its completed bars and the current price, so past bars show what it was at that time. A timeframe lower than the chart uses the chart timeframe.")
unitIn = input.string("Percent", "Distance unit", options=["Percent", "ATR", "Pips"], inline="unit", group=G_BASIC, display=display.none)
atrLen = input.int(14, "", minval=1, maxval=500, inline="unit", group=G_BASIC, display=display.none, active=unitIn == "ATR",
tooltip="How the distance from the MA is measured.\nPercent: (close − MA) ÷ MA × 100.\nATR: (close − MA) ÷ the ATR of the previous bar (length on the right).\nPips: (close − MA) in pips on forex, gold and silver; in price on other markets.")
lookback = input.int(3000, "Lookback (bars)", minval=100, maxval=5000, group=G_BASIC, display=display.none,
tooltip="The Stretched and Extreme levels come from the distance of this many past bars of the MA's timeframe. Bars above the MA and bars below it are measured separately.")
pStr = input.float(90.0, "Levels (%)", minval=50.0, maxval=99.9, step=1.0, inline="lv", group=G_BASIC, display=display.none)
pExt = input.float(98.0, "", minval=50.0, maxval=99.9, step=0.5, inline="lv", group=G_BASIC, display=display.none,
tooltip="Stretched (left) and Extreme (right): the distance from the MA is farther than this percentage of past bars on the same side of the MA.")
G_DISP = "Chart display"
showMa = input.bool(true, "Show MA", group=G_DISP, display=display.none,
tooltip="The MA on the price chart. Gray: normal. Green: Stretched above the MA. Red: Stretched below the MA. Thicker: Extreme.")
showLv = input.bool(true, "Show Stretched and Extreme prices", group=G_DISP, display=display.none,
tooltip="Dashed lines at the price where a close would be Stretched or Extreme, on the side of the MA the price is on now.")
showTable = input.bool(true, "Show summary", group=G_DISP, display=display.none)
G_STYLE = "Colors and text"
normCol = input.color(#787B86, "Colors", inline="col", group=G_STYLE, display=display.none)
upCol = input.color(#089981, "", inline="col", group=G_STYLE, display=display.none)
dnCol = input.color(#F23645, "", inline="col", group=G_STYLE, display=display.none,
tooltip="Normal, stretched above the MA, stretched below the MA. Used for the MA, the distance line, the levels, the prices and the summary.")
lineW = input.int(2, "Line width", minval=1, maxval=5, group=G_STYLE, display=display.none,
tooltip="Width of the MA and the distance line. Extreme is drawn twice as thick.")
txtSize = input.int(13, "Text size", minval=8, maxval=30, group=G_STYLE, display=display.none)
tblPos = input.string("Top right", "Summary position", options=["Top right", "Top left", "Bottom right", "Bottom left"], group=G_STYLE, display=display.none)
G_ALERT = "Alerts"
alStr = input.bool(true, "Stretched", group=G_ALERT, display=display.none,
tooltip="Create the alert with \"Any alert() function call\". Sent at bar close.\nStretched: the distance becomes Stretched on either side.")
alExt = input.bool(true, "Extreme", group=G_ALERT, display=display.none, tooltip="The distance becomes Extreme.")
alBack = input.bool(false, "Back to normal", group=G_ALERT, display=display.none, tooltip="After Stretched or Extreme, the distance comes back inside the Stretched level.")
alCross = input.bool(false, "MA cross", group=G_ALERT, display=display.none, tooltip="The close crosses the MA.")
MIN_N = 50
fmtP(float p) => str.tostring(p, format.mintick)
tfLabel(string tf) =>
int sec = timeframe.in_seconds(tf)
sec < 3600 ? str.tostring(math.round(sec / 60.0), "#") + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600.0), "#") + "h" : sec < 604800 ? "D" : sec < 2419200 ? "W" : "M"
isPipMarket() =>
string s = str.upper(syminfo.ticker)
syminfo.type == "forex" or str.contains(s, "XAU") or str.contains(s, "GOLD") or str.contains(s, "XAG") or str.contains(s, "SILVER")
pipUnit() =>
string s = str.upper(syminfo.ticker)
str.contains(s, "JPY") ? 0.01 : str.contains(s, "XAU") or str.contains(s, "GOLD") ? 0.1 : str.contains(s, "XAG") or str.contains(s, "SILVER") ? 0.01 : 0.0001
IS_PIP = isPipMarket()
PIP_SZ = IS_PIP ? pipUnit() : 1.0
type Sample
array<float> buf
array<float> up
array<float> dn
newSample() => Sample.new(array.new<float>(), array.new<float>(), array.new<float>())
countBelow(array<float> a, float v) =>
int c = 0
if a.size() > 0
int i = a.binary_search_leftmost(v)
c := i < 0 ? 0 : a.get(i) < v ? i + 1 : i
c
insertSorted(array<float> a, float v) =>
int p = countBelow(a, v)
if p >= a.size()
a.push(v)
else
a.insert(p, v)
removeSorted(array<float> a, float v) =>
int i = a.binary_search(v)
if i >= 0
a.remove(i)
method add(Sample s, float d, int maxN) =>
s.buf.push(d)
if d > 0
insertSorted(s.up, d)
else if d < 0
insertSorted(s.dn, -d)
if s.buf.size() > maxN
float old = s.buf.shift()
if old > 0
removeSorted(s.up, old)
else if old < 0
removeSorted(s.dn, -old)
level(array<float> a, float p) =>
int n = a.size()
n < MIN_N ? na : a.get(math.max(0, math.min(n - 1, int(math.ceil(p / 100.0 * n)) - 1)))
stateOf(float d, float uS, float uE, float lS, float lE) =>
int st = 0
if d > 0
st := not na(uE) and d >= uE ? 2 : not na(uS) and d >= uS ? 1 : 0
else if d < 0
st := not na(lE) and -d >= lE ? -2 : not na(lS) and -d >= lS ? -1 : 0
st
wmaB(float src, simple int k) => ta.wma(src, math.max(1, k - 1))[1] * (k - 1) / (k + 1)
maParts(simple string typ, simple int n) =>
float aE = 2.0 / (n + 1)
float aR = 1.0 / n
int h = math.max(1, math.floor(n / 2))
int s = math.max(1, math.floor(math.sqrt(n)))
float x = 2 * ta.wma(close, h) - ta.wma(close, n)
float bSma = math.sum(close, n - 1)[1] / n
float bEma = (1 - aE) * ta.ema(close, n)[1]
float bRma = (1 - aR) * ta.rma(close, n)[1]
float bWma = wmaB(close, n)
float aHma = (2.0 / (s + 1)) * (2 * (2.0 / (h + 1)) - 2.0 / (n + 1))
float bHma = (2.0 / (s + 1)) * (2 * wmaB(close, h) - wmaB(close, n)) + wmaB(x, s)
float pvSum = math.sum(close * volume, n - 1)[1]
float vSum = math.sum(volume, n - 1)[1]
float a = typ == "SMA" ? 1.0 / n : typ == "EMA" ? aE : typ == "SMMA (RMA)" ? aR : typ == "WMA" ? 2.0 / (n + 1) : typ == "HMA" ? aHma : na
float b = typ == "SMA" ? bSma : typ == "EMA" ? bEma : typ == "SMMA (RMA)" ? bRma : typ == "WMA" ? bWma : typ == "HMA" ? bHma : na
[a, b, pvSum, vSum]
abOf(float a, float b, float pvSum, float vSum, float vol) =>
float d = vol + vSum
float aa = maType == "VWMA" ? vol / d : a
float bb = maType == "VWMA" ? pvSum / d : b
[aa, bb]
distOf(float diff, float ma, float atrPrev) =>
unitIn == "Percent" ? diff / ma * 100 : unitIn == "ATR" ? diff / atrPrev : diff / PIP_SZ
string tf = tfIn == "" or timeframe.in_seconds(tfIn) <= timeframe.in_seconds(timeframe.period) ? timeframe.period : tfIn
bool isHtf = tf != timeframe.period
[a0, b0, pv0, vs0] = maParts(maType, maLen)
float atr0 = ta.atr(atrLen)[1]
var Sample smp0 = newSample()
htfData(simple string typ, simple int len, simple int lb, simple int aLen) =>
[a, b, pv, vs] = maParts(typ, len)
float atrP = ta.atr(aLen)[1]
[aa, bb] = abOf(a, b, pv, vs, volume)
float m = aa * close + bb
float d = distOf(close - m, m, atrP)
var Sample smp = newSample()
array<float> upSnap = smp.up.copy()
array<float> dnSnap = smp.dn.copy()
if not na(d)
smp.add(d, lb)
[upSnap, dnSnap, a, b, pv, vs, atrP]
array<float> upA = smp0.up
array<float> dnA = smp0.dn
float aBase = a0
float bBase = b0
float pvP = pv0
float vsP = vs0
float atrP = atr0
float volNow = volume
var float htfVol = 0.0
if isHtf
[hu, hd, ha, hb, hpv, hvs, hatr] = request.security(syminfo.tickerid, tf, htfData(maType, maLen, lookback, atrLen), lookahead=barmerge.lookahead_on)
upA := hu
dnA := hd
aBase := ha
bBase := hb
pvP := hpv
vsP := hvs
atrP := hatr
htfVol := timeframe.change(tf) ? nz(volume) : htfVol + nz(volume)
volNow := htfVol
[aM, bM] = abOf(aBase, bBase, pvP, vsP, volNow)
float ma = aM * close + bM
float dev = distOf(close - ma, ma, atrP)
float uS = level(upA, pStr)
float uE = level(upA, pExt)
float lS = level(dnA, pStr)
float lE = level(dnA, pExt)
int st = stateOf(dev, uS, uE, lS, lE)
int nSide = dev > 0 ? upA.size() : dnA.size()
int below = dev > 0 ? countBelow(upA, dev) : dev < 0 ? countBelow(dnA, -dev) : 0
if not isHtf and barstate.isconfirmed and not na(dev)
smp0.add(dev, lookback)
priceAt(float t) =>
unitIn == "Percent" ? (1 + t / 100) * bM / (1 - (1 + t / 100) * aM) : (bM + t * (unitIn == "ATR" ? atrP : PIP_SZ)) / (1 - aM)
int side = dev >= 0 ? 1 : -1
float pxS = priceAt(side > 0 ? uS : -lS)
float pxE = priceAt(side > 0 ? uE : -lE)
colOf(int s) => s == 0 ? normCol : s > 0 ? upCol : dnCol
sideCol(int s) => s >= 0 ? upCol : dnCol
hline(0, "Zero line", color=color.new(normCol, 40), linestyle=hline.style_dotted)
pUS = plot(uS, "Stretched level (above)", color=color.new(upCol, 30), linewidth=1, linestyle=plot.linestyle_dashed, display=display.pane)
pUE = plot(uE, "Extreme level (above)", color=upCol, linewidth=1, display=display.pane)
pLS = plot(-lS, "Stretched level (below)", color=color.new(dnCol, 30), linewidth=1, linestyle=plot.linestyle_dashed, display=display.pane)
pLE = plot(-lE, "Extreme level (below)", color=dnCol, linewidth=1, display=display.pane)
pDev = plot(dev, "Distance", color=colOf(st), linewidth=lineW)
fill(pDev, pUS, color=dev > uS ? color.new(upCol, 70) : na, title="Stretched fill (above)")
fill(pDev, pUE, color=dev > uE ? color.new(upCol, 40) : na, title="Extreme fill (above)")
fill(pDev, pLS, color=dev < -lS ? color.new(dnCol, 70) : na, title="Stretched fill (below)")
fill(pDev, pLE, color=dev < -lE ? color.new(dnCol, 40) : na, title="Extreme fill (below)")
plot(math.abs(st) == 2 ? dev : na, "Distance (Extreme)", color=sideCol(st), linewidth=lineW * 2, style=plot.style_linebr, display=display.pane, editable=false)
plot(showMa ? ma : na, "MA", color=colOf(st), linewidth=lineW, format=format.price, force_overlay=true)
plot(showMa and math.abs(st) == 2 ? ma : na, "MA (Extreme)", color=sideCol(st), linewidth=lineW * 2, style=plot.style_linebr, display=display.pane, editable=false, force_overlay=true)
distText(float d) =>
float x = math.abs(d)
unitIn == "Percent" ? str.tostring(x, x < 0.1 ? "0.000" : "0.00") + "%" : unitIn == "ATR" ? str.tostring(x, "0.00") + " ATR" : IS_PIP ? str.tostring(x, "0.0") + " pips" : str.tostring(x, format.mintick)
sideWord(float d) => d >= 0 ? "above" : "below"
maShort() => maType == "SMMA (RMA)" ? "SMMA" : maType
maName() => (isHtf ? tfLabel(tf) + " " : "") + maShort() + " " + str.tostring(maLen)
devText(float d) => distText(d) + " " + sideWord(d) + " " + maName()
stateWord(int s) => math.abs(s) == 2 ? "Extreme" : math.abs(s) == 1 ? "Stretched" : ""
var line lnS = na
var line lnE = na
var label lbS = na
var label lbE = na
if barstate.islast
line.delete(lnS)
line.delete(lnE)
label.delete(lbS)
label.delete(lbE)
if showLv and not na(pxS) and not na(pxE)
int x0 = math.max(0, bar_index - 30)
color c = side > 0 ? upCol : dnCol
lnS := line.new(x0, pxS, bar_index, pxS, style=line.style_dashed, color=color.new(c, 30), width=1, force_overlay=true)
lnE := line.new(x0, pxE, bar_index, pxE, style=line.style_dashed, color=c, width=1, force_overlay=true)
lbS := label.new(bar_index, pxS, "Stretched " + fmtP(pxS), style=side > 0 ? label.style_label_upper_right : label.style_label_lower_right, color=color.new(c, 30), textcolor=color.white, size=math.max(8, txtSize - 1), force_overlay=true)
lbE := label.new(bar_index, pxE, "Extreme " + fmtP(pxE), style=side > 0 ? label.style_label_upper_right : label.style_label_lower_right, color=c, textcolor=color.white, size=math.max(8, txtSize - 1), force_overlay=true)
var table tbl = table.new(tblPos == "Top left" ? position.top_left : tblPos == "Bottom right" ? position.bottom_right : tblPos == "Bottom left" ? position.bottom_left : position.top_right, 1, 3, bgcolor=chart.bg_color, border_color=chart.bg_color, border_width=3, force_overlay=true)
if barstate.islast and showTable
table.clear(tbl, 0, 0, 0, 2)
string w = stateWord(st)
table.cell(tbl, 0, 0, na(dev) ? "Not enough bars yet" : devText(dev) + (w == "" ? "" : " · " + w), text_color=color.white, bgcolor=colOf(st), text_size=txtSize, text_halign=text.align_left)
string r1 = na(dev) ? "" : nSide < MIN_N ? "Not enough past bars yet" : below >= nSide ? "Farther than all past bars" : "Farther than " + str.tostring(math.floor(100.0 * below / nSide), "#") + "% of past bars"
table.cell(tbl, 0, 1, r1, text_color=chart.fg_color, text_size=txtSize - 1, text_halign=text.align_left)
if not na(pxS) and not na(pxE)
string sw = side > 0 ? " above " : " below "
table.cell(tbl, 0, 2, "Stretched" + sw + fmtP(pxS) + " · Extreme" + sw + fmtP(pxE), text_color=side > 0 ? upCol : dnCol, text_size=txtSize - 1, text_halign=text.align_left)
var int pst = 0
var float pdv = na
if barstate.isconfirmed
string head = "[Saikix-MA-Deviation] " + syminfo.ticker + " " + tfLabel(timeframe.period) + " "
string tail = ". Price: " + fmtP(close)
bool flip = st != 0 and pst != 0 and math.sign(st) != math.sign(pst)
bool entExt = math.abs(st) == 2 and (math.abs(pst) < 2 or flip)
bool entStr = math.abs(st) >= 1 and (pst == 0 or flip)
if alExt and entExt
alert(head + "Extreme: " + devText(dev) + tail, alert.freq_once_per_bar_close)
else if alStr and entStr
alert(head + "Stretched: " + devText(dev) + tail, alert.freq_once_per_bar_close)
if alBack and st == 0 and pst != 0
alert(head + "Back to normal: " + devText(dev) + tail, alert.freq_once_per_bar_close)
if alCross and not na(pdv) and not na(dev) and dev != 0 and math.sign(dev) != math.sign(pdv)
alert(head + "MA cross: close " + sideWord(dev) + " " + maName() + " (" + fmtP(ma) + ")" + tail, alert.freq_once_per_bar_close)
pst := st
pdv := dev