TradingView strategy research

Red-to-green trading strategy: previous-close reclaims

A red-to-green trading strategy buys a reclaim of the previous regular-session close after price has traded below it during the current session. This page defines a specific long-side experiment: observe a below-baseline bar, wait for a later completed close crossing above the baseline, allow at most two entry attempts, and exit after a close back at or below the baseline. The reference is fixed before the signal; neither the day's eventual high nor its eventual closing color defines an entry.

See the decision guide

Freeze the previous trading session's close

Let B be the previous completed regular-session daily close from the selected TradingView feed. At the first calculation after the 09:30 bar closes, store B for the new session. That daily reference was already known before the open. On a Monday, the previous available trading session can be Friday; after an exchange holiday it can be earlier. Calendar yesterday is not the definition. The daily feed close may differ from a closing-auction print or the final intraday trade, so record the ticker, feed and adjustment settings.

  • NYSE core equity trading is normally 09:30 to 16:00 Eastern time. This experiment restricts activity to the morning and uses America/New_York, which follows daylight-saving changes. The chart display timezone does not change this clock.
  • The script requests close[1] from a regular-session daily ticker with lookahead_on, then freezes it for the session. The offset is essential: requesting the current daily close would introduce developing or future information.
  • Use the same corporate-action adjustment convention for daily and intraday data. The ticker modification preserves the chart ticker context while selecting regular hours. Verify split and dividend dates in the feed; a watchlist percentage can use a different reference.
  • Premarket and postmarket prices do not arm this version. Extended-hours charts are rejected explicitly so switching the chart session cannot silently change the order population.

Use an observable state sequence

The following choices are an original research protocol, not a universal definition or a measured edge. Evaluate one transition per completed bar. Equality matters: low must be strictly below B to arm; an entry close must be strictly above B; an exit close at B already invalidates the reclaim.

  • A gap below B qualifies as below-baseline trading once the opening bar completes. Opening above B is also eligible if price subsequently trades below and reclaims. A gap below is not mandatory.
  • A session that never trades below B has no setup. A below-baseline wick followed by an above-baseline close does not authorize an intrabar fill; a later close-to-close crossing is still required.
  • An attempt counts when an entry is submitted, including an unfilled or rejected entry. If no position is visible at the next calculation, the script ends that session instead of repeatedly resubmitting.
  • Missing one-minute bars cancel the remaining session when detected. New sessions discard the old armed state and old reference. No intraday high, future maximum or retrospective winner label is used.
State or eventDecision at the completed barNext state
New sessionRequire the first observed bar to open at 09:30, a positive B, and no residual position. Reset the attempt counter.WAIT
WAITA regular-session bar has low < B. It can arm even if it closes above B, but cannot enter on this same bar.ARMED
ARMEDOn a later bar require previous close <= B and current close > B. Submit one long market order if attempts remain.ENTRY_PENDING; add one attempt
Filled longOn the next calculation, a positive position confirms the entry fill. Hold while close > B.LONG
Failed reclaimWhile long, close <= B submits a market exit. No retry is evaluated on this decision bar.EXIT_PENDING
Flat after exitIf attempts remain, this new flat bar can arm only through its own low < B. A later crossing close is required again.ARMED or WAIT
Attempt cap or cutoffTwo submitted entries exhaust the default allowance. At 11:00, request any remaining exit and stop entries until next session.DONE

Keep decisions, fills and losses on different timestamps

At the 09:32 close, the bar opening at 09:31 is complete. An entry decided then is normally filled at the 09:32 bar open, with the configured slippage. These events share a clock boundary but have a causal order: close calculation first, following-bar fill second. The code disables on-close fills, intrabar recalculation and recalculation after fills.

  • All entries and exits are market orders. A failed-reclaim close is an exit condition, not a protective stop order resting at B. A gap or sharp drop can create a loss much larger than the distance to B.
  • The 10:59 bar closes at 11:00 and submits the time exit before considering any entry. No new entry decision is permitted at 11:00. A normal exit fills at the 11:00 bar open; a halt can delay it until a later available tick.
  • Default sizing is 100 shares, $100,000 initial capital, no pyramiding and 100% long margin. It is fixed share sizing, not fixed dollar risk. An expensive stock or depleted equity can prevent a fill.
  • The example charges $0.005 per share per side and one tick of adverse slippage per market order. These are research assumptions, not broker quotes. Spread, variable liquidity and market impact require separate cost scenarios.

