Day Trader's Edge Companion - D Johnson

thelonetrainers · study · 319 行 · 点赞 19 · TradingView 原页

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

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Day Trader's Edge Companion
// Companion indicator to the book "The Day Trader's Edge" by D. Johnson.
//
// What it does: puts the book's rules on your chart. It classifies the market
// mode, draws VWAP / opening range / prior-day levels, flags the book's four
// chart setups, sizes the trade from the stop, and runs the pre-trade checklist.
//
// What it does NOT do: predict price, guarantee results, or give investment
// advice. It is a process and risk tool. Markers are rule conditions, not
// recommendations. Test every setup on your own data before risking money.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Day Trader's Edge Companion", shorttitle="DTE Companion", overlay=true, max_lines_count=10, max_labels_count=20)
 
// ═════════════════════════════ INPUTS ═════════════════════════════
GA = "1. Account and risk"
GB = "2. Stop and targets"
GC = "3. Session and volume"
GD = "4. Market mode"
GE = "5. Setup settings"
GF = "6. Daily discipline (you update these)"
GG = "7. Display"
 
accountSize = input.float(10000.0, "Account size", minval=1.0, group=GA, tooltip="Your trading account size, in your account currency.")
riskPct     = input.float(1.0, "Risk per trade (%)", minval=0.05, maxval=5.0, step=0.05, group=GA, tooltip="The book's range is 0.25% to 1%. The dashboard flags anything above 1%.")
costPerUnit = input.float(0.02, "Round-trip cost per unit (price units)", minval=0.0, step=0.005, group=GA, tooltip="Spread plus commission plus expected slippage for one share, contract or unit, in price terms (Chapter 4 shows how to measure it).")
maxPosX     = input.float(2.0, "Max position value (x account)", minval=0.1, step=0.1, group=GA, tooltip="Flags trades whose full value exceeds this multiple of your account. Raise it for futures and forex, where you put up margin rather than the full value.")
wholeUnits  = input.bool(true, "Round size down to whole units", group=GA)
 
stopMode  = input.string("ATR multiple", "Stop method", options=["ATR multiple", "Recent swing", "Opening range midpoint"], group=GB, tooltip="Where the stop goes. The book says: where your idea is proven wrong. Pick the method that matches your setup.")
atrLen    = input.int(14, "ATR length", minval=1, group=GB)
stopMult  = input.float(1.5, "Stop distance (x ATR)", minval=0.1, step=0.1, group=GB)
swingBars = input.int(5, "Swing lookback (bars)", minval=2, group=GB)
t1R       = input.float(1.0, "Target 1 (R)", minval=0.1, step=0.1, group=GB)
t2R       = input.float(2.0, "Target 2 (R)", minval=0.2, step=0.1, group=GB)
minNetRR  = input.float(1.5, "Minimum net reward-to-risk to target 2", minval=0.5, step=0.1, group=GB, tooltip="Reward-to-risk after costs. Below this, the checklist fails.")
maxCostR  = input.float(0.10, "Maximum cost (R)", minval=0.01, step=0.01, group=GB, tooltip="The book's rule of thumb: costs above 0.10R eat too much of your edge.")
 
winSess  = input.session("0930-1130", "Trading window", group=GC, tooltip="Your trading window in the exchange's time zone. The opening range is measured from the start of this window.")
orMins   = input.int(30, "Opening range (minutes)", minval=1, group=GC)
maxOrAtr = input.float(0.5, "Max opening-range width (x daily ATR)", minval=0.05, step=0.05, group=GC, tooltip="Filters out unusually wide opening ranges. Tune it to your instrument.")
volLen   = input.int(20, "Volume average length", minval=2, group=GC)
volMin   = input.float(1.0, "Minimum volume vs normal (x)", minval=0.1, step=0.1, group=GC)
 
adxLen    = input.int(14, "ADX length", minval=2, group=GD)
adxTrend  = input.float(20.0, "ADX level that counts as trending", minval=5.0, group=GD)
emaLen    = input.int(20, "Moving average length", minval=2, group=GD)
htf       = input.timeframe("D", "Higher timeframe", group=GD, tooltip="Direction comes from here. Uses the last completed higher-timeframe bar, so it does not repaint.")
htfEmaLen = input.int(20, "Higher-timeframe average length", minval=2, group=GD)
 
