Long or Short? Trend Signals with Stop, Target & Size

ProofCharts · study · 206 行 · 点赞 22 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ProofCharts
//@version=6
indicator("Long or Short? Trend Signals with Stop, Target & Size", shorttitle = "Long or Short?", overlay = true, max_labels_count = 500, max_lines_count = 50)
 
// Long and short signals from a SuperTrend flip with an optional EMA 200 trend filter. Every signal comes with a
// stop, a target and a position size from the money you choose to risk, and the panel shows how past signals on
// this chart actually ended, losses included. Signals appear only when a candle has closed. Not advice.
 
G_SIG = "1. Signals"
G_RISK = "2. Your risk"
G_ADV = "Advanced (most people leave this as it is)"
 
iSens   = input.string("Normal (start here)", "Sensitivity", options = ["Calm (fewer signals)", "Normal (start here)", "Fast (more signals, more wrong ones)"], group = G_SIG, tooltip = "Calm: fewer, slower signals. Fast: more signals, and more of them are wrong. Normal is in between. Start with Normal. You can change it any time.")
iFilter = input.bool(true, "Only trade with the big trend (200-candle average)", group = G_SIG, tooltip = "EMA 200 = the average price of the last 200 candles. It shows the big trend. On: a LONG needs the close above it, and a SHORT needs the close below it. Leave it on while you learn: fewer signals, all with the big trend.")
iRR     = input.float(2.0, "Target = how many times the risk", minval = 0.5, step = 0.5, group = G_RISK, tooltip = "Risk = the distance from your entry to your stop. 2 = the target is twice as far away as the stop. So you aim to win 2 for every 1 you risk. Start with 2 and see how it did in the record.")
iMoney  = input.float(100.0, "Money I want to risk per trade", minval = 0, group = G_RISK, tooltip = "The money you are ready to lose if the stop is hit, in your account currency. The script works out the size from it. Pick an amount you can lose calmly. Then a loss is part of the plan, not a shock.")
iPvOvr  = input.float(0.0, "Money per 1.0 price move (0 = automatic)", minval = 0, group = G_ADV, tooltip = "Point value = how much money one contract or unit gains or loses when the price moves by 1.0. 0 = take it from the symbol. Futures have their own, for example 50 for ES. Most people leave 0.")
iLot    = input.float(1.0, "Units in one lot (forex: 100000)", minval = 0, group = G_ADV, tooltip = "How many units one lot holds. Forex: type 100000. Then the size is shown in lots, in steps of 0.01. Other symbols: leave 1.")
iAccCcy = input.string("USD", "Account currency", group = G_ADV, tooltip = "The currency of your account, for example USD or EUR. If the symbol is priced in another currency, the script gets the exchange rate from TradingView.")
iPanel  = input.bool(true, "Show the record and the trade plan", group = G_ADV, tooltip = "The box with the honest record of past signals on this chart and a check of the open trade. Keep it on: it shows how the signals really did on this market.")
iQuick  = input.bool(true, "Show the 3-step quick start", group = G_ADV, tooltip = "Three steps for your first trade. Turn it off once you know them.")
iBars   = input.bool(false, "Colour candles by trend", group = G_ADV, tooltip = "Green candles in an uptrend, red candles in a downtrend. It helps you see the trend at a glance.")
 
int atrLen = iSens == "Calm (fewer signals)" ? 14 : iSens == "Fast (more signals, more wrong ones)" ? 7 : 10
float factor = iSens == "Calm (fewer signals)" ? 3.0 : iSens == "Fast (more signals, more wrong ones)" ? 1.5 : 2.0
 
