Myth Busting E02 - Quick Flip Scalper [PyneSys]

PyneSys · strategy · 364 行 · 点赞 35 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//              [] ##          PyneSys
//           [] [] ## ##
//        [] [] [] ## ## ##
//     [] [] [] [] ## ## ## ##
//  [] [] [] [] [] ## ## ## ## ##
//              || ||
// ============================================================================
// SCRIPT: Quick Flip Scalper - Native Five-Minute Strategy
// SCRIPT AUTHOR: PyneSys
// Copyright (c) 2026 PyneSys LLC
// SPDX-License-Identifier: MPL-2.0
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// STRATEGY CONCEPT: Opening-range reversal with causal candle-pattern entries.
// IDEA ATTRIBUTION: Carl / ProRealAlgos (trading concept only)
//
// DESCRIPTION
// Fade the first regular-session 15-minute candle after a reversal outside its
// range. Green opening: short above. Red opening: long below. Daily ATR filters
// the opening range. Signals and broker emulation both use native FIVE-MINUTE candles.
//
// EXPLICIT INTERPRETATIONS
// The source leaves pattern geometry, order lifetime and retries incomplete.
// Default: confirmed pattern, next-bar market fill, one filled trade/day,
// one-tick stop buffer, far-side target and regular-session closing exit.
// Pending orders expire at the next five-minute close or 11:00 New York.
// Previous COMPLETED provider daily ATR14 is used, never today's final range.
// A hammer has a rejection wick >= twice its body and opposite wick <= body.
// Engulfing means opposite-color full BODY coverage, including equal edges.
// Signal bodies must be strictly outside the box. Missing opening or signal
// bars invalidate that range. Doji openings cannot set a direction.
//
// OPTIONAL VARIANTS
// Intrabar stop: place an order after an opposite-color candle or a hammer.
// The next candle need not finish engulfing; its future low/high is unknown.
// Confirmed limit: after engulfing closes, wait for a retracement to the prior
// candle's extreme. Reject an already marketable limit to keep this distinct.
// Volume, extra confirmation, target and ATR switches are research hypotheses.
//
// BACKTEST SETTINGS
// Commission and slippage are zero for a cross-market gross research baseline.
// Broker, venue and instrument costs differ; no universal cost preset is assumed.
// Gross results exclude costs and are not achievable net returns. Set your own
// commission and slippage in Properties before assessing performance. Spread,
// funding and other applicable costs need an explicit model and are not
// automatically included. Separate cost-sensitivity reports are not these fills.
// Standard 5-minute candles plus provider daily data. One unit per trade; gross
// results by default. Set costs in Properties. Risk-normalized research reports
// are separate from account returns. Historical intrabar order follows the
// broker emulator; it is not observed tick execution. No profitability claim.
// ============================================================================
 
// Mechanical reading of an opening-range reversal lesson, not the creator's exact
// system. Pattern geometry, order lifetime, retries and the closing exit are our
// explicit research assumptions. Only completed five-minute candles can signal.
//
// Read from top to bottom: the default setup (a hammer or engulfing candle with
// its body outside the opening box, then a next-bar market entry) is complete by
// section 5. Sections 6 and 7 hold the optional research variants; they replace
// an interpretation or add one extra gate, and never change the default
// conditions above them. Section 8 places every order.
strategy("PyneSys E02 - Quick Flip Scalper", shorttitle="PyneSysE02", overlay=true,
     pyramiding=0, initial_capital=1000000, default_qty_type=strategy.fixed,
     default_qty_value=1, process_orders_on_close=false, calc_on_every_tick=false,
     calc_on_order_fills=false, commission_type=strategy.commission.percent,
     commission_value=0, slippage=0)
 
// ---------------------------------------------------------------------------
// 1. Inputs
// ---------------------------------------------------------------------------
// Defaults reproduce the episode's baseline. Every other choice is a separate
// research hypothesis; change one at a time to reproduce a reported variant.
string execution = input.string("Confirmed market", "Entry interpretation", options=["Confirmed market", "Intrabar stop", "Confirmed limit"])
float atrPercent = input.float(25.0, "Minimum opening range / daily ATR (%)", minval=0)
bool usePatterns = input.bool(true, "Require reversal pattern")
string locationRule = input.string("Body outside", "Signal location", options=["Body outside", "Wick outside", "Whole candle outside"])
int stopBufferTicks = input.int(1, "Stop buffer (ticks)", minval=0)
int maxTrades = input.int(1, "Maximum filled trades per day", minval=1)
bool extraConfirmation = input.bool(false, "Wait for next candle close beyond signal extreme")
bool volumeFilter = input.bool(false, "Volume above previous 20 signal candles")
string targetMode = input.string("Far boundary", "Target", options=["Far boundary", "Near boundary"])
bool moveStop = input.bool(false, "Move stop to near boundary after confirmed cross")
bool showSignals = input.bool(true, "Show candidate signals")
 
// ---------------------------------------------------------------------------
// 2. The session clock and the daily volatility yardstick
// ---------------------------------------------------------------------------
// Read the most recently completed daily ATR with lookahead OFF. Section 3
// freezes it on the first bar of each date, so the filter stays fixed even when
// the daily feed and the intraday venue have slightly different highs and lows.
float completedDailyAtr = request.security(syminfo.tickerid, "1D", ta.atr(14), lookahead=barmerge.lookahead_off)
// Dates and minutes are New York exchange time; 570 is 09:30 and 960 is 16:00.
string zone = "America/New_York"
int dateKey = year(time, zone) * 10000 + month(time, zone) * 100 + dayofmonth(time, zone)
int minuteOfDay = hour(time, zone) * 60 + minute(time, zone)
int closeMinute = hour(time_close, zone) * 60 + minute(time_close, zone)
bool rth = minuteOfDay >= 570 and minuteOfDay < 960
bool newDay = na(dateKey[1]) or dateKey != dateKey[1]
if barstate.isfirst and timeframe.period != "5"
    runtime.error("Use standard 5-minute candles; PyneCore handles order execution.")
 
// ---------------------------------------------------------------------------
// 3. Daily state: filled trades and the new-day reset
// ---------------------------------------------------------------------------
// var keeps a value from bar to bar; := updates it. Everything below belongs
// to one New York trading date and starts fresh on the next one.
var float dailyAtr = na
// The opening box and its direction: side +1 means a red opening (look for a
// long below the box), -1 a green opening (look for a short above it).
var float rangeOpen = na
var float rangeHigh = na
var float rangeLow = na
var int rangeCount = 0
var int side = 0
var bool rangeReady = false
var bool rangeAllowed = false
// Trade bookkeeping and the levels of the order or position in force.
var int fillsToday = 0
var int observedTrades = 0
var float stopLevel = na
var float targetLevel = na
var float orderLevel = na
var int expiry = na
var bool pending = false
// Optional extra confirmation: the level the next close has to beat.
var bool awaitingConfirmation = false
var float confirmLevel = na
var float confirmStop = na
var int confirmUntil = na
// The previous completed candle, for the engulfing check and limit entries,
// and a rolling 20-candle volume window for the optional volume gate.
var float prevO = na
var float prevH = na
var float prevL = na
var float prevC = na
var array<float> volumes = array.new<float>()
var float volumeSum = 0.0
 
// closedtrades + opentrades also catches an entry and exit within one five-minute bar.
int totalTrades = strategy.closedtrades + strategy.opentrades
if totalTrades > observedTrades
    fillsToday += totalTrades - observedTrades
    pending := false
observedTrades := totalTrades
 
if newDay
    dailyAtr := completedDailyAtr
    rangeOpen := na
    rangeHigh := na
    rangeLow := na
    rangeCount := 0
    side := 0
    rangeReady := false
    rangeAllowed := false
    fillsToday := 0
    pending := false
    awaitingConfirmation := false
    prevO := na
    prevH := na
    prevL := na
    prevC := na
 
// ---------------------------------------------------------------------------
// 4. The opening box: the first 15 minutes of the regular session
// ---------------------------------------------------------------------------
// Collect the three opening five-minute bars, 09:30 to 09:45. Missing bars
// invalidate the range, and a doji opening (close equal to open) sets no side.
// The daily ATR filter skips days whose box is narrower than atrPercent of the
// previous completed day's ATR; zero disables the filter.
if rth and minuteOfDay < 585
    if minuteOfDay == 570
        rangeOpen := open
        rangeHigh := high
        rangeLow := low
        rangeCount := 0
    rangeCount += 1
    rangeHigh := math.max(rangeHigh, high)
    rangeLow := math.min(rangeLow, low)
    if closeMinute == 585
        rangeReady := rangeCount == 3 and not na(rangeOpen) and rangeHigh > rangeLow
        side := close > rangeOpen ? -1 : close < rangeOpen ? 1 : 0
        rangeAllowed := rangeReady and side != 0 and (atrPercent == 0 or (not na(dailyAtr) and rangeHigh - rangeLow >= dailyAtr * atrPercent / 100.0))
 
// ---------------------------------------------------------------------------
// 5. The default setup: a reversal candle outside the box
// ---------------------------------------------------------------------------
// A signal candle is a complete regular-session five-minute bar that closes
// after the box and before 11:00 New York (660).
bool complete = minuteOfDay % 5 == 0 and time_close - time == 300000
bool eligible = rth and complete and rangeReady and minuteOfDay >= 585 and closeMinute < 660
bool longSide = side == 1
// Candle geometry: a hammer's rejection wick is at least twice its body and
// its opposite wick is at most the body; the body must be at least one tick.
float body = math.abs(close - open)
float upperWick = high - math.max(open, close)
float lowerWick = math.min(open, close) - low
bool hammerLong = body >= syminfo.mintick and lowerWick >= body * 2 and upperWick <= body
bool hammerShort = body >= syminfo.mintick and upperWick >= body * 2 and lowerWick <= body
// Engulfing: an opposite-color candle whose body covers the previous
// completed candle's whole body, equal edges included.
bool engulfUp = not na(prevO) and close > open and prevC < prevO and open <= prevC and close >= prevO
bool engulfDown = not na(prevO) and close < open and prevC > prevO and open >= prevC and close <= prevO
// By default the signal body must sit strictly outside the box.
bool bodyBelow = math.max(open, close) < rangeLow
bool bodyAbove = math.min(open, close) > rangeHigh
 
// ---------------------------------------------------------------------------
// 6. Optional entry interpretations
// ---------------------------------------------------------------------------
// Each choice replaces one part of the default reading; the default comes
// first. Intrabar stop places an order after any opposite-color candle or a
// hammer, because the next candle's final shape is still unknown. Confirmed
// limit waits for a completed engulfing candle, then a retracement.
bool outsideLong = switch locationRule
    "Body outside" => bodyBelow
    "Wick outside" => low < rangeLow
    "Whole candle outside" => high < rangeLow
bool outsideShort = switch locationRule
    "Body outside" => bodyAbove
    "Wick outside" => high > rangeHigh
    "Whole candle outside" => low > rangeHigh
bool patternLong = switch execution
    "Confirmed market" => hammerLong or engulfUp
    "Intrabar stop" => close < open or hammerLong
    "Confirmed limit" => engulfUp
bool patternShort = switch execution
    "Confirmed market" => hammerShort or engulfDown
    "Intrabar stop" => close > open or hammerShort
    "Confirmed limit" => engulfDown
bool setupLong = eligible and outsideLong and (not usePatterns or patternLong)
bool setupShort = eligible and outsideShort and (not usePatterns or patternShort)
// The opening candle's color decides which side is watched today.
bool candidate = longSide ? setupLong : setupShort
 
// ---------------------------------------------------------------------------
// 7. Optional extra gates
// ---------------------------------------------------------------------------
// Extra confirmation delays a candidate by one candle: the next complete close
// must break beyond the candidate's extreme, and the stop stays at the
// candidate candle. A new candidate on the confirming bar is not queued.
// Outside the entry window a pending confirmation is abandoned.
if closeMinute >= 660
    awaitingConfirmation := false
bool confirmNow = awaitingConfirmation and time_close == confirmUntil and (longSide ? close > confirmLevel : close < confirmLevel)
if eligible and awaitingConfirmation
    awaitingConfirmation := false
bool ready = extraConfirmation ? eligible and confirmNow : candidate
if extraConfirmation and candidate and not confirmNow
    awaitingConfirmation := true
    confirmLevel := longSide ? high : low
    confirmStop := longSide ? low - stopBufferTicks * syminfo.mintick : high + stopBufferTicks * syminfo.mintick
    confirmUntil := time_close + 300000
// Volume gate: the signal candle's volume beats the average of the previous
// 20 complete regular-session candles.
bool volumeOK = not volumeFilter or (array.size(volumes) == 20 and volume > volumeSum / 20.0)
 
// ---------------------------------------------------------------------------
// 8. Orders
// ---------------------------------------------------------------------------
// A new date starts without leftover orders. An unfilled entry order expires
// at the next five-minute close or at 11:00 New York, whichever comes first;
// cancel at that boundary after processing the last eligible bar's fills.
if newDay
    strategy.cancel_all()
if pending and (time_close >= expiry or closeMinute >= 660)
    strategy.cancel("Long")
    strategy.cancel("Short")
    pending := false
 
// Plan the levels from the signal candle. The stop sits one tick buffer beyond
// its extreme; the default target is the far side of the box. The entry price
// is the close for a market order, or the order level for stop/limit entries.
float candleStop = longSide ? low - stopBufferTicks * syminfo.mintick : high + stopBufferTicks * syminfo.mintick
float prospectiveStop = extraConfirmation ? confirmStop : candleStop
float referenceEntry = switch execution
    "Confirmed market" => close
    "Intrabar stop" => longSide ? high : low
    "Confirmed limit" => longSide ? prevH : prevL
float prospectiveTarget = switch targetMode
    "Far boundary" => longSide ? rangeHigh : rangeLow
    "Near boundary" => longSide ? rangeLow : rangeHigh
bool riskOK = longSide ? referenceEntry > prospectiveStop and prospectiveTarget > referenceEntry : referenceEntry < prospectiveStop and prospectiveTarget < referenceEntry
// Reject an already marketable limit, which would just be a market entry.
bool limitOK = execution != "Confirmed limit" or (longSide ? referenceEntry < close : referenceEntry > close)
 
// Reject codes for the Data Window: 1 range filtered or no side, 2 volume,
// 3 daily trade limit, 4 position already open, 5 invalid risk or limit level.
bool submitted = false
bool rejected = false
float signalStop = na
float signalEntry = na
float signalTarget = na
int rejectCode = 0
if ready
    signalStop := prospectiveStop
    signalEntry := referenceEntry
    signalTarget := prospectiveTarget
    rejectCode := not rangeAllowed ? 1 : not volumeOK ? 2 : fillsToday >= maxTrades ? 3 : strategy.position_size != 0 ? 4 : not riskOK or not limitOK ? 5 : 0
    rejected := rejectCode != 0
    if rejectCode == 0
        stopLevel := math.round_to_mintick(prospectiveStop)
        targetLevel := math.round_to_mintick(prospectiveTarget)
        orderLevel := math.round_to_mintick(referenceEntry)
        expiry := time_close + 300000
        pending := true
        submitted := true
        if longSide
            strategy.entry("Long", strategy.long, stop=execution == "Intrabar stop" ? orderLevel : na, limit=execution == "Confirmed limit" ? orderLevel : na)
            strategy.exit("Long bracket", "Long", stop=stopLevel, limit=targetLevel)
        else
            strategy.entry("Short", strategy.short, stop=execution == "Intrabar stop" ? orderLevel : na, limit=execution == "Confirmed limit" ? orderLevel : na)
            strategy.exit("Short bracket", "Short", stop=stopLevel, limit=targetLevel)
 
// Remember this candle. Only complete chart candles can become the previous
// engulfing candle or enter the volume window.
if rth
    prevO := complete ? open : na
    prevH := complete ? high : na
    prevL := complete ? low : na
    prevC := complete ? close : na
    if complete and not na(volume)
        array.push(volumes, volume)
        volumeSum += volume
        if array.size(volumes) > 20
            volumeSum -= array.shift(volumes)
 
// Keep the bracket in force. The optional move-stop rule acts only after a
// completed five-minute close beyond the near boundary, and only tightens.
if strategy.position_size > 0
    if moveStop and close > rangeLow
        stopLevel := math.max(stopLevel, rangeLow)
    strategy.exit("Long bracket", "Long", stop=stopLevel, limit=targetLevel)
if strategy.position_size < 0
    if moveStop and close < rangeHigh
        stopLevel := math.min(stopLevel, rangeHigh)
    strategy.exit("Short bracket", "Short", stop=stopLevel, limit=targetLevel)
// Close any position at the end of the regular session. immediately applies
// only to this closing market exit, never to entries.
if rth and (session.islastbar_regular or closeMinute == 960)
    strategy.cancel_all()
    strategy.close_all(comment="Session close", immediately=true)
    pending := false
 
// ---------------------------------------------------------------------------
// 9. Chart and research diagnostics
// ---------------------------------------------------------------------------
plot(rangeReady ? rangeHigh : na, "Opening high", color=color.teal, style=plot.style_linebr)
plot(rangeReady ? rangeLow : na, "Opening low", color=color.orange, style=plot.style_linebr)
plot(stopLevel, "Stop", color=color.red, style=plot.style_circles)
plot(targetLevel, "Target", color=color.green, style=plot.style_circles)
// Data Window only: the values the research harness checks bar by bar.
plot(dailyAtr, "Previous daily ATR", display=display.data_window)
plot(signalStop, "Signal stop", display=display.data_window)
plot(signalEntry, "Signal entry", display=display.data_window)
plot(signalTarget, "Signal target", display=display.data_window)
plot(rangeAllowed ? 1 : 0, "Range allowed", display=display.data_window)
plot(fillsToday, "Filled today", display=display.data_window)
plot(rejectCode, "Reject reason", display=display.data_window)
plotshape(showSignals and candidate, "Candidate", shape.circle, location.belowbar, color=color.gray, size=size.tiny)
plotshape(submitted, "Order submitted", shape.triangleup, location.belowbar, color=color.blue, size=size.tiny)
plotshape(rejected, "Rejected", shape.xcross, location.abovebar, color=color.orange, size=size.tiny)

← 返回列表