OCO Doubling Range Breakout

Who7is7Like7God · study · 237 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
indicator("OCO Doubling Range Breakout", overlay=true, max_boxes_count=500, max_labels_count=500)
 
// === Publication Description ===
// OCO Doubling Range Breakout is a visual research indicator I developed to demonstrate a structured risk-management method using staged position sizing, directional reversals, and a predefined stopping point.
//
// The project focuses on how exposure and cumulative losses evolve across a sequence of entries. A time-defined price range provides the setting for demonstrating the method.
//
// The underlying model uses a 1 → 2 → 4 position-size progression. An unsuccessful entry is closed at the opposite range boundary, where the next position reverses direction with twice the previous size. The sequence permits an initial entry and two reversals. A further adverse crossing ends the setup.
//
// With targets placed one range width beyond each entry boundary, the theoretical payoff structure is:
// - First-stage target: +1 base unit.
// - Second-stage target: −1 + 2 = +1 base unit.
// - Third-stage target: −1 − 2 + 4 = +1 base unit.
// - Full unsuccessful sequence: −1 − 2 − 4 = −7 base units.
//
// A base unit represents the value of one range width at the initial position size. These calculations assume execution exactly at the specified levels and exclude commissions and slippage.
//
// The model has a negative risk–reward profile: risking 7 units to earn 1 unit per completed setup. Its theoretical breakeven win rate is 87.5% before trading costs, calculated as 7 ÷ (7 + 1). Seven successful setups offset one full loss.
//
// Later positions require greater exposure to offset accumulated losses, while a complete losing sequence outweighs several successful setups. The progression has a fixed endpoint rather than continuing indefinitely. Trading costs increase the win rate required to break even, making the frequency and clustering of complete losing sequences central to evaluating the model.
//
// The indicator displays a yellow range box, a green box marking the outer target boundaries, small labels identifying simulated entries and outcomes, and a compact table showing entry levels, target levels, current state, and stage count.
//
// The default range window is 18:00–23:00 New York time (6:00–11:00 PM). The range develops during this window and locks at 23:00, after which the indicator tracks the breakout sequence. The model state resets at the next daily 18:00 boundary. Start and end times are adjustable.
//
// This implementation visualizes the model’s decision sequence. Position sizing is conceptual: the indicator does not place orders, calculate account-specific contract quantities, or provide a broker-executed performance record. Outcomes use chart-bar highs and lows; when several levels are touched within one candle, their actual order cannot be established from that candle alone. Developing-bar labels and states may change before the candle closes. The daily reset clears an unfinished sequence without recording a realized closing result.
//
// The purpose of this project is to make the risk structure transparent and inspectable: how exposure increases, how prior losses affect recovery requirements, and where the sequence terminates. Its effectiveness requires separate testing with realistic execution assumptions and trading costs. A high win rate alone does not establish profitability.
 
// === Inputs ===
startH = input.int(18, "Start Hour", minval=0, maxval=23, step=1)
startM = input.int(0, "Start Minute", minval=0, maxval=59, step=15)
endH = input.int(23, "End Hour", minval=0, maxval=23, step=1)
endM = input.int(0, "End Minute", minval=0, maxval=59, step=15)
chart = input.bool(true, "Show Table")
tradeAmount = input.int(50, "Rolling Trade Amount", minval=1)
BreakevenPercentage = input.string("87.5 percent", "Breakeven Percentage")
showTradeTags = input.bool(true, "Show Entry / TP / SL Tags", group="Chart Tags")
tablePosition = input.string("Top Right", "Table Position", options=["Top Right", "Middle Right", "Bottom Right"], group="Table")
pos = switch tablePosition
    "Top Right" => position.top_right
    "Middle Right" => position.middle_right
    "Bottom Right" => position.bottom_right
 
// === Session Times ===
nyYear = year(time, "America/New_York")
nyMonth = month(time, "America/New_York")
nyDay = dayofmonth(time, "America/New_York")
sessStart = timestamp("America/New_York", nyYear, nyMonth, nyDay, startH, startM)
sessEnd = timestamp("America/New_York", nyYear, nyMonth, nyDay, endH, endM)
dayStart = timestamp("America/New_York", nyYear, nyMonth, nyDay, 18, 0)
inRange = time >= sessStart and time < sessEnd
onLock = time >= sessEnd and time[1] < sessEnd
newTradeDay = time >= dayStart and (na(time[1]) or time[1] < dayStart)
 
// === Box State ===
var float highR = na
var float lowR = na
var int boxStart = na
var int boxEnd = na
var bool liveBoxes = false
var box rangeBox = na
var box fullBox = na
var float fullDist = na
 
if inRange and not inRange[1]
    highR := high
    lowR := low
    boxStart := bar_index
    liveBoxes := true
    rangeBox := box.new(bar_index, highR, bar_index, lowR, border_color=color.yellow, border_width=1, bgcolor=color.new(color.yellow, 100))
    fullBox := box.new(bar_index, highR, bar_index, lowR, border_color=color.green, border_width=1, bgcolor=color.new(color.green, 100))
if inRange
    highR := math.max(highR, high)
    lowR := math.min(lowR, low)
    boxEnd := bar_index
    if liveBoxes
        float rng = highR - lowR
        fullDist := rng * 1
        box.set_right(rangeBox, boxEnd)
        box.set_top(rangeBox, highR)
        box.set_bottom(rangeBox, lowR)
        box.set_right(fullBox, boxEnd)
        box.set_top(fullBox, highR + fullDist)
        box.set_bottom(fullBox, lowR - fullDist)
if onLock and liveBoxes
    box.new(boxStart, highR, boxEnd, lowR, border_color=color.yellow, border_width=1, bgcolor=color.new(color.yellow, 100))
    box.new(boxStart, highR + fullDist, boxEnd, lowR - fullDist, border_color=color.green, border_width=1, bgcolor=color.new(color.green, 100))
    box.delete(rangeBox)
    box.delete(fullBox)
    liveBoxes := false
 
// === Trade State Logic ===
var int flips = 0
var string tradeState = "WAITING"
var bool canTrade = false
if onLock
    canTrade := true
var int entryTime = na
enterLong = high >= highR and tradeState[1] == "WAITING" and canTrade
enterShort = low <= lowR and tradeState[1] == "WAITING" and canTrade
if enterLong or enterShort
    entryTime := time
if enterLong
    tradeState := "LONG ACTIVE"
    flips += 1
if enterShort
    tradeState := "SHORT ACTIVE"
    flips += 1
if high >= highR and tradeState[1] == "SHORT ACTIVE" and canTrade
    tradeState := "LONG ACTIVE"
    flips += 1
if low <= lowR and tradeState[1] == "LONG ACTIVE" and canTrade
    tradeState := "SHORT ACTIVE"
    flips += 1
if high >= highR + fullDist and flips < 4 and canTrade
    tradeState := "WIN"
if low <= lowR - fullDist and flips < 4 and canTrade
    tradeState := "WIN"
if flips == 4
    tradeState := "LOSS"
if newTradeDay
    tradeState := "WAITING"
    flips := 0
    canTrade := false
    entryTime := na
 
// === Rolling Last-N Outcomes ===
var array<int> lastN = array.new_int()
winEvent = tradeState == "WIN" and tradeState[1] != "WIN"
lossEvent = tradeState == "LOSS" and tradeState[1] != "LOSS"
if winEvent
    array.push(lastN, 1)
if lossEvent
    array.push(lastN, 0)
if array.size(lastN) > tradeAmount
    array.shift(lastN)
int tradesN = array.size(lastN)
int winsN = 0
if tradesN > 0
    for i = 0 to tradesN - 1
        winsN += array.get(lastN, i)
int lossesN = tradesN - winsN
float winRateN = tradesN > 0 ? winsN * 100.0 / tradesN : na
float rTotalN = winsN * 0.14285 - lossesN * 1.0
 
// === Paired Range / Duration Statistics ===
curRange = highR - lowR
var array<int> outN = array.new_int()
var array<float> rngN = array.new_float()
var array<float> durN = array.new_float()
float durMin = not na(entryTime) ? (time - entryTime) / 60000.0 : na
if winEvent
    array.push(outN, 1)
    array.push(rngN, curRange)
    array.push(durN, durMin)
    entryTime := na
if lossEvent
    array.push(outN, 0)
    array.push(rngN, curRange)
    array.push(durN, durMin)
    entryTime := na
if array.size(outN) > tradeAmount
    array.shift(outN)
    array.shift(rngN)
    array.shift(durN)
int wCount = 0
int lCount = 0
float sumWinRng = 0.0
float sumLossRng = 0.0
float sumWinDur = 0.0
float sumLossDur = 0.0
int n = array.size(outN)
if n > 0
    for i = 0 to n - 1
        int o = array.get(outN, i)
        float r = array.get(rngN, i)
        float d = array.get(durN, i)
        if o == 1
            wCount += 1
            sumWinRng += r
            if not na(d)
                sumWinDur += d
        else
            lCount += 1
            sumLossRng += r
            if not na(d)
                sumLossDur += d
float avgWinRange = wCount > 0 ? sumWinRng / wCount : na
float avgLossRange = lCount > 0 ? sumLossRng / lCount : na
float avgWinMin = wCount > 0 ? sumWinDur / wCount : na
float avgLossMin = lCount > 0 ? sumLossDur / lCount : na
float liveMin = not na(entryTime) ? (time - entryTime) / 60000.0 : na
 
// === Entry / TP / Stop-Loss Tags ===
// Tags follow the original indicator's simulated state changes, not broker fills.
// Entry conditions are used directly so an entry followed by a same-bar outcome
// still receives an entry tag. The fourth edge touch is the final stop, not an entry.
if showTradeTags and not newTradeDay
    bool buySignal = enterLong or (high >= highR and tradeState[1] == "SHORT ACTIVE" and canTrade)
    bool sellSignal = enterShort or (low <= lowR and tradeState[1] == "LONG ACTIVE" and canTrade)
    if buySignal and flips < 4
        label.new(bar_index, highR, (enterLong ? "BUY ENTRY" : "REVERSE BUY") + "\nStage " + str.tostring(flips), yloc=yloc.price, style=label.style_label_up, color=color.green, textcolor=color.white, size=size.tiny)
    if sellSignal and flips < 4
        label.new(bar_index, lowR, (enterShort ? "SELL ENTRY" : "REVERSE SELL") + "\nStage " + str.tostring(flips), yloc=yloc.price, style=label.style_label_down, color=color.red, textcolor=color.white, size=size.tiny)
    if winEvent
        bool upperTargetHit = high >= highR + fullDist
        float tpPrice = upperTargetHit ? highR + fullDist : lowR - fullDist
        label.new(bar_index, tpPrice, "TAKE PROFIT\n" + str.tostring(tpPrice, format.mintick), yloc=yloc.price, style=upperTargetHit ? label.style_label_down : label.style_label_up, color=color.lime, textcolor=color.black, size=size.tiny)
    if lossEvent
        float slPrice = tradeState[1] == "LONG ACTIVE" ? lowR : highR
        label.new(bar_index, slPrice, "STOP LOSS\n" + str.tostring(slPrice, format.mintick), yloc=yloc.price, style=tradeState[1] == "LONG ACTIVE" ? label.style_label_up : label.style_label_down, color=color.maroon, textcolor=color.white, size=size.tiny)
 
// === Table ===
var table t = na
var string lastTablePosition = ""
if na(t) or tablePosition != lastTablePosition
    if not na(t)
        table.delete(t)
    t := table.new(pos, 3, 4, border_width=1)
    lastTablePosition := tablePosition
if not chart
    table.clear(t, 0, 0, 2, 3)
if chart
    table.cell(t, 0, 0, "LEVEL", bgcolor=color.rgb(40, 40, 40), text_color=color.white)
    table.cell(t, 1, 0, "BUY", bgcolor=color.rgb(40, 40, 40), text_color=color.white)
    table.cell(t, 2, 0, "SELL", bgcolor=color.rgb(40, 40, 40), text_color=color.white)
    table.cell(t, 0, 1, "Entry", text_color=color.white)
    table.cell(t, 1, 1, str.tostring(highR), text_color=color.green)
    table.cell(t, 2, 1, str.tostring(lowR), text_color=color.red)
    table.cell(t, 0, 2, "Final", text_color=color.white)
    table.cell(t, 1, 2, str.tostring(highR + fullDist), text_color=color.fuchsia)
    table.cell(t, 2, 2, str.tostring(lowR - fullDist), text_color=color.purple)
    table.cell(t, 0, 3, "State", text_color=color.white)
    table.cell(t, 1, 3, tradeState, text_color=color.white)
    table.cell(t, 2, 3, str.tostring(flips), text_color=color.yellow)

← 返回列表