stretchThr  = input.float(2.0, "VWAP stretch (x ATR)", minval=0.5, step=0.1, group=GE)
trendDayAdx = input.float(30.0, "Switch off VWAP reversion above ADX", minval=10.0, group=GE, tooltip="Fading a genuine trend day is a classic way to lose a month's profit in an afternoon (Chapter 6).")
gapThr      = input.float(0.5, "Gap flag (x daily ATR)", minval=0.1, step=0.1, group=GE)
 
dirIn       = input.string("Auto", "Planning direction", options=["Auto", "Long", "Short"], group=GF, tooltip="Auto follows a setup that has just triggered, otherwise the market mode.")
dailyLimitR = input.float(3.0, "Daily loss limit (R)", minval=0.5, step=0.5, group=GF)
rLostToday  = input.float(0.0, "R lost so far today", minval=0.0, step=0.5, group=GF, tooltip="Update this from your journal. The indicator cannot see your trades.")
maxTrades   = input.int(4, "Max trades per day", minval=1, group=GF)
tradesToday = input.int(0, "Trades taken so far today", minval=0, group=GF)
breakAfter  = input.int(2, "Take a break after this many losses in a row", minval=1, group=GF)
lossStreak  = input.int(0, "Losses in a row right now", minval=0, group=GF)
 
showDash   = input.bool(true, "Show dashboard", group=GG)
dashPosIn  = input.string("Top right", "Dashboard position", options=["Top right", "Top left", "Bottom right", "Bottom left"], group=GG)
showPlan   = input.bool(true, "Draw planned stop and targets", group=GG)
showMarks  = input.bool(true, "Show setup markers", group=GG)
showLevels = input.bool(true, "Show VWAP, opening range and prior-day levels", group=GG)
 