Reproduce a failed first attempt and a second reclaim

These invented one-minute OHLC bars use B = $100, a $0.01 tick and two allowed attempts. Times are bar openings in New York; decisions occur one minute later. Every bar is present. The following rows are sufficient to reconstruct the two entry decisions without seeing any later high.

  • First trade net: 100 × (99.87 - 100.13) - 2 × 100 × 0.005 = -$27. Second trade net: 100 × (99.97 - 100.15) - $1 = -$19. Combined net is -$46. Slippage is already in the fill prices; do not deduct it again.
  • Never-below branch: if every low is at least B, even many closes above B leave the state WAIT and produce zero entry decisions.
  • Reset branch: if the 10:58 bar arms an untraded setup, the 11:00 cutoff retires it. The next session starts WAIT with its own B and attempt count zero. An opening close above the new B cannot inherit yesterday's armed state.
  • The repository fixture additionally checks a same-bar dip-and-reclaim, a missing-minute shutdown, an unavailable entry fill and the time-exit boundary. It tests the specified state machine, not profitability or TradingView broker-emulator equivalence.
Bar openOpen / high / low / closeDecision at bar close
09:3099.80 / 99.95 / 99.70 / 99.9009:31: arm below 100. No order.
09:3199.90 / 100.15 / 99.85 / 100.1009:32: first crossing close. Submit attempt 1.
09:32100.12 / 100.20 / 99.80 / 99.90Entry fills at 100.13 with one tick slippage. 09:33: failed-reclaim exit decision.
09:3399.88 / 99.99 / 99.70 / 99.85Exit fills at 99.87. 09:34: now flat, fresh below-baseline bar arms retry.
09:3499.86 / 100.18 / 99.80 / 100.1209:35: second crossing close. Submit attempt 2.
09:35100.14 / 100.25 / 100.05 / 100.20Entry fills at 100.15. 09:36: hold. Attempts stay at 2.
09:36100.20 / 100.22 / 99.90 / 100.0009:37: equality at 100 triggers the second failed-reclaim exit.
09:3799.98 / 100.15 / 99.90 / 100.10Exit fills at 99.97. 09:38: cap reached; no third entry.

Pine Script v6 research strategy

Paste the complete source into TradingView Pine Editor and use standard one-minute candles with Regular trading hours selected on a US stock whose exchange timezone is America/New_York. R marks the completed entry-decision bar and F the failed-reclaim decision bar. The Data Window exposes the frozen reference, state and submitted attempt count. Compare those values with the timeline before interpreting a strategy report.

Original long-only research example. The final source passed Pineify syntax validation; syntax validation does not establish market performance or verify a chart feed.pine
//@version=6
strategy("Previous close reclaim research", overlay = true, initial_capital = 100000,
     pyramiding = 0, margin_long = 100, commission_type = strategy.commission.cash_per_contract,
     commission_value = 0.005, slippage = 1, process_orders_on_close = false,
     calc_on_every_tick = false, calc_on_order_fills = false)
int maxAttempts = input.int(2, "Maximum entry attempts per session", minval = 1, maxval = 3)
int shares = input.int(100, "Shares per entry", minval = 1)
string zone = "America/New_York"
if barstate.isfirst
    if not chart.is_standard or not timeframe.isminutes or timeframe.multiplier != 1
        runtime.error("Use standard one-minute candles.")
    if syminfo.type != "stock" or syminfo.timezone != zone or syminfo.session != session.regular
        runtime.error("Use a US stock with New York exchange time and regular session selected.")
string regularTicker = ticker.modify(syminfo.tickerid, session = session.regular)
float priorClose = request.security(regularTicker, "1D", close[1], lookahead = barmerge.lookahead_on)
bool newSession = barstate.isfirst or time("1D") != time("1D")[1]
int openMinute = hour(time, zone) * 60 + minute(time, zone)
int closeMinute = hour(time_close, zone) * 60 + minute(time_close, zone)
// 0 WAIT, 1 ARMED, 2 ENTRY_PENDING, 3 LONG, 4 EXIT_PENDING, 5 DONE
var int state = 5
var int attempts = 0
var float baseline = na
bool entryDecision = false
bool failureDecision = false
if barstate.isconfirmed
    if newSession
        strategy.cancel_all()
        baseline := priorClose
        attempts := 0
        state := openMinute == 570 and not na(baseline) and baseline > 0 ? 0 : 5
        if strategy.position_size != 0
            strategy.close_all(comment = "Residual position at new session")
            state := 5
    bool missingMinute = not newSession and time != time_close[1]
    bool stopSession = missingMinute or closeMinute >= 660 or not session.ismarket
    if stopSession
        strategy.cancel_all()
        if strategy.position_size > 0
            strategy.close_all(comment = "Time or data exit")
        state := 5
    else if state != 5
        if strategy.position_size > 0
            state := 3
            if close <= baseline
                strategy.close("Long", comment = "Failed reclaim")
                state := 4
                failureDecision := true
        else if state == 2
            // No filled position at the next calculation: stop, do not keep resubmitting.
            strategy.cancel_all()
            state := 5
        else if attempts >= maxAttempts
            state := 5
        else if state == 4
            // Exit has filled. This flat bar can arm a fresh attempt, but cannot enter.
            state := low < baseline ? 1 : 0
        else if state == 0
            if low < baseline
                state := 1
        else if state == 1 and close > baseline and close[1] <= baseline
            strategy.entry("Long", strategy.long, qty = shares)
            attempts += 1
            state := 2
            entryDecision := true
plot(baseline, "Frozen previous regular close", color = color.blue, style = plot.style_stepline)
plot(state, "State: 0 wait, 1 armed, 2 pending, 3 long, 4 exit, 5 done", display = display.data_window)
plot(attempts, "Attempts submitted", display = display.data_window)
plotshape(entryDecision, "Entry decision at bar close", shape.triangleup, location.belowbar, color.green, text = "R")
plotshape(failureDecision, "Failure decision at bar close", shape.xcross, location.abovebar, color.red, text = "F")

Data boundaries that can change the experiment

A one-minute OHLC bar reveals its low and final close, but not every intrabar crossing. The separate arming bar and close-to-close confirmation avoid pretending to know that path. A tick-triggered entry, multiple confirmations or a volume filter would be a different strategy and must keep its own decision log.

  • Daily, higher intraday, nonstandard and extended-session charts are outside this implementation. Forex, futures and crypto need different session and reference definitions; do not transplant this US equity clock.
  • A missing 09:30 bar disables that session. Missing later minutes end it when the gap is observed. The script cannot detect a halt before a new bar arrives, and an order already pending can fill on the first bar after the gap before that bar's closing calculation detects the gap.
  • Normal early-close sessions still include the 11:00 morning cutoff; holidays have no new session bars. Exceptional closures or halts before 11:00 can leave an exit pending beyond the intended window. The code cannot guarantee flatness at a wall-clock time with no tradable tick.
  • If a position survives into a new session, request an exit and disable new entries for that session. Keep the delayed fill in results. Do not erase the trade or assign an unavailable prior-session closing fill.
  • Record missing daily history, corporate actions, delayed openings, chart timezone display and data revisions. A positive baseline is necessary but cannot establish that the feed is complete or economically comparable.

Compare retry policies only after the baseline matches

Save the symbol, regular-session setting, test dates, source version, state log, order properties and costs. First reproduce the entry-decision times and exit reasons. Then compare maximum attempts of one and two on the same development sample; retain a later date range for a separate evaluation. More attempts increase exposure to both recoveries and repeated failed reclaims.

  • Report first-attempt and retry counts separately, including rejected orders, missing-data sessions and never-below sessions. A trade list alone cannot reconstruct every skipped setup.
  • Keep fixed share size when comparing the two attempt policies, then test separate cost assumptions. Track net average trade, drawdown and total exposure alongside net profit. No performance figures are claimed here.
  • Pine Script AI Coding Agent can help revise the written rule set into a Pine draft. Require the same observable states, review the source and repeat syntax and timestamp checks after changes.
  • Strategy Optimizer compares exposed strategy input combinations. Use it for the attempt-count input after the baseline is checked. Set held-out dates and perform that evaluation separately; this workflow does not claim automatic walk-forward validation.
Where Pineify fits

Pine Script AI Coding Agent

Draft a variation of the explicit previous-close, confirmation and retry rules, then inspect the Pine source and its decision timestamps.

Also useful: Strategy Optimizer. Compare exposed attempt-count inputs after verifying the baseline. Evaluate retained settings separately on dates not used to choose them.

Draft my reclaim rules

Frequently asked questions

Educational research, not investment advice. Prices, costs and rules are illustrative; no market performance test is presented. A failed-reclaim close is not a guaranteed stop price. Gaps and delayed fills can cause substantial losses. Backtests and parameter searches do not guarantee future returns.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.