Martingale Blow-up Demo

mm_mitsuya · strategy · 264 行 · 点赞 2 · TradingView 原页

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

Pine Script

//@version=6
// Educational strategy: shows why martingale looks attractive and why it eventually blows up.
// Default properties are deliberately documented in the description (incl. why pyramiding = 20).
strategy("Martingale Blow-up Demo", shorttitle = "Martingale Demo", overlay = true,
     pyramiding = 20, initial_capital = 10000, currency = currency.NONE,
     default_qty_type = strategy.fixed, default_qty_value = 1,
     commission_type = strategy.commission.percent, commission_value = 0.02,
     slippage = 100, margin_long = 5, margin_short = 5,
     process_orders_on_close = false, calc_on_every_tick = false, calc_on_order_fills = false,
     max_labels_count = 50)
 
// 証拠金率(%)。strategy() の margin_long と同じ値にしておく(清算価格の計算に使う)
const float MARGIN_PCT = 5.0
 
// ─────────────────────────────────────────────
// 列挙型
// ─────────────────────────────────────────────
enum EntryLogic
    always = "Always (no signal)"
    macd   = "MACD trend shift"
    stoch  = "Stoch RSI cross-up"
    atr    = "ATR channel"
 
enum SizeMode
    pct  = "% of equity"
    usdt = "Fixed amount"
    qty  = "Fixed quantity"
 
enum AddBase
    last = "From last fill"
    avg  = "From average price"
 
// ─────────────────────────────────────────────
// 入力
// ─────────────────────────────────────────────
string G1 = "Entry"
EntryLogic entryLogic = input.enum(EntryLogic.always, "First entry logic", group = G1)
 
string G2 = "Position size"
SizeMode sizeMode  = input.enum(SizeMode.pct, "Size mode", group = G2)
float    sizeValue = input.float(5.0, "First size", minval = 0.00000001, step = 0.1, group = G2,
     tooltip = "Read as % of equity, a fixed amount, or a fixed quantity depending on Size mode. The first size is fixed when the position opens; every add is first size × multiplier^round.")
 
string G3 = "Martingale"
AddBase addBase    = input.enum(AddBase.last, "Add spacing measured", group = G3)
float   addStepPct = input.float(1.5, "Add spacing (%)", minval = 0.1, step = 0.1, group = G3)
float   mult       = input.float(2.0, "Size multiplier", minval = 1.0, step = 0.1, group = G3)
int     maxRounds  = input.int(20, "Max rounds (incl. first)", minval = 1, maxval = 20, group = G3)
float   maxLev     = input.float(20.0, "Max exposure (× equity)", minval = 0.1, maxval = 100.0 / MARGIN_PCT, step = 0.1, group = G3,
     tooltip = "An add is skipped (cap reached) if the position after the add would exceed equity × this value. With 5% margin the broker allows at most 20×.")
 
string G4 = "Exit"
float tpPct        = input.float(1.0, "Take profit (%)", minval = 0.05, step = 0.05, group = G4)
float trailPct     = input.float(0.0, "Ratchet trail (%)  0 = take profit immediately", minval = 0.0, step = 0.05, group = G4,
     tooltip = "Once the take-profit level is reached, trailing starts and the position closes on a close that falls this much from the highest close. The trail line never goes below the average price.")
bool  useSurrender = input.bool(false, "Use surrender line (only after cap)", group = G4)
float surrenderPct = input.float(10.0, "Surrender line: below average price (%)", minval = 0.1, step = 0.5, group = G4)
bool  simLiq       = input.bool(true, "Simulate liquidation", group = G4,
     tooltip = "Places a stop at the liquidation price (where equity falls to the 5% margin requirement). If it is hit, everything is closed and the strategy never trades again (bankrupt).")
 
string G5 = "Period"
int startTime = input.time(timestamp("01 Jan 2023 00:00 +0000"), "Start", group = G5,
     tooltip = "The default result in the description starts here. If your chart loads less history, trading starts at the first loaded bar instead.")
int endTime   = input.time(timestamp("31 Dec 2099 23:59 +0000"), "End", group = G5)
 
string G6 = "Display"
bool showLines = input.bool(true, "Average / TP / next add / surrender lines", group = G6)
bool showLiq   = input.bool(true, "Liquidation line", group = G6)
bool showTable = input.bool(true, "Status table", group = G6)
 
// ─────────────────────────────────────────────
// 初回エントリーシグナル
// ─────────────────────────────────────────────
// MACD系:平滑価格(EMA2)がEMA12の上、かつEMA12>EMA26 になった最初の足
float ap        = ta.ema(close, 2)
float fastMa    = ta.ema(ap, 12)
float slowMa    = ta.ema(ap, 26)
bool  macdGreen = fastMa > slowMa and ap > fastMa
bool  macdBuy   = macdGreen and not macdGreen[1]
 
// STO RSI:%K が20超で %D が20を上抜け
float rsiV    = ta.rsi(close, 14)
float stochK  = ta.sma(ta.stoch(rsiV, rsiV, rsiV, 14), 3)
float stochD  = ta.sma(stochK, 3)
bool  dCross  = ta.crossover(stochD, 20)
bool  stoBuy  = stochK > 20 and dCross
 
// ATRチャネル:速い/遅いATRトレイルの差がプラス転換
f_atrTrail(float src, float offset) =>
    var float t = 0.0
    float prev    = nz(t)
    float prevSrc = nz(src[1], src)
    float off     = nz(offset)
    t := src > prev and prevSrc > prev ? math.max(prev, src - off) : src < prev and prevSrc < prev ? math.min(prev, src + off) : src > prev ? src - off : src + off
    t
 
float trail1   = f_atrTrail(close, 0.5 * ta.atr(5))
float trail2   = f_atrTrail(close, 2.3 * ta.atr(10))
float hst      = trail1 - trail2
float hstSig   = ta.ema(hst, 9)
bool  atrGreen = hst > 0 and hst > hstSig
bool  atrRed   = hst < 0 and hst < hstSig
int   bsGreen  = ta.barssince(atrGreen)
int   bsRed    = ta.barssince(atrRed)
bool  atrBear  = not na(bsRed) and (na(bsGreen) or bsRed < bsGreen)
bool  atrBuy   = atrGreen and atrBear[1]
 
bool entrySignal = switch entryLogic
    EntryLogic.macd  => macdBuy
    EntryLogic.stoch => stoBuy
    EntryLogic.atr   => atrBuy
    => true
 
// ─────────────────────────────────────────────
// ポジション状態
// ─────────────────────────────────────────────
bool  inRange  = time >= startTime and time <= endTime
float posQty   = strategy.position_size
bool  inPos    = posQty > 0
int   rounds   = strategy.opentrades
float avgPrice = strategy.position_avg_price
float lastFill = rounds > 0 ? strategy.opentrades.entry_price(rounds - 1) : na
float baseQty  = rounds > 0 ? strategy.opentrades.size(0) : na   // 初回サイズはエントリー時点で固定
 
float newBaseQty = switch sizeMode
    SizeMode.pct  => strategy.equity * sizeValue / 100 / close
    SizeMode.usdt => sizeValue / close
    => sizeValue
 
// 破産判定(直前の決済が清算、または TradingView のマージンコールなら以後は取引しない)
var bool busted  = false
var int  bustT   = na
bool justBusted  = false
if not busted and strategy.closedtrades > 0
    int    li  = strategy.closedtrades - 1
    string xc  = strategy.closedtrades.exit_comment(li)
    string xid = strategy.closedtrades.exit_id(li)
    if xc == "Liquidation" or str.contains(xid, "Margin") or str.contains(xc, "Margin")
        busted     := true
        bustT      := time
        justBusted := true
 
bool canTrade = inRange and strategy.equity > 0 and not busted
 
// 次のナンピン
float refPrice      = addBase == AddBase.last ? lastFill : avgPrice
float nextAddPrice  = inPos ? refPrice * (1 - addStepPct / 100) : na
float nextAddQty    = inPos ? baseQty * math.pow(mult, rounds) : na
bool  levOk         = inPos and (posQty + nextAddQty) * close <= strategy.equity * maxLev
bool  capReached    = inPos and (rounds >= maxRounds or not levOk)
 
// 利確(ラチェット追従)
float pnlPct = inPos ? (close / avgPrice - 1) * 100 : na
bool  tpHit  = inPos and pnlPct >= tpPct
 
var float peak = na
if not inPos
    peak := na
else if tpHit or not na(peak)
    peak := math.max(nz(peak, close), close)
 
float trailLine = inPos and not na(peak) ? math.max(peak * (1 - trailPct / 100), avgPrice) : na
bool  exitTp    = inPos and (trailPct == 0 ? tpHit : not na(trailLine) and close <= trailLine)
 
// 撤退(上限到達後のみ)
float surrenderLine = inPos ? avgPrice * (1 - surrenderPct / 100) : na
bool  exitSurrender = inPos and useSurrender and capReached and close <= surrenderLine
 
// この足でナンピンするか
bool doAdd = inPos and not exitTp and not exitSurrender and canTrade and not capReached and close <= nextAddPrice
 
// 清算価格:資産 = 建玉 × 証拠金率 になる価格(クロスマージン、口座全体を証拠金とみなす)
//   cash + Q × (P − A) = m × Q × P  →  P = (A − cash / Q) / (1 − m)
// ナンピンする足は、約定後のポジションで計算しておく
float mRate    = MARGIN_PCT / 100
float cash     = strategy.equity - strategy.openprofit
float addQ     = doAdd ? nextAddQty : 0.0
float planQty  = posQty + addQ
float planAvg  = inPos ? (avgPrice * posQty + close * addQ) / planQty : na
float liqPrice = inPos ? math.max((planAvg - cash / planQty) / (1 - mRate), 0) : na
float curLev   = inPos ? posQty * close / strategy.equity : 0.0
 
// 資産の記録(見せる用)
var float peakEq = strategy.initial_capital
var int   peakT  = time
if strategy.equity > peakEq
    peakEq := strategy.equity
    peakT  := time
float eqNow = strategy.equity
 
// ─────────────────────────────────────────────
// 注文(判定は終値、ナンピン・利確は次の足の始値、清算は逆指値)
// ─────────────────────────────────────────────
f_msg(string action, float qty, int round) =>
    '{"action":"' + action + '","symbol":"' + syminfo.ticker + '","qty":' + str.tostring(qty, "#.########") + ',"round":' + str.tostring(round) + '}'
 
var int deepestRound = 0
deepestRound := math.max(deepestRound, rounds)
 
if not inPos
    if canTrade and entrySignal and newBaseQty > 0
        strategy.entry("MG", strategy.long, qty = newBaseQty, comment = "R1",
             alert_message = f_msg("buy", newBaseQty, 1))
else
    if simLiq
        strategy.exit("LIQ", "MG", stop = liqPrice, comment = "Liquidation",
             alert_message = f_msg("close", planQty, rounds))
    if exitTp or exitSurrender
        strategy.close("MG", comment = exitTp ? "TP" : "Surrender",
             alert_message = f_msg("close", posQty, rounds))
    else if doAdd
        strategy.entry("MG", strategy.long, qty = nextAddQty, comment = "R" + str.tostring(rounds + 1),
             alert_message = f_msg("buy", nextAddQty, rounds + 1))
 
// ─────────────────────────────────────────────
// 描画
// ─────────────────────────────────────────────
color cWhite = color.new(color.white, 0)
color cGreen = color.new(#26a69a, 0)
color cRed   = color.new(#ef5350, 0)
color cAmber = color.new(#ff9800, 0)
color cGray  = color.new(#9598a1, 0)
 
plot(showLines and inPos ? avgPrice : na, "Average price", cWhite, 2, plot.style_linebr)
plot(showLines and inPos ? avgPrice * (1 + tpPct / 100) : na, "Take-profit line", color.new(#26a69a, 40), 1, plot.style_linebr)
plot(showLines and inPos ? trailLine : na, "Ratchet trail", cGreen, 2, plot.style_linebr)
plot(showLines and inPos and not capReached ? nextAddPrice : na, "Next add", color.new(#ef5350, 40), 1, plot.style_linebr)
plot(showLines and inPos and useSurrender ? surrenderLine : na, "Surrender line", cAmber, 1, plot.style_linebr)
plot(showLiq and inPos ? liqPrice : na, "Liquidation line", cRed, 1, plot.style_cross)
 
// 破産した足に「最高資産 → 現在資産」を大きく表示
if justBusted
    string txt = "LIQUIDATED\nPeak " + str.tostring(peakEq, "#,###") + " " + syminfo.currency + " (" + str.tostring((peakEq / strategy.initial_capital - 1) * 100, "+#,###") + "%)\n↓\n" + str.tostring(eqNow, "#,###;-#,###") + " " + syminfo.currency
    label.new(bar_index, low, txt, style = label.style_label_up, color = cRed, textcolor = color.white, size = size.large)
bgcolor(justBusted ? color.new(#ef5350, 60) : na, title = "Liquidation bar")
 
// ステータス表
var table tb = table.new(position.top_right, 2, 14, bgcolor = color.new(#131722, 8),
     frame_color = color.new(#9598a1, 70), frame_width = 1, border_width = 0)
 
f_row(int r, string k, string v, color vc) =>
    table.cell(tb, 0, r, k, text_color = cGray, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
if showTable and barstate.islast
    string st  = busted ? "Bankrupt" : not inPos ? "Waiting" : capReached ? "Cap reached" : not na(peak) ? "Trailing TP" : "In position"
    color  stC = busted ? cRed : not inPos ? cGray : capReached ? cAmber : not na(peak) ? cGreen : cWhite
    string na_ = "—"
    float  peakPct = (peakEq / strategy.initial_capital - 1) * 100
    float  nowPct  = (eqNow / strategy.initial_capital - 1) * 100
    f_row(0, "MARTINGALE DEMO", str.tostring(entryLogic), cWhite)
    f_row(1, "Status", st, stC)
    f_row(2, "Round", str.tostring(rounds) + " / " + str.tostring(maxRounds), rounds >= maxRounds ? cAmber : cWhite)
    f_row(3, "Average price", inPos ? str.tostring(avgPrice, format.mintick) : na_, cWhite)
    f_row(4, "Open P/L", inPos ? str.tostring(pnlPct, "+0.00;-0.00") + "%" : na_, inPos ? (pnlPct >= 0 ? cGreen : cRed) : cGray)
    f_row(5, "Next add", inPos and not capReached ? str.tostring(nextAddPrice, format.mintick) : na_, cWhite)
    f_row(6, "Liquidation", inPos ? str.tostring(liqPrice, format.mintick) : na_, cRed)
    f_row(7, "Exposure / equity", str.tostring(curLev, "0.00") + "x", curLev > maxLev * 0.8 ? cAmber : cWhite)
    f_row(8, "Deepest round", str.tostring(deepestRound), deepestRound >= maxRounds ? cAmber : cWhite)
    f_row(9, "Initial capital", str.tostring(strategy.initial_capital, "#,###") + " " + syminfo.currency, cWhite)
    f_row(10, "Peak equity", str.tostring(peakEq, "#,###") + " " + syminfo.currency + " (" + str.tostring(peakPct, "+#,###") + "%)", cGreen)
    f_row(11, "Peak date", str.format_time(peakT, "yyyy-MM-dd"), cGray)
    f_row(12, "Equity now", str.tostring(eqNow, "#,###;-#,###") + " " + syminfo.currency + " (" + str.tostring(nowPct, "+#,###;-#,###") + "%)", busted ? cRed : nowPct >= 0 ? cGreen : cRed)
    f_row(13, "Liquidation date", busted ? str.format_time(bustT, "yyyy-MM-dd") : na_, busted ? cRed : cGray)

← 返回列表