Bull & Wolf Nifty Indicator

Bull-and-Wolf · strategy · 225 行 · 点赞 166 · TradingView 原页

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

Pine Script

//@version=6
//@strategy_alert_message {{strategy.order.alert_message}} | {{ticker}} | Fill: {{strategy.order.price}} | Qty: {{strategy.order.contracts}}
strategy("VWAP 3rd SD Mean Reversion - BUY/SELL + Exits", overlay=true,
     initial_capital=25000, pyramiding=0,
     default_qty_type=strategy.cash, default_qty_value=25000,
     commission_type=strategy.commission.cash_per_contract,
     commission_value=0.0035, slippage=2,
     calc_on_every_tick=true, calc_on_order_fills=false,
     process_orders_on_close=true,
     margin_long=0, margin_short=0, max_labels_count=500)
 
// Explicit zero margins preserve the original v5 margin behavior.
// Keep "On order fill" disabled: protective exits are submitted with entries.
 
// INPUTS
vwapSource = input.source(hlc3, "VWAP Source", group="VWAP")
sessionStartHour = input.int(9, "Session Start Hour", minval=0, maxval=23, group="Session")
sessionStartMin = input.int(15, "Session Start Minute", minval=0, maxval=59, group="Session")
tradingStartHour = input.int(9, "No Entries Before Hour", minval=0, maxval=23, group="Session")
tradingStartMin = input.int(30, "No Entries Before Minute", minval=0, maxval=59, group="Session")
tradingFutures = input.bool(false, "Use Futures Cutoff (15:40)", group="Session",
     tooltip="All times use the symbol's exchange timezone. When enabled, the manual cutoff below is ignored.")
forceExitHour = input.int(15, "Manual Force Exit Hour", minval=0, maxval=23, group="Session")
forceExitMin = input.int(15, "Manual Force Exit Minute", minval=0, maxval=59, group="Session")
 
stopBandMultiplier = input.float(4.5, "Stop Distance (x SD from VWAP)", minval=3.1, step=0.1, group="Risk")
riskPerTradePct = input.float(1.0, "Risk per Trade (% of equity)", minval=0.1, maxval=100, step=0.1, group="Risk")
cooldownMinutes = input.int(30, "Cooldown After Stop-Out (minutes)", minval=0, group="Risk")
proximityTolerance = input.float(5.0, "Entry / Target Tolerance (points)", minval=0, group="Risk")
quantityStep = input.float(1.0, "Order Quantity Step", minval=0.00000001, group="Risk",
     tooltip="Quantity is rounded DOWN to this step. Set it to the permitted order increment in the chart's quantity units; futures lot conventions depend on the symbol.")
 
allowLongs = input.bool(true, "Allow BUY / Long", group="Direction")
allowShorts = input.bool(true, "Allow SELL / Short", group="Direction")
showBands = input.bool(true, "Show VWAP / SD Bands", group="Display")
showSignals = input.bool(true, "Show BUY / SELL / EXIT Labels", group="Display")
showTradeLevels = input.bool(true, "Show Active Stop / Target", group="Display")
 
// SESSION TIMES: same-day, intraday sessions only.
int sessionStartTime = timestamp(syminfo.timezone, year, month, dayofmonth, sessionStartHour, sessionStartMin)
int tradingStartTime = timestamp(syminfo.timezone, year, month, dayofmonth, tradingStartHour, tradingStartMin)
int forceExitTime = timestamp(syminfo.timezone, year, month, dayofmonth,
     tradingFutures ? 15 : forceExitHour, tradingFutures ? 40 : forceExitMin)
 
if barstate.isfirst
    if not timeframe.isintraday
        runtime.error("Use this strategy on a time-based intraday chart.")
    if tradingStartTime < sessionStartTime or tradingStartTime >= forceExitTime
        runtime.error("Entry start must be at/after session start and before force exit.")
 
int dayChange = ta.change(time("D"))
bool newDay = barstate.isfirst or dayChange != 0
bool inSession = time >= sessionStartTime and time < forceExitTime
// time_close is in the future on an open realtime bar. Use timenow there
// so the final bar does not force an exit as soon as that bar opens.
int evaluationTime = barstate.isrealtime ? timenow : time_close
bool cutoffReached = (not na(evaluationTime) and evaluationTime >= forceExitTime) or
     (barstate.isconfirmed and not na(time_close) and time_close >= forceExitTime)
bool inTradingWindow = inSession and not na(evaluationTime) and
     evaluationTime >= tradingStartTime and not cutoffReached
 
// SESSION VWAP / VOLUME-WEIGHTED STANDARD DEVIATION
var float cumPV = 0.0
var float cumPV2 = 0.0
var float cumVol = 0.0
if newDay
    cumPV := 0.0
    cumPV2 := 0.0
    cumVol := 0.0