[st, stDir] = ta.supertrend(factor, atrLen)
float atrV = ta.atr(atrLen)
float emaV = ta.ema(close, 200)
float fxReq = request.currency_rate(syminfo.currency, iAccCcy, ignore_invalid_currency = true)
// Stablecoins quoted against the dollar count as USD (rate 1). A missing rate is shown in the panel.
usdLike(string c) => c == "USD" or c == "USDT" or c == "USDC" or c == "FDUSD" or c == "BUSD" or c == "DAI" or c == "TUSD" or c == "USDP" or c == "USD1"
bool sameCcy = syminfo.currency == iAccCcy or (usdLike(syminfo.currency) and usdLike(iAccCcy))
bool fxMissing = not sameCcy and na(fxReq)
float fx = sameCcy ? 1.0 : nz(fxReq, 1.0)
float pv = iPvOvr > 0 ? iPvOvr : nz(syminfo.pointvalue, 1.0)
bool isCrypto = syminfo.type == "crypto"
float step = iLot >= 1000 ? 0.01 : isCrypto ? 0.001 : 1.0
string unitTxt = iLot >= 1000 ? " lots" : isCrypto ? " coins" : " contracts"
 
// Price comparisons use the sign of the difference: exact at any price (crypto down to 1e-8), also where floats
// are compared with an absolute tolerance (PineTS: 1e-10). Crypto amendment 2026-10-24.
gt(float a, float b) => math.sign(a - b) > 0
ge(float a, float b) => math.sign(a - b) >= 0
bool ready = not na(atrV) and not na(atrV[1])
bool flipUp = ready and stDir < 0 and stDir[1] > 0
bool flipDn = ready and stDir > 0 and stDir[1] < 0
bool longSig = flipUp and (not iFilter or (not na(emaV) and gt(close, emaV)))
bool shortSig = flipDn and (not iFilter or (not na(emaV) and gt(emaV, close)))
 
// ---------- One trade at a time, decided on closed candles ----------
var int tDir = 0
var float tEntry = na
var float tStop = na
var float tTarget = na
var float tRisk = na
var float tSize = na
var int tBar = na
var int nTrades = 0
var int nWins = 0
var int streak = 0
var int worstStreak = 0
var float sumR = 0.0
var bool skipped = false  // a trend flip did not become a signal (filter), so the old trade stays open
bool exitWin = false
bool exitLoss = false
 
if barstate.isconfirmed
    float closedR = na
    if tDir != 0 and bar_index > tBar
        float ex = na
        if tDir == 1
            if ge(tStop, low)
                ex := math.min(tStop, open)
            else if ge(high, tTarget)
                ex := math.max(tTarget, open)
        else
            if ge(high, tStop)
                ex := math.max(tStop, open)
            else if ge(tTarget, low)
                ex := math.min(tTarget, open)
        if not na(ex)
            closedR := tDir * (ex - tEntry) / tRisk
            tDir := 0
    if longSig or shortSig
        if tDir != 0
            closedR := tDir * (close - tEntry) / tRisk
            tDir := 0
        float risk = math.abs(close - st)
        if math.sign(risk) > 0
            tDir := longSig ? 1 : -1
            tEntry := close
            tStop := st
            tRisk := risk
            tTarget := close + tDir * iRR * risk
            tSize := math.floor(iMoney / (risk * iLot * pv * fx) / step + 1e-9) * step
            tBar := bar_index
    if not na(closedR)
        nTrades += 1
        nWins += closedR > 0 ? 1 : 0
        sumR += closedR
        streak := closedR <= 0 ? streak + 1 : 0
        worstStreak := math.max(worstStreak, streak)
        exitWin := closedR > 0
        exitLoss := closedR <= 0
    // A flip that did not become a signal leaves the old trade open; the panel says why (owner 2026-11-01).
    if longSig or shortSig or tDir == 0
        skipped := false
    else if flipUp or flipDn
        skipped := true
 
// ---------- Look ----------
color cUp = #22c55e
color cDn = #ef4444
color cMuted = #94a3b8
pMid = plot(hl2, "Mid", display = display.none)
pTrend = plot(ready ? st : na, "Trend line", color = stDir < 0 ? cUp : cDn, linewidth = 2, style = plot.style_linebr)
fill(pMid, pTrend, color = ready ? color.new(stDir < 0 ? cUp : cDn, 88) : na, title = "Trend cloud")
plot(emaV, "EMA", color = color.new(cMuted, 40), linewidth = 1)
barcolor(iBars and ready ? color.new(stDir < 0 ? cUp : cDn, 15) : na)
if longSig and barstate.isconfirmed
    label.new(bar_index, low, "LONG ▲\n" + str.tostring(close, format.mintick), style = label.style_label_up, color = cUp, textcolor = color.white, size = size.small, yloc = yloc.belowbar)