// ═════════════════════════════ COLOURS ═════════════════════════════
cGood = #26a69a
cBad  = #ef5350
cWarn = #ffb74d
cTxt  = #d1d4dc
cMut  = #9598a1
cBg   = color.new(#131722, 8)
 
// ═════════════════════════════ CORE SERIES ═════════════════════════════
atr      = ta.atr(atrLen)
emaFast  = ta.ema(close, emaLen)
volAvg   = ta.sma(volume, volLen)
swingLo  = ta.lowest(low, swingBars)
swingHi  = ta.highest(high, swingBars)
[diP, diM, adx] = ta.dmi(adxLen, adxLen)
[vwapV, vwapUp, vwapLo] = ta.vwap(hlc3, timeframe.change("D"), 1.0)
 
[pdh, pdl, dAtr, dOpen, dPrevClose] = request.security(syminfo.tickerid, "D", [high[1], low[1], ta.atr(14)[1], open, close[1]], lookahead=barmerge.lookahead_on)
htfClose = request.security(syminfo.tickerid, htf, close[1], lookahead=barmerge.lookahead_on)
htfEma   = request.security(syminfo.tickerid, htf, ta.ema(close, htfEmaLen)[1], lookahead=barmerge.lookahead_on)
 
volRatio = volAvg > 0 ? volume / volAvg : na
volOk    = na(volRatio) ? true : volRatio >= volMin
stretch  = atr > 0 ? (close - vwapV) / atr : na
gapAtr   = dAtr > 0 ? (dOpen - dPrevClose) / dAtr : na
 
// ═════════════════════════════ MARKET MODE ═════════════════════════════
// 1 = trend up, -1 = trend down, 0 = range
mode = adx >= adxTrend and diP > diM and close > emaFast ? 1 : adx >= adxTrend and diM > diP and close < emaFast ? -1 : 0
htfBias = htfClose > htfEma ? 1 : htfClose < htfEma ? -1 : 0
 
// ═════════════════════════════ SESSION AND OPENING RANGE ═════════════════════════════
inWin  = not na(time(timeframe.period, winSess, syminfo.timezone))
newWin = inWin and not inWin[1]
var int   winStart = na
var float orHi = na
var float orLo = na
if newWin
    winStart := time
    orHi := high
    orLo := low
else if inWin and not na(winStart) and (time - winStart) < orMins * 60000
    orHi := math.max(orHi, high)
    orLo := math.min(orLo, low)
orDone   = inWin and not na(winStart) and (time - winStart) >= orMins * 60000
orMid    = (orHi + orLo) / 2
orNarrow = not na(dAtr) and not na(orHi) and (orHi - orLo) <= maxOrAtr * dAtr
 
// ═════════════════════════════ THE FOUR CHART SETUPS ═════════════════════════════
// All ta.* calls sit on their own lines so every bar is calculated.
lowest3     = ta.lowest(low, 3)
highest3    = ta.highest(high, 3)
lowestStr4  = ta.lowest(stretch, 4)
highestStr4 = ta.highest(stretch, 4)
highest5    = ta.highest(high, 5)
lowest5     = ta.lowest(low, 5)
xUnderPdh   = ta.crossunder(close, pdh)
xOverPdl    = ta.crossover(close, pdl)
 
// 1. Opening range breakout (first close beyond the range, with volume)
orbL = orDone and close > orHi and close[1] <= orHi and volOk and orNarrow and htfBias >= 0
orbS = orDone and close < orLo and close[1] >= orLo and volOk and orNarrow and htfBias <= 0
 
// 2. Trend pullback (touches the average zone, then turns back with the trend)
pbL = inWin and mode == 1 and lowest3 <= emaFast + 0.25 * atr and close > high[1] and close > emaFast and close > vwapV
pbS = inWin and mode == -1 and highest3 >= emaFast - 0.25 * atr and close < low[1] and close < emaFast and close < vwapV
 
// 3. VWAP reversion (stretched, a turn candle, and not a trend day)
revL = inWin and adx < trendDayAdx and lowestStr4 <= -stretchThr and close > open and close > close[1]
revS = inWin and adx < trendDayAdx and highestStr4 >= stretchThr and close < open and close < close[1]
 
// 4. Failed breakout of the prior-day high or low
fbS = inWin and not na(pdh) and xUnderPdh and highest5 > pdh
fbL = inWin and not na(pdl) and xOverPdl and lowest5 < pdl
 
anyLong  = orbL or pbL or revL or fbL
anyShort = orbS or pbS or revS or fbS
 
// ═════════════════════════════ TRADE PLAN ═════════════════════════════
manualDir = dirIn == "Long" ? 1 : dirIn == "Short" ? -1 : 0
autoDir   = mode
planDir   = anyLong and not anyShort ? 1 : anyShort and not anyLong ? -1 : dirIn == "Auto" ? autoDir : manualDir
 
longStop0 = switch stopMode
    "Recent swing" => swingLo - 0.1 * atr
    "Opening range midpoint" => na(orMid) ? close - stopMult * atr : orMid
    => close - stopMult * atr
shortStop0 = switch stopMode
    "Recent swing" => swingHi + 0.1 * atr
    "Opening range midpoint" => na(orMid) ? close + stopMult * atr : orMid
    => close + stopMult * atr
longStop  = longStop0 < close ? longStop0 : close - stopMult * atr
shortStop = shortStop0 > close ? shortStop0 : close + stopMult * atr
 
planStop = planDir == -1 ? shortStop : longStop
riskDist = math.max(math.abs(close - planStop), syminfo.mintick)
tgt1     = close + planDir * t1R * riskDist
tgt2     = close + planDir * t2R * riskDist
 
riskAmt  = accountSize * riskPct / 100
unitRisk = riskDist * syminfo.pointvalue
rawSize  = unitRisk > 0 ? riskAmt / unitRisk : na
posSize  = wholeUnits ? math.floor(rawSize) : rawSize
posValue = posSize * close * syminfo.pointvalue
posX     = posValue / accountSize
costR    = costPerUnit / riskDist
netRR    = (t2R - costR) / (1 + costR)
 
// ═════════════════════════════ PRE-TRADE CHECKLIST ═════════════════════════════
limitHit = rLostToday >= dailyLimitR or tradesToday >= maxTrades
breakNow = lossStreak >= breakAfter
limitsOk = not limitHit and not breakNow
 
c1 = planDir != 0 and htfBias == planDir
c2 = inWin
c3 = volOk
c4 = costR <= maxCostR
c5 = netRR >= minNetRR
c6 = limitsOk
c7 = posSize > 0 and posX <= maxPosX
score = (c1 ? 1 : 0) + (c2 ? 1 : 0) + (c3 ? 1 : 0) + (c4 ? 1 : 0) + (c5 ? 1 : 0) + (c6 ? 1 : 0) + (c7 ? 1 : 0)
trigAligned = planDir == 1 ? anyLong : planDir == -1 ? anyShort : false
 
// ═════════════════════════════ CHART OUTPUT ═════════════════════════════
plot(showLevels ? vwapV : na, "VWAP", color=color.new(#ff9800, 0), linewidth=2)
plot(showLevels ? vwapUp : na, "VWAP +1 SD", color=color.new(#ff9800, 72), linewidth=1)
plot(showLevels ? vwapLo : na, "VWAP -1 SD", color=color.new(#ff9800, 72), linewidth=1)
plot(showLevels ? emaFast : na, "Moving average", color=color.new(color.gray, 35), linewidth=1)
plot(showLevels and inWin ? orHi : na, "Opening range high", color=color.new(#2962ff, 0), linewidth=1, style=plot.style_linebr)
plot(showLevels and inWin ? orLo : na, "Opening range low", color=color.new(#2962ff, 0), linewidth=1, style=plot.style_linebr)
plot(showLevels ? pdh : na, "Prior day high", color=color.new(color.gray, 45), linewidth=1, style=plot.style_linebr)
plot(showLevels ? pdl : na, "Prior day low", color=color.new(color.gray, 45), linewidth=1, style=plot.style_linebr)
bgcolor(timeframe.isintraday and not inWin ? color.new(color.gray, 94) : na)
 
mk = showMarks and barstate.isconfirmed
plotshape(mk and orbL, "ORB long", style=shape.triangleup, location=location.belowbar, color=cGood, text="ORB", textcolor=cGood, size=size.tiny)
plotshape(mk and orbS, "ORB short", style=shape.triangledown, location=location.abovebar, color=cBad, text="ORB", textcolor=cBad, size=size.tiny)
plotshape(mk and pbL, "Pullback long", style=shape.triangleup, location=location.belowbar, color=cGood, text="PB", textcolor=cGood, size=size.tiny)
plotshape(mk and pbS, "Pullback short", style=shape.triangledown, location=location.abovebar, color=cBad, text="PB", textcolor=cBad, size=size.tiny)
plotshape(mk and revL, "VWAP reversion long", style=shape.triangleup, location=location.belowbar, color=cGood, text="VR", textcolor=cGood, size=size.tiny)
plotshape(mk and revS, "VWAP reversion short", style=shape.triangledown, location=location.abovebar, color=cBad, text="VR", textcolor=cBad, size=size.tiny)
plotshape(mk and fbL, "Failed breakout long", style=shape.triangleup, location=location.belowbar, color=cGood, text="FB", textcolor=cGood, size=size.tiny)
plotshape(mk and fbS, "Failed breakout short", style=shape.triangledown, location=location.abovebar, color=cBad, text="FB", textcolor=cBad, size=size.tiny)
 
// Alerts: set to "Once Per Bar Close" so they match the markers.
alertcondition(barstate.isconfirmed and anyLong, "DTE: long setup triggered", "Long setup on {{ticker}} ({{interval}}). Run the checklist before you enter.")
alertcondition(barstate.isconfirmed and anyShort, "DTE: short setup triggered", "Short setup on {{ticker}} ({{interval}}). Run the checklist before you enter.")
alertcondition(barstate.isconfirmed and trigAligned and score == 7 and limitsOk, "DTE: setup with checklist clear", "Setup triggered and all 7 checks pass on {{ticker}} ({{interval}}).")
 
// Planned entry, stop and targets (last bar only)
var line  lnE  = na
var line  lnS  = na
var line  lnT1 = na
var line  lnT2 = na
var label lbS  = na
var label lbT1 = na
var label lbT2 = na
if barstate.islast
    line.delete(lnE)
    line.delete(lnS)
    line.delete(lnT1)
    line.delete(lnT2)
    label.delete(lbS)
    label.delete(lbT1)
    label.delete(lbT2)
    if showPlan and planDir != 0 and not na(riskDist)
        x1 = bar_index
        x2 = bar_index + 6
        lnE  := line.new(x1, close, x2, close, color=color.new(color.gray, 0), style=line.style_dashed, width=1)
        lnS  := line.new(x1, planStop, x2, planStop, color=cBad, width=2)
        lnT1 := line.new(x1, tgt1, x2, tgt1, color=cGood, width=1)
        lnT2 := line.new(x1, tgt2, x2, tgt2, color=cGood, width=2)
        lbS  := label.new(x2, planStop, "Stop " + str.tostring(planStop, format.mintick), style=label.style_label_left, color=color.new(cBad, 20), textcolor=color.white, size=size.small)
        lbT1 := label.new(x2, tgt1, "T1 " + str.tostring(t1R, "0.0") + "R  " + str.tostring(tgt1, format.mintick), style=label.style_label_left, color=color.new(cGood, 20), textcolor=color.white, size=size.small)
        lbT2 := label.new(x2, tgt2, "T2 " + str.tostring(t2R, "0.0") + "R  " + str.tostring(tgt2, format.mintick), style=label.style_label_left, color=color.new(cGood, 20), textcolor=color.white, size=size.small)
 
// ═════════════════════════════ DASHBOARD ═════════════════════════════
dashPos = switch dashPosIn
    "Top left" => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left" => position.bottom_left
    => position.top_right
 
var table dash = table.new(dashPos, 2, 23, border_width=1, border_color=color.new(color.gray, 70), frame_width=1, frame_color=color.new(color.gray, 60))
 
f_row(table t, int r, string lbl, string val, color valColor) =>
    table.cell(t, 0, r, lbl, text_color=cMut, text_halign=text.align_left, text_size=size.small, bgcolor=cBg)
    table.cell(t, 1, r, val, text_color=valColor, text_halign=text.align_left, text_size=size.small, bgcolor=cBg)
 
f_check(table t, int r, string lbl, bool ok) =>
    table.cell(t, 0, r, lbl, text_color=cTxt, text_halign=text.align_left, text_size=size.small, bgcolor=cBg)
    table.cell(t, 1, r, ok ? "✔" : "✖", text_color=ok ? cGood : cBad, text_halign=text.align_center, text_size=size.small, bgcolor=cBg)
 
if barstate.islast and showDash
    modeTxt = (mode == 1 ? "Trend up" : mode == -1 ? "Trend down" : "Range") + " (ADX " + str.tostring(adx, "0") + ")"
    modeCol = mode == 1 ? cGood : mode == -1 ? cBad : cWarn
    htfTxt  = htfBias == 1 ? "Up" : htfBias == -1 ? "Down" : "Flat"
    htfCol  = htfBias == 1 ? cGood : htfBias == -1 ? cBad : cWarn
    vwapTxt = na(stretch) ? "n/a" : str.tostring(math.abs(stretch), "0.0") + " ATR " + (stretch >= 0 ? "above" : "below")
    volTxt  = na(volRatio) ? "n/a (no volume data)" : str.tostring(volRatio, "0.0") + "x normal"
    gapTxt  = na(gapAtr) ? "n/a" : math.abs(gapAtr) >= gapThr ? (gapAtr > 0 ? "Gap up " : "Gap down ") + str.tostring(math.abs(gapAtr), "0.0") + " daily ATR" : "None of note"
 
    string setupTxt = ""
    setupTxt += orbL ? "ORB▲ " : ""
    setupTxt += orbS ? "ORB▼ " : ""
    setupTxt += pbL ? "PB▲ " : ""
    setupTxt += pbS ? "PB▼ " : ""
    setupTxt += revL ? "VR▲ " : ""
    setupTxt += revS ? "VR▼ " : ""
    setupTxt += fbL ? "FB▲ " : ""
    setupTxt += fbS ? "FB▼ " : ""
    setupTxt := setupTxt == "" ? "None right now" : setupTxt
 
    planTxt  = planDir == 1 ? "LONG (entry near " + str.tostring(close, format.mintick) + ")" : planDir == -1 ? "SHORT (entry near " + str.tostring(close, format.mintick) + ")" : "None: range, wait for a level setup"
    planCol  = planDir == 1 ? cGood : planDir == -1 ? cBad : cWarn
    stopTxt  = planDir == 0 ? "-" : str.tostring(planStop, format.mintick) + "  (" + str.tostring(riskDist, format.mintick) + " = " + str.tostring(atr > 0 ? riskDist / atr : 0.0, "0.0") + " ATR)"
    tgtTxt   = planDir == 0 ? "-" : str.tostring(tgt1, format.mintick) + " / " + str.tostring(tgt2, format.mintick)
    sizeTxt  = planDir == 0 or na(posSize) ? "-" : (posSize > 0 ? str.tostring(posSize, wholeUnits ? "0" : "0.00") + " units, risking " + str.tostring(riskAmt, "0.00") : "0: stop too wide for this account at this risk")
    posTxt   = planDir == 0 or na(posX) ? "-" : str.tostring(posX, "0.00") + "x account"
    costTxt  = planDir == 0 ? "-" : str.tostring(costR, "0.00") + "R per trade"
 
    verdict = not timeframe.isintraday ? "Use an intraday chart (1m to 30m)" : not limitsOk ? "STOP: your own limit rule is hit" : score == 7 and trigAligned ? "Checklist clear and a setup has triggered" : score == 7 ? "Checklist clear. Waiting for a trigger" : "Not yet: " + str.tostring(score) + " of 7 checks pass"
    verdictCol = not timeframe.isintraday ? cWarn : not limitsOk ? cBad : score == 7 ? cGood : cWarn
 
    table.cell(dash, 0, 0, "DAY TRADER'S EDGE COMPANION", text_color=color.white, text_halign=text.align_center, text_size=size.small, bgcolor=color.new(#2a2e39, 0))
    table.merge_cells(dash, 0, 0, 1, 0)
    f_row(dash, 1, "Market mode", modeTxt, modeCol)
    f_row(dash, 2, "Higher timeframe (" + htf + ")", htfTxt, htfCol)
    f_row(dash, 3, "Price vs VWAP", vwapTxt, cTxt)
    f_row(dash, 4, "Volume", volTxt, volOk ? cTxt : cWarn)
    f_row(dash, 5, "Gap today", gapTxt, cTxt)
    f_row(dash, 6, "Trading window", inWin ? "Inside" : "Outside", inWin ? cGood : cWarn)
    f_row(dash, 7, "Setups (bar close)", setupTxt, setupTxt == "None right now" ? cMut : cTxt)
    f_row(dash, 8, "Plan", planTxt, planCol)
    f_row(dash, 9, "Stop", stopTxt, cTxt)
    f_row(dash, 10, "Targets (1R / 2R)", tgtTxt, cTxt)
    f_row(dash, 11, "Position size", sizeTxt, c7 ? cTxt : cWarn)
    f_row(dash, 12, "Position value", posTxt, posX <= maxPosX ? cTxt : cWarn)
    f_row(dash, 13, "Cost", costTxt, c4 ? cTxt : cWarn)
    f_check(dash, 14, "Direction clear, higher timeframe agrees", c1)
    f_check(dash, 15, "Inside my trading window", c2)
    f_check(dash, 16, "Volume at least normal", c3)
    f_check(dash, 17, "Costs small relative to the stop", c4)
    f_check(dash, 18, "Reward after costs is worth it", c5)
    f_check(dash, 19, "Daily limits and break rule respected", c6)
    f_check(dash, 20, "Position size fits the account", c7)
    table.cell(dash, 0, 21, verdict, text_color=verdictCol, text_halign=text.align_center, text_size=size.small, bgcolor=color.new(#2a2e39, 0))
    table.merge_cells(dash, 0, 21, 1, 21)
    table.cell(dash, 0, 22, "Process tool, not advice. Test before risking money.", text_color=cMut, text_halign=text.align_center, text_size=size.tiny, bgcolor=cBg)
    table.merge_cells(dash, 0, 22, 1, 22)

← 返回列表