if inSession and not na(vwapSource)
    float barVolume = nz(volume, 0.0)
    cumPV += vwapSource * barVolume
    cumPV2 += vwapSource * vwapSource * barVolume
    cumVol += barVolume
 
float vwapVal = cumVol > 0 ? cumPV / cumVol : na
float variance = cumVol > 0 ? math.max(cumPV2 / cumVol - vwapVal * vwapVal, 0.0) : na
float stdevVal = math.sqrt(variance)
float band1Upper = vwapVal + stdevVal
float band1Lower = vwapVal - stdevVal
float band2Upper = vwapVal + 2.0 * stdevVal
float band2Lower = vwapVal - 2.0 * stdevVal
float band3Upper = vwapVal + 3.0 * stdevVal
float band3Lower = vwapVal - 3.0 * stdevVal
float entryLong = math.round_to_mintick(band3Lower + proximityTolerance)
float entryShort = math.round_to_mintick(band3Upper - proximityTolerance)
float stopLong = math.round_to_mintick(vwapVal - stopBandMultiplier * stdevVal)
float stopShort = math.round_to_mintick(vwapVal + stopBandMultiplier * stdevVal)
float targetLong = math.round_to_mintick(vwapVal - proximityTolerance)
float targetShort = math.round_to_mintick(vwapVal + proximityTolerance)
 
// FIXED STOPS / COOLDOWN
// varip keeps the last submitted stop when a realtime entry fills after
// an intrabar order update. Stops freeze once the position is open.
varip float workingLongStop = na
varip float workingShortStop = na
varip int cooldownUntilTime = na
varip int cooldownSession = na
if na(cooldownSession) or cooldownSession != sessionStartTime
    cooldownUntilTime := na
    cooldownSession := sessionStartTime
 
// Use the broker emulator's recorded exit comment, not the current
// position or this bar's high/low, to identify a stop-out.
if strategy.closedtrades > 0
    int lastTrade = strategy.closedtrades - 1
    int lastExitTime = strategy.closedtrades.exit_time(lastTrade)
    string lastReason = strategy.closedtrades.exit_comment(lastTrade)
    if lastExitTime >= sessionStartTime and lastReason == "STOP LOSS" and cooldownMinutes > 0
        cooldownUntilTime := lastExitTime + cooldownMinutes * 60 * 1000
bool inCooldown = not na(cooldownUntilTime) and evaluationTime < cooldownUntilTime
bool priorDayPosition = strategy.opentrades > 0 and
     strategy.opentrades.entry_time(0) < sessionStartTime
 
// ORDER MANAGEMENT
// Stops and VWAP targets are bracket orders, attached when entries are
// submitted. Targets update on each calculation; stops stay fixed.
if cutoffReached or priorDayPosition
    strategy.cancel_all()
    if strategy.position_size != 0
        string reason = priorDayPosition ? "PRIOR DAY EXIT" : "EOD EXIT"
        strategy.close_all(comment=reason, immediately=true,
             alert_message="EXIT | " + reason)
else if strategy.position_size > 0
    strategy.cancel("VWAP Short")
    strategy.cancel("Short Exit")
    strategy.exit("Long Exit", "VWAP Long", stop=workingLongStop, limit=targetLong,
         comment_profit="VWAP TARGET", comment_loss="STOP LOSS",
         alert_profit="EXIT BUY | VWAP TARGET", alert_loss="EXIT BUY | STOP LOSS")
else if strategy.position_size < 0
    strategy.cancel("VWAP Long")
    strategy.cancel("Long Exit")
    strategy.exit("Short Exit", "VWAP Short", stop=workingShortStop, limit=targetShort,
         comment_profit="VWAP TARGET", comment_loss="STOP LOSS",
         alert_profit="EXIT SELL | VWAP TARGET", alert_loss="EXIT SELL | STOP LOSS")