if shortSig and barstate.isconfirmed
    label.new(bar_index, high, "SHORT ▼\n" + str.tostring(close, format.mintick), style = label.style_label_down, color = cDn, textcolor = color.white, size = size.small, yloc = yloc.abovebar)
plotshape(exitWin, "Target hit", shape.circle, location.abovebar, color.new(cUp, 0), text = "✓", textcolor = cUp, size = size.tiny)
plotshape(exitLoss, "Stop or exit at a loss", shape.xcross, location.belowbar, color.new(cDn, 0), text = "✗", textcolor = cDn, size = size.tiny)
 
// ---------- Values in the Data Window (also used by the tests) ----------
plot(longSig and barstate.isconfirmed ? 1 : 0, "Long signal", display = display.data_window)
plot(shortSig and barstate.isconfirmed ? 1 : 0, "Short signal", display = display.data_window)
plot(tDir != 0 ? tEntry : na, "Entry", display = display.data_window)
plot(tDir != 0 ? tStop : na, "Stop", display = display.data_window)
plot(tDir != 0 ? tTarget : na, "Target", display = display.data_window)
plot(tDir != 0 ? tSize : na, "Size", display = display.data_window, precision = 3)
plot(nTrades, "Trades", display = display.data_window)
plot(nWins, "Wins", display = display.data_window)
plot(nTrades > 0 ? 100 * nWins / nTrades : na, "Win %", display = display.data_window)
plot(nTrades > 0 ? sumR / nTrades : na, "Average R", display = display.data_window)
plot(sumR, "Total R", display = display.data_window)
plot(worstStreak, "Losing streak", display = display.data_window)
plot(tDir, "Open trade", display = display.data_window)
 
// ---------- Current trade lines and panel ----------
var line lnEntry = line.new(na, na, na, na, color = cMuted, width = 1)
var line lnStop = line.new(na, na, na, na, color = cDn, style = line.style_dashed, width = 2)
var line lnTarget = line.new(na, na, na, na, color = cUp, style = line.style_dashed, width = 2)
var table quick = table.new(position.bottom_right, 1, 4, bgcolor = color.new(#0f172a, 5), frame_color = color.new(cMuted, 70), frame_width = 1)
var table panel = table.new(position.top_right, 2, 11, bgcolor = color.new(#0f172a, 5), border_width = 0, frame_color = color.new(cMuted, 70), frame_width = 1)
 
if barstate.isfirst
    table.merge_cells(panel, 0, 0, 1, 0)
    table.merge_cells(panel, 0, 10, 1, 10)
 
px(float x) => str.tostring(x, format.mintick)
cell(int c, int r, string t, color tc, color bg, string sz) =>
    table.cell(panel, c, r, t, text_color = tc, bgcolor = bg, text_size = sz, text_halign = c == 0 ? text.align_left : text.align_right)
 
if barstate.islast
    bool isOpen = tDir != 0
    float yE = isOpen ? tEntry : na
    float yS = isOpen ? tStop : na
    float yT = isOpen ? tTarget : na
    line.set_xy1(lnEntry, isOpen ? tBar : na, yE)
    line.set_xy2(lnEntry, bar_index + 5, yE)
    line.set_xy1(lnStop, isOpen ? tBar : na, yS)
    line.set_xy2(lnStop, bar_index + 5, yS)
    line.set_xy1(lnTarget, isOpen ? tBar : na, yT)
    line.set_xy2(lnTarget, bar_index + 5, yT)
    if iPanel
        color cNone = color.new(color.black, 100)
        string trend = not ready ? "warming up" : stDir < 0 ? "UP" : "DOWN"
        cell(0, 0, "TREND SIGNALS  ·  trend " + trend, color.white, not ready ? cMuted : stDir < 0 ? color.new(cUp, 15) : color.new(cDn, 15), size.normal)
        cell(0, 1, "Open trade", cMuted, cNone, size.small)
        bool against = isOpen and ready and (tDir == 1) != (stDir < 0)
        string why = not against ? "" : not barstate.isconfirmed and stDir != stDir[1] ? " (the line turned; wait for the candle to close)" : skipped ? (tDir == 1 ? " (SHORT skipped: price was above EMA 200)" : " (LONG skipped: price was under EMA 200)") : ""
        cell(1, 1, isOpen ? (tDir == 1 ? "LONG" : "SHORT") + why : "none - wait for a signal", isOpen ? (tDir == 1 ? cUp : cDn) : color.white, cNone, size.small)
        cell(0, 2, "Entry / Stop", cMuted, cNone, size.small)
        cell(1, 2, isOpen ? px(tEntry) + " / " + px(tStop) : "-", color.white, cNone, size.small)
        cell(0, 3, "Target", cMuted, cNone, size.small)
        cell(1, 3, isOpen ? px(tTarget) : "-", color.white, cNone, size.small)
        cell(0, 4, "Size for your risk", cMuted, cNone, size.small)
        cell(1, 4, isOpen ? str.tostring(tSize, "#.###") + unitTxt : "-", color.white, cNone, size.small)
        cell(0, 5, "Past signals on this chart", cMuted, cNone, size.small)
        cell(1, 5, str.tostring(nTrades) + " trades, " + (nTrades > 0 ? str.tostring(math.round(100 * nWins / nTrades)) + "% won" : "-"), color.white, cNone, size.small)
        cell(0, 6, "Average result per trade", cMuted, cNone, size.small)
        cell(1, 6, nTrades > 0 ? str.tostring(sumR / nTrades, "#.##") + " x risk" : "-", nTrades > 0 ? (sumR > 0 ? cUp : cDn) : color.white, cNone, size.small)
        cell(0, 7, "Worst losing streak", cMuted, cNone, size.small)
        cell(1, 7, str.tostring(worstStreak) + " in a row", color.white, cNone, size.small)
        bool withTrend = isOpen and not na(emaV) and (tDir == 1 ? gt(close, emaV) : gt(emaV, close))
        bool sizeOk = isOpen and tSize >= step
        cell(0, 8, "With the big trend (EMA 200)", cMuted, cNone, size.small)
        cell(1, 8, not isOpen ? "-" : withTrend ? "✓ yes" : "✗ no - be careful", not isOpen ? color.white : withTrend ? cUp : cDn, cNone, size.small)
        cell(0, 9, "Size possible with your risk", cMuted, cNone, size.small)
        cell(1, 9, not isOpen ? "-" : sizeOk ? "✓ yes" : "✗ stop too far for your risk - skip this one", not isOpen ? color.white : sizeOk ? cUp : cDn, cNone, size.small)
        cell(0, 10, (fxMissing ? "Currency rate " + syminfo.currency + " -> " + iAccCcy + " missing: size uses 1. " : "") + "Past results on this chart, so you can judge them yourself. No costs included. Not advice.", fxMissing ? color.orange : cMuted, cNone, size.tiny)
    if iQuick
        table.cell(quick, 0, 0, "QUICK START: your first trade in 3 steps", text_color = color.white, bgcolor = color.new(#334155, 0), text_size = size.small, text_halign = text.align_left)
        table.cell(quick, 0, 1, "1. Wait for a LONG or SHORT tag. It appears when a candle closes.", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(quick, 0, 2, "2. Use the stop and the size from the panel. Then a normal loss is about what you chose.", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(quick, 0, 3, "3. Alerts: right-click the chart > Add alert > Long or Short? > Any alert() function call.", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
 
if (longSig or shortSig) and barstate.isconfirmed and tDir != 0 and tBar == bar_index
    alert("Trend Signals: " + (tDir == 1 ? "LONG " : "SHORT ") + syminfo.ticker + " | entry " + str.tostring(tEntry, format.mintick) + " | stop " + str.tostring(tStop, format.mintick) + " | target " + str.tostring(tTarget, format.mintick) + " | size " + str.tostring(tSize, "#.###"), alert.freq_once_per_bar_close)
alertcondition(longSig and barstate.isconfirmed, "Long signal", "Trend Signals: LONG on {{ticker}} at {{close}}")
alertcondition(shortSig and barstate.isconfirmed, "Short signal", "Trend Signals: SHORT on {{ticker}} at {{close}}")

← 返回列表