Mr. Love Algo Trend

maxjede · study · 315 行 · 点赞 15 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Mr. Love Algo Trend
// ATR-Ratchet-Trendsystem mit CTA-inspiriertem Daily-Trend-Kontext und
// hypothetischer Wave-Simulation.
// Wave kalibriert Bar für Bar auf CAPITALCOM:US500 (1D) und NYSE:NKE (8h), Okt 2026.
// Keine Anlageberatung, keine Fonds-/CTA-Replikation.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Mr. Love Algo Trend", shorttitle = "Mr. Love Algo Trend", overlay = true, max_labels_count = 50)
 
// ═══ Inputs ══════════════════════════════════════════════════════════════════
string gWave = "WAVE"
string profile    = input.string("42", "Wave Profile", options = ["21", "42", "84", "Custom"], group = gWave,
     tooltip = "Presets: 42 = kalibrierter Standard (Basis EMA 34, ATR 11, Vola-Referenz 42, 1.3 / 1.0). 21/84 = halbe/doppelte Geschwindigkeit. Custom nutzt die Felder darunter.")
string cSmooth    = input.string("EMA", "Custom Wave Smoothing", options = ["EMA", "SMA", "WMA", "RMA", "HMA"], group = gWave)
float  cMult      = input.float(1.3, "Custom Base Wave ATR Multiplier", minval = 0.1, step = 0.05, group = gWave,
     tooltip = "Bandbreite = Multiplier × ATR × (ATR / Referenz-ATR)^Adaptation")
float  cAdapt     = input.float(1.0, "Custom Volatility Adaptation", minval = 0.0, maxval = 3.0, step = 0.05, group = gWave,
     tooltip = "0 = statisches ATR-Band. Höher = Band weitet sich stärker, wenn die kurzfristige ATR über der Referenz-ATR liegt.")
int    cWaveLen   = input.int(42, "Custom Wave Length (Vol-Referenz)", minval = 5, group = gWave)
int    cBasisLen  = input.int(34, "Custom Basis Length", minval = 2, group = gWave)
int    cAtrLen    = input.int(11, "Custom ATR Length", minval = 1, group = gWave)
 
string gDaily = "DAILY TREND"
string maDisplay  = input.string("Off", "Daily Trend MA Display", options = ["Off", "All", "Fast + Tactical", "Core + Anchor + Macro"], group = gDaily)
int    lenF       = input.int(20,  "Fast",     minval = 2, group = gDaily, inline = "d1")
int    lenT       = input.int(50,  "Tactical", minval = 2, group = gDaily, inline = "d1")
int    lenC       = input.int(100, "Core",     minval = 2, group = gDaily, inline = "d2")
int    lenA       = input.int(200, "Anchor",   minval = 2, group = gDaily, inline = "d2")
int    lenM       = input.int(250, "Macro",    minval = 2, group = gDaily, inline = "d3")
bool   dtOnHtf    = input.bool(true, "Daily Trend auch auf Weekly/Monthly", group = gDaily,
     tooltip = "Aus = wie das Original: auf Charts > 1D wird der Daily-Kontext als 'Unavailable' ausgewiesen.")
 
string gStyle = "STIL"
bool   showWave   = input.bool(true, "Show Trend Wave", group = gStyle)
string shadowMode = input.string("Adaptive", "Wave Shadow Mode", options = ["Adaptive", "Solid", "Off"], group = gStyle,
     tooltip = "Adaptive: Schatten wird kräftiger, je weiter der Kurs von der Wave entfernt ist.")
color  bullShadow = input.color(#4CAF50, "Bull Shadow Color", group = gStyle)
color  bearShadow = input.color(#801922, "Bear Shadow Color", group = gStyle)
color  waveUpCol  = input.color(#089981, "Wave Up Color", group = gStyle)
color  waveDnCol  = input.color(#B23A48, "Wave Down Color", group = gStyle)
bool   showTag    = input.bool(true, "Show Active Trend Tag", group = gStyle)
int    tagOffset  = input.int(9, "Tag Offset Bars", minval = 0, maxval = 400, group = gStyle)
string tagSizeIn  = input.string("Small", "Tag Size", options = ["Tiny", "Small", "Normal", "Large"], group = gStyle)
int    tagTransp  = input.int(75, "Tag Background Transparency", minval = 0, maxval = 100, group = gStyle)
color  tagTextCol = input.color(color.white, "Tag Text Color", group = gStyle)
color  tagBullCol = input.color(#39FF14, "Tag Bull Color", group = gStyle)
color  tagBearCol = input.color(#FF3B30, "Tag Bear Color", group = gStyle)
bool   tagTraffic = input.bool(true,  "Tag: Show Traffic State", group = gStyle)
bool   tagXScore  = input.bool(false, "Tag: Show Trend xScore", group = gStyle)
bool   tagPosMode = input.bool(false, "Tag: Show Position Mode", group = gStyle)
bool   tagStruct  = input.bool(true,  "Tag: Show Wave Structure", group = gStyle)
bool   tagCTA     = input.bool(true,  "Tag: Show CTA Exposure", group = gStyle)
bool   tagPct     = input.bool(true,  "Tag: Show Wave Percentile", group = gStyle)
float  tol        = input.float(0.25, "Balanced Tolerance ATR", minval = 0.0, step = 0.05, group = gStyle,
     tooltip = "Abstand in ATR, unter dem Wave-Struktur als 'Testing' und Daily-Horizonte als 'Flat' gelten.")
int    pctLen     = input.int(100, "Wave Percentile Lookback", minval = 10, group = gStyle)
 
string gSim = "WAVE SIMULATION"
string posMode    = input.string("Long Only", "Wave Position Mode", options = ["Long Only", "Long/Short", "Short Only"], group = gSim)
string simStart   = input.string("Since Date", "Simulation Start", options = ["Since Date", "Full History"], group = gSim)
int    sinceDate  = input.time(timestamp("2019-01-01T00:00:00"), "Since Date", group = gSim)
float  capital    = input.float(25000, "Starting Capital", minval = 1, group = gSim, inline = "cap")
string ccy        = input.string("EUR", "", group = gSim, inline = "cap")
float  friction   = input.float(0.15, "Total Roundtrip Friction %", minval = 0.0, step = 0.01, group = gSim)
 
string gCock = "COCKPIT"
bool   showCockpit = input.bool(false, "Show Hypothetical Simulation Cockpit", group = gCock)
string cockpitIn   = input.string("Top Right", "Cockpit Position", options = ["Top Right", "Top Left", "Middle Right", "Bottom Right", "Bottom Left"], group = gCock)
 
// ═══ Profile ═════════════════════════════════════════════════════════════════
int    basisLen = profile == "21" ? 17 : profile == "42" ? 34 : profile == "84" ? 68 : cBasisLen
int    refLen   = profile == "21" ? 21 : profile == "42" ? 42 : profile == "84" ? 84 : cWaveLen
int    atrLen   = profile == "21" ? 7  : profile == "42" ? 11 : profile == "84" ? 21 : cAtrLen
float  mult     = profile == "Custom" ? cMult  : 1.3
float  adapt    = profile == "Custom" ? cAdapt : 1.0
string smooth   = profile == "Custom" ? cSmooth : "EMA"
 
// ═══ Helpers ═════════════════════════════════════════════════════════════════
f_tanh(float x) =>
    float xc = math.max(math.min(x, 20.0), -20.0)
    float e2 = math.exp(2.0 * xc)
    (e2 - 1.0) / (e2 + 1.0)
 
f_ma(float src, simple int len, simple string typ) =>
    float e = ta.ema(src, len)
    float s = ta.sma(src, len)
    float w = ta.wma(src, len)
    float r = ta.rma(src, len)
    float h = ta.hma(src, len)
    typ == "SMA" ? s : typ == "WMA" ? w : typ == "RMA" ? r : typ == "HMA" ? h : e
 
f_pct(float x) =>
    na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x * 100, "0.0") + "%"
 
f_horizon(string name, float spreadAtr) =>
    na(spreadAtr) ? name + " n/a" : spreadAtr > tol ? name + " Up" : spreadAtr < -tol ? name + " Down" : name + " Flat"
 
f_vote(float spreadAtr) =>
    na(spreadAtr) ? 0 : spreadAtr > tol ? 1 : spreadAtr < -tol ? -1 : 0
 
// Daily-Trend-Engine (läuft im Daily-Kontext via request.security)
f_daily(simple int lF, simple int lT, simple int lC, simple int lA, simple int lM) =>
    float a   = ta.atr(14)
    float mF  = ta.ema(close, lF)
    float mT  = ta.ema(close, lT)
    float mC  = ta.ema(close, lC)
    float mA  = ta.ema(close, lA)
    float mM  = ta.ema(close, lM)
    float k   = 0.25
    // Horizonte = MA-Spreads, vol-normiert (ATR × √Länge); Pulse = Kurs vs. Fast-MA in ATR
    float sF  = f_tanh((mF - mT) / (a * k * math.sqrt(lT)))
    float sM  = f_tanh((mT - mC) / (a * k * math.sqrt(lC)))
    float sS  = 0.5 * (f_tanh((mC - mA) / (a * k * math.sqrt(lA))) + f_tanh((mA - mM) / (a * k * math.sqrt(lM))))
    float cmp = (0.2 * sF + 0.3 * sM + 0.35 * sS) / 0.85
    float rdy = bar_index >= lM ? 1.0 : 0.0
    [mF, mT, mC, mA, mM, cmp, (close - mF) / a, (mF - mT) / a, (mT - mC) / a, (mC - mM) / (2.0 * a), rdy]
 
// ═══ Wave ════════════════════════════════════════════════════════════════════
float basis = f_ma(close, basisLen, smooth)
float atrS  = ta.rma(ta.tr(true), atrLen)
float atrL  = ta.rma(ta.tr(true), refLen)
float band  = mult * atrS * math.pow(atrS / atrL, adapt)
float lo    = basis - band
float up    = basis + band
 
var float wave = na
var int   dir  = 1
if not na(lo)
    if na(wave)
        wave := lo
        dir  := 1
    else if dir == 1
        wave := math.max(wave, lo)
        if close < wave
            dir := -1
    else
        wave := math.min(wave, up)
        if close > wave
            dir := 1
 
bool flipUp   = dir == 1 and dir[1] == -1
bool flipDown = dir == -1 and dir[1] == 1
 
// Struktur & Perzentil
float distN    = na(wave) ? na : (close - wave) * dir / atrS
float pctRank  = ta.percentrank(distN, pctLen)
string structTxt = distN > tol ? "Supported" : distN >= -tol ? "Testing" : "Breaking"
int   slopeDir = basis > basis[5] ? 1 : basis < basis[5] ? -1 : 0
string trendRel = slopeDir == dir ? "With trend" : slopeDir == 0 ? "Flat basis" : "Counter trend"
 
// ═══ Daily Trend / CTA ═══════════════════════════════════════════════════════
[dF, dT, dC, dA, dM, dComp, dPul, dHF, dHM, dHS, dRdy] = request.security(syminfo.tickerid, "D", f_daily(lenF, lenT, lenC, lenA, lenM), lookahead = barmerge.lookahead_off)
bool   dtReady  = dRdy == 1.0 and not na(dComp) and (dtOnHtf or timeframe.in_seconds() <= 86400)
// xScore = richtungsneutrale Trendstärke 0–100, Richtung separat über das Vorzeichen
float  dXs      = dtReady ? 100.0 * math.pow(math.abs(dComp), 0.6) : na
int    dtDir    = not dtReady ? 0 : dComp > 0.1 ? 1 : dComp < -0.1 ? -1 : 0
string strength = not dtReady ? "n/a" : dXs >= 75 ? "Strong" : dXs >= 60 ? "Moderate" : "Low"
int    vF       = f_vote(dHF)
int    vM       = f_vote(dHM)
int    vS       = f_vote(dHS)
int    netVote  = vF + vM + vS
int    pulVote  = f_vote(dPul)
// CTA: je Horizont ±25 %, Pulse (Kurs vs. Fast-MA) gibt die letzten 25 % nur in Trendrichtung frei
int    ctaExp   = dtReady ? 25 * netVote + (netVote != 0 and pulVote == (netVote > 0 ? 1 : -1) ? 25 * pulVote : 0) : na
bool   allAlign = vF == dir and vM == dir and vS == dir
string traffic  = not dtReady ? "Unavailable" : dtDir == 0 ? "Neutral" : dtDir != dir ? "Conflict" : strength == "Strong" ? "Strong" : strength == "Moderate" ? "Mixed" : "Weak"
string ctxDetail = not dtReady ? "Daily Trend not ready" : dtDir == 0 ? "No clear Daily Trend" : dtDir != dir ? "Daily Trend opposes Wave" : strength == "Strong" ? (allAlign ? "Full support" : "Partial support") : strength + " Daily Trend score"
 
// ═══ Plots ═══════════════════════════════════════════════════════════════════
pBasis = plot(showWave ? basis : na, "Wave Basis", color.new(color.gray, 55), 1)
pWave  = plot(showWave ? wave : na, "Trend Wave", dir == 1 ? waveUpCol : waveDnCol, 2)
 
float shStrength = na(wave) ? 0.0 : math.min(math.abs(close - wave) / (2.0 * band), 1.0)
float strongTr = shadowMode == "Adaptive" ? 88.0 - 38.0 * shStrength : 72.0
color shCol    = dir == 1 ? bullShadow : bearShadow
color nearWave = shadowMode == "Off" ? na : color.new(shCol, strongTr)
color nearBase = shadowMode == "Off" ? na : color.new(shCol, 96)
bool  waveTop  = wave >= basis
fill(pBasis, pWave, math.max(basis, wave), math.min(basis, wave), waveTop ? nearWave : nearBase, waveTop ? nearBase : nearWave, "Wave Shadow")
 
bool showFT  = maDisplay == "All" or maDisplay == "Fast + Tactical"
bool showCAM = maDisplay == "All" or maDisplay == "Core + Anchor + Macro"
plot(showFT  ? dF : na, "Daily Trend Fast",     #2962FF, 1)
plot(showFT  ? dT : na, "Daily Trend Tactical", #00BCD4, 1)
plot(showCAM ? dC : na, "Daily Trend Core",     #FFB300, 1)
plot(showCAM ? dA : na, "Daily Trend Anchor",   #FF6D00, 2)
plot(showCAM ? dM : na, "Daily Trend Macro",    #AB47BC, 2)
 
// ═══ Simulation (hypothetisch, Ausführung zum nächsten Open) ═════════════════
float target = posMode == "Long Only" ? (dir == 1 ? 1.0 : 0.0) : posMode == "Short Only" ? (dir == -1 ? -1.0 : 0.0) : (dir == 1 ? 1.0 : -1.0)
 
var bool  started    = false
var float eq         = na
var float pos        = 0.0
var float tgtPrev    = 0.0
var float entryEq    = na
var float peak       = na
var float maxDD      = 0.0
var float startPrice = na
var int   startTime  = na
var int   trades     = 0
var int   wins       = 0
var int   barsIn     = 0
var int   barsTot    = 0
 
bool startOk = simStart == "Full History" or time >= sinceDate
if not started
    if not na(wave) and startOk
        started    := true
        eq         := capital
        peak       := capital
        startPrice := close
        startTime  := time
else
    eq := eq * (1 + pos * (open / close[1] - 1))
    if tgtPrev != pos
        eq := eq * (1 - math.abs(tgtPrev - pos) * friction / 200)
        if pos != 0
            trades += 1
            if eq > entryEq
                wins += 1
        if tgtPrev != 0
            entryEq := eq
        pos := tgtPrev
    eq := eq * (1 + pos * (close / open - 1))
    barsTot += 1
    if pos != 0
        barsIn += 1
    peak  := math.max(peak, eq)
    maxDD := math.max(maxDD, 1 - eq / peak)
if started
    tgtPrev := target
 
string tgtTxt = target > 0 ? "+100% long" : target < 0 ? "-100% short" : "Flat"
 
// ═══ Tag & Tooltip ═══════════════════════════════════════════════════════════
var label tag = na
if barstate.islast and showTag and not na(wave)
    string ctaTag  = not dtReady ? "CTA Invalid" : ctaExp > 0 ? "CTA +" + str.tostring(ctaExp) + "L" : ctaExp < 0 ? "CTA " + str.tostring(ctaExp) + "S" : "CTA 0"
    string ctaLong = not dtReady ? "N/A" : ctaExp > 0 ? "+" + str.tostring(ctaExp) + "% long" : ctaExp < 0 ? str.tostring(ctaExp) + "% short" : "0% flat"
    string pTxt    = na(pctRank) ? "P-" : "P" + str.tostring(math.round(pctRank))
 
    array<string> l1 = array.new<string>()
    if tagCTA
        l1.push(ctaTag)
    if tagXScore
        l1.push(dtReady ? "xS " + str.tostring(math.round(dXs)) : "xS N/A")
    if tagPosMode
        l1.push(posMode)
    array<string> l2 = array.new<string>()
    if tagTraffic
        l2.push(traffic)
    if tagStruct
        l2.push(structTxt)
    if tagPct
        l2.push(pTxt)
    string line1 = l1.join(" | ")
    string line2 = l2.join(" | ")
    string txt   = line1 == "" ? line2 : line2 == "" ? line1 : line1 + "\n" + line2
 
    string ctxTxt = "Context: " + traffic + " | " + ctxDetail
    string wavTxt = "Wave: " + (dir == 1 ? "Up" : "Down") + " | " + structTxt + " | " + pTxt + " " + trendRel
    string dtTxt  = "Daily Trend: " + (not dtReady ? "Invalid" : dtDir == 1 ? "Up" : dtDir == -1 ? "Down" : "Neutral") + " | CTA: " + ctaLong
    string hzTxt  = "Horizons: " + (dtReady ? f_horizon("Fast", dHF) + " | " + f_horizon("Medium", dHM) + " | " + f_horizon("Slow", dHS) : "Unavailable (Invalid)")
    string xsTxt  = "Trend xScore: " + (dtReady ? str.tostring(math.round(dXs)) + " / 100" : "Invalid")
    string simTxt = "Simulation: Wave | " + posMode + " | Next-open target: " + tgtTxt
    string tip    = "Mr. Love Algo Trend Context\n" + ctxTxt + "\n" + wavTxt + "\n" + dtTxt + "\n" + hzTxt + "\n" + xsTxt + "\n" + simTxt + "\n\nCTA-inspired single-symbol context; not a fund/portfolio replication or trade instruction."
 
    color  tc = dir == 1 ? tagBullCol : tagBearCol
    string sz = tagSizeIn == "Tiny" ? size.tiny : tagSizeIn == "Normal" ? size.normal : tagSizeIn == "Large" ? size.large : size.small
    label.delete(tag)
    tag := label.new(bar_index + tagOffset, wave, txt, color = color.new(tc, tagTransp), style = label.style_label_left,
         textcolor = tagTextCol, size = sz, textalign = text.align_center, tooltip = tip)
 
// ═══ Cockpit ═════════════════════════════════════════════════════════════════
var table cockpit = na
if barstate.islast and showCockpit and started
    string cp = cockpitIn == "Top Left" ? position.top_left : cockpitIn == "Middle Right" ? position.middle_right : cockpitIn == "Bottom Right" ? position.bottom_right : cockpitIn == "Bottom Left" ? position.bottom_left : position.top_right
    if na(cockpit)
        cockpit := table.new(cp, 2, 13, bgcolor = color.new(#131722, 8), border_color = color.new(color.gray, 75), border_width = 1)
        table.merge_cells(cockpit, 0, 0, 1, 0)
    float years = (time - startTime) / (365.25 * 86400000.0)
    float cagr  = years > 0 ? math.pow(eq / capital, 1 / years) - 1 : na
    float bh    = close / startPrice - 1
    color tcol  = color.new(color.white, 10)
    table.cell(cockpit, 0, 0, "Hypothetical Wave Simulation", text_color = tcol, text_size = size.small)
    table.cell(cockpit, 0, 1, "Mode",           text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 1, posMode,          text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 2, "Since",          text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 2, str.format_time(startTime, "yyyy-MM-dd", syminfo.timezone), text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 3, "Start capital",  text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 3, str.tostring(capital, "#,##0") + " " + ccy, text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 4, "Equity",         text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 4, str.tostring(eq, "#,##0") + " " + ccy, text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 5, "Net return",     text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 5, f_pct(eq / capital - 1), text_color = eq >= capital ? waveUpCol : waveDnCol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 6, "Buy & Hold",     text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 6, f_pct(bh),        text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 7, "CAGR",           text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 7, f_pct(cagr),      text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 8, "Max drawdown",   text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 8, f_pct(-maxDD),    text_color = waveDnCol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 9, "Closed trades",  text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 9, str.tostring(trades), text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 10, "Win rate",      text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 10, trades > 0 ? str.tostring(100.0 * wins / trades, "0.0") + "%" : "n/a", text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 11, "Time in market", text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 11, barsTot > 0 ? str.tostring(100.0 * barsIn / barsTot, "0.0") + "%" : "n/a", text_color = tcol, text_size = size.small, text_halign = text.align_right)
    table.cell(cockpit, 0, 12, "Next-open target", text_color = tcol, text_size = size.small, text_halign = text.align_left)
    table.cell(cockpit, 1, 12, tgtTxt,          text_color = target > 0 ? waveUpCol : target < 0 ? waveDnCol : tcol, text_size = size.small, text_halign = text.align_right)
 
// ═══ Alerts ══════════════════════════════════════════════════════════════════
alertcondition(flipUp,   "Wave flip up",   "Trend Wave flipped UP on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(flipDown, "Wave flip down", "Trend Wave flipped DOWN on {{ticker}} ({{interval}}) at {{close}}")

← 返回列表