else
    bool bandsReady = not na(stdevVal) and stdevVal > 0
    bool canEnter = inTradingWindow and not inCooldown and bandsReady
    float riskCash = math.max(strategy.equity, 0.0) * riskPerTradePct / 100.0
    float pointValue = syminfo.pointvalue
    bool validLong = canEnter and allowLongs and pointValue > 0 and
         stopLong < entryLong and entryLong < targetLong
    bool validShort = canEnter and allowShorts and pointValue > 0 and
         targetShort < entryShort and entryShort < stopShort
 
    if validLong
        float qtyLong = math.floor(riskCash / ((entryLong - stopLong) * pointValue) / quantityStep) * quantityStep
        if qtyLong > 0
            workingLongStop := stopLong
            strategy.entry("VWAP Long", strategy.long, qty=qtyLong, limit=entryLong,
                 oca_name="VWAP Entries", oca_type=strategy.oca.cancel,
                 comment="BUY", alert_message="BUY | LOWER 3 SD")
            strategy.exit("Long Exit", "VWAP Long", stop=workingLongStop, limit=targetLong,
                 comment_profit="VWAP TARGET", comment_loss="STOP LOSS",
                 alert_profit="EXIT BUY | VWAP TARGET", alert_loss="EXIT BUY | STOP LOSS")
        else
            strategy.cancel("VWAP Long")
            strategy.cancel("Long Exit")
    else
        strategy.cancel("VWAP Long")
        strategy.cancel("Long Exit")
 
    if validShort
        float qtyShort = math.floor(riskCash / ((stopShort - entryShort) * pointValue) / quantityStep) * quantityStep
        if qtyShort > 0
            workingShortStop := stopShort
            strategy.entry("VWAP Short", strategy.short, qty=qtyShort, limit=entryShort,
                 oca_name="VWAP Entries", oca_type=strategy.oca.cancel,
                 comment="SELL", alert_message="SELL | UPPER 3 SD")
            strategy.exit("Short Exit", "VWAP Short", stop=workingShortStop, limit=targetShort,
                 comment_profit="VWAP TARGET", comment_loss="STOP LOSS",
                 alert_profit="EXIT SELL | VWAP TARGET", alert_loss="EXIT SELL | STOP LOSS")
        else
            strategy.cancel("VWAP Short")
            strategy.cancel("Short Exit")
    else
        strategy.cancel("VWAP Short")
        strategy.cancel("Short Exit")
 
// FILLED-TRADE LABELS: include trades that open and close on one bar.
// Labels are placed on recorded fill bars/prices once fills are observed.
f_entryLabel(int fillTime, float fillPrice, bool isLong) =>
    label.new(fillTime, fillPrice,
         (isLong ? "BUY" : "SELL") + "\n" + str.tostring(fillPrice, format.mintick),
         xloc=xloc.bar_time, yloc=yloc.price,
         style=isLong ? label.style_label_up : label.style_label_down,
         color=isLong ? color.green : color.red, textcolor=color.white, size=size.small)
 
var int labeledClosedTrades = 0
var int lastLabeledEntry = -1
if strategy.closedtrades > labeledClosedTrades
    for tradeNumber = labeledClosedTrades to strategy.closedtrades - 1
        bool wasLong = strategy.closedtrades.size(tradeNumber) > 0
        if showSignals
            if tradeNumber > lastLabeledEntry
                f_entryLabel(strategy.closedtrades.entry_time(tradeNumber),
                     strategy.closedtrades.entry_price(tradeNumber), wasLong)
                lastLabeledEntry := tradeNumber
            float exitPrice = strategy.closedtrades.exit_price(tradeNumber)
            string exitReason = strategy.closedtrades.exit_comment(tradeNumber)
            label.new(strategy.closedtrades.exit_time(tradeNumber), exitPrice,
                 (wasLong ? "EXIT BUY" : "EXIT SELL") + "\n" + exitReason +
                 "\n" + str.tostring(exitPrice, format.mintick),
                 xloc=xloc.bar_time, yloc=yloc.price,
                 style=wasLong ? label.style_label_down : label.style_label_up,
                 color=exitReason == "STOP LOSS" ? color.orange : color.blue,
                 textcolor=color.white, size=size.small)
    labeledClosedTrades := strategy.closedtrades
if showSignals and strategy.opentrades > 0 and strategy.closedtrades > lastLabeledEntry
    f_entryLabel(strategy.opentrades.entry_time(0), strategy.opentrades.entry_price(0),
         strategy.opentrades.size(0) > 0)
    lastLabeledEntry := strategy.closedtrades
 
// CHART LEVELS
float activeStop = strategy.position_size > 0 ? workingLongStop : strategy.position_size < 0 ? workingShortStop : na
float activeTarget = strategy.position_size > 0 ? targetLong : strategy.position_size < 0 ? targetShort : na
plot(showBands and inSession ? vwapVal : na, "VWAP", color=color.yellow, linewidth=2, style=plot.style_linebr)
plot(showBands and inSession ? band1Upper : na, "+1 SD", color=color.new(color.gray, 60), style=plot.style_linebr)
plot(showBands and inSession ? band1Lower : na, "-1 SD", color=color.new(color.gray, 60), style=plot.style_linebr)
plot(showBands and inSession ? band2Upper : na, "+2 SD", color=color.new(color.gray, 35), style=plot.style_linebr)
plot(showBands and inSession ? band2Lower : na, "-2 SD", color=color.new(color.gray, 35), style=plot.style_linebr)
plot(showBands and inSession ? band3Upper : na, "+3 SD", color=color.red, style=plot.style_linebr)
plot(showBands and inSession ? band3Lower : na, "-3 SD", color=color.green, style=plot.style_linebr)
plot(showTradeLevels ? activeStop : na, "Active Stop Loss", color=color.orange, linewidth=2, style=plot.style_linebr)
plot(showTradeLevels ? activeTarget : na, "Dynamic VWAP Target", color=color.aqua, linewidth=2, style=plot.style_linebr)

← 返回列表