More screenshots

    Works with the AI tools you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIGitHub CopilotGitHub CopilotGemini CLIGemini CLI+20 more

    Pine Script Trading Strategy Debugger & Optimizer

    1

    The first objective is to understand the intended strategy behavior.

    $9.99

    Secure checkout via Stripe

    30-day refund guarantee

    Converts to your local currency at checkout

    0 installsSecurity scanned
    Pine Script Trading Strategy Debugger & Optimizer

    Pine Script Trading Strategy Debugger & Optimizer

    Example session with this skill installed

    Project
    Fictional TradingView strategy — MomentumRail v3.7

    Pine Version
    v5

    Script Type
    strategy

    Instrument
    MNQ1!

    Timeframe
    3 minutes

    Chart
    Standard Candles

    Session
    09:35–15:50 America/New_York

    Expected Strategy

    LONG

    Entry
    Fast EMA crosses above Slow EMA
    AND RSI > 55
    AND in session
    AND position is flat

    Stop
    1.5 ATR below original entry

    Target
    2R from original entry

    Trailing
    After price reaches +1R, trail 1 ATR below the highest price since activation.

    Pyramiding
    Disabled

    Reentry
    Allowed only after the previous position is fully closed and a new EMA crossover occurs.

    SHORT

    Symmetrical opposite logic.

    Alerts
    One BUY alert only when an actual confirmed long strategy entry is created.
    One SELL alert only when an actual confirmed short strategy entry is created.
    Separate EXIT alert when the position closes.

    Commission
    Already configured by user.

    Slippage
    Already configured by user.

    Observed Problems

    1. Multiple long entries occasionally appear even though pyramiding should be disabled.
    2. Stop-loss moves every bar before the trailing stop activates.
    3. Long trailing stop sometimes moves downward.
    4. Short take-profit is occasionally above the entry price.
    5. BUY alerts sometimes fire while already long.
    6. Strategy Tester entry marker appears one bar after the plotted BUY marker.
    7. On several historical trades the stop and target appear to be touched in the same candle.
    8. The strategy sometimes trades at 16:00 even though new entries should end at 15:50.
    9. Higher-timeframe 15-minute EMA filter appears suspiciously perfect historically.
    10. After a stopped trade, the next crossover sometimes does not open a position.
    11. User wants the strategy updated to the current supported Pine version if migration is safe.
    12. User wants cleaner architecture without materially changing strategy behavior.

    Relevant Existing Logic Description

    • longSignal is true while fastEMA > slowEMA rather than only on crossover.
    • session condition wraps both entry and exit logic.
    • stop price is recalculated every bar using close - ATR × multiplier.
    • trailing stop is calculated from current close.
    • same persistent trail variable is reused for long and short trades.
    • alertcondition uses longSignal, while strategy.entry uses longSignal AND inSession AND strategy.position_size == 0.
    • 15-minute filter uses higher-timeframe data.
    • strategy.exit references several order IDs.

    Requested Work

    • diagnose all logical bugs;
    • check repainting and lookahead;
    • correct entries;
    • correct SL/TP;
    • repair trailing stop;
    • verify pyramiding;
    • fix session behavior;
    • synchronize alerts;
    • explain chart-signal vs Strategy Tester fill timing;
    • review same-bar stop/target ambiguity;
    • migrate Pine version if appropriate;
    • refactor into clearer modules;
    • provide regression tests;
    • document every behavior-changing fix.

    Special Constraint

    Do not redesign the underlying trading strategy.
    Preserve the original economic intent wherever possible.

    • Read your context and instructions
    • Compiled the pine script trading
    • Generated the document

    === PINE SCRIPT TRADING STRATEGY DEBUG AUDIT ===

    Strategy
    MomentumRail v3.7

    Current Pine Version
    v5

    Target
    Current supported Pine version, subject to migration verification

    Primary Objective
    Repair execution and state defects without redesigning the underlying EMA/RSI trend-following model.

    === EXECUTIVE DIAGNOSIS ===

    The strategy contains several independent defects.

    The most material are

    1. Persistent long/short conditions are being treated as entry events.
    2. Fixed stops are being recalculated from the current close.
    3. Trailing stops are not monotonic.
    4. Long and short trailing states share persistent state.
    5. Short target direction contains a sign error.
    6. Alert logic is broader than actual strategy-entry logic.
    7. The session wrapper may be disabling protective exits.
    8. Session boundary behavior requires explicit timezone verification.
    9. The 15-minute higher-timeframe filter requires a repaint/lookahead review.
    10. Reentry state appears not to reset consistently after some stop exits.
    11. Same-bar stop/target events cannot be ordered confidently from standard 3-minute OHLC data alone.
    12. The plotted signal and strategy fill marker represent different stages of the order lifecycle.

    Severity Summary

    Critical
    Higher-timeframe lookahead must be ruled out.

    High
    Stop recalculation
    Trailing-stop regression
    Alert/order mismatch
    Session wrapper around exits
    Reentry state reset

    Medium
    Entry event architecture
    Short target sign
    Signal-vs-fill visualization

    Platform Limitation
    Same-bar stop/target ordering

    === ISSUE 1 — DUPLICATE / REPEATED ENTRY SIGNAL ===

    Observed

    longSignal remains true for every bar where:

    fastEMA > slowEMA

    Expected

    A new trade should require a fresh crossover after the previous trade closes.

    Root Cause

    The script is using a persistent regime condition as if it were a transition event.

    Current conceptual condition

    fastEMA > slowEMA

    Required transition

    Fast EMA crosses above Slow EMA.

    Recommended architecture

    longCross

    fresh bullish crossover event

    longSetup

    longCross
    AND RSI confirmation
    AND higher-timeframe confirmation

    longEntryAllowed

    longSetup
    AND inEntrySession
    AND position is flat
    AND cooldown/reentry state permits entry

    Final executable entry

    longEntry

    longEntryAllowed

    Expected Effect

    One new long setup per genuine crossover cycle rather than repeated eligibility while the EMAs remain bullish.

    === ISSUE 2 — FIXED STOP MOVES BEFORE TRAILING ACTIVATION ===

    Severity
    HIGH

    Expected

    Initial stop remains 1.5 ATR below the original entry until trailing activates.

    Observed

    Stop is recalculated each bar using

    Current Close - Current ATR × Multiplier

    Root Cause

    The script does not preserve the entry-time stop.

    Correct Architecture

    When a new long position is confirmed

    Capture

    entryPrice
    entryATR
    initialStop

    Conceptually

    initialStop =
    entryPrice - entryATR × 1.5

    Persist the value.

    Before trailing activation

    activeStop =
    initialStop

    After trailing activation

    activeStop =
    max(initialStop, trailingStop)

    Reset all stored values after returning flat.

    Important

    If the strategy intends dynamic ATR before trail activation, this would be a strategy change.

    Based on supplied requirements, the stop should be fixed from the original entry.

    === ISSUE 3 — LONG TRAILING STOP MOVES DOWNWARD ===

    Severity
    HIGH

    Observed

    Long trailing stop can decline.

    Expected

    Once activated, long trail can only tighten.

    Root Cause

    Candidate stop is recalculated from current close without preserving the prior best stop.

    Correct monotonic rule

    For long

    newTrail =
    max(previousTrail, candidateTrail)

    For short

    newTrail =
    min(previousTrail, candidateTrail)

    Reset after flat.

    === ISSUE 4 — SHARED LONG / SHORT TRAILING STATE ===

    Severity
    HIGH

    Observed

    Same persistent variable is reused.

    Risk

    A value from a previous long can contaminate a later short state or vice versa.

    Recommended

    Separate state conceptually into

    longTrailActive
    longTrailPrice

    shortTrailActive
    shortTrailPrice

    or rigorously reset one shared state during every direction transition.

    Separate state is easier to audit.

    === ISSUE 5 — SHORT TAKE-PROFIT DIRECTION ===

    Severity
    HIGH

    Expected

    Short profit target must be below entry.

    If percentage target

    Long
    Entry × (1 + targetPct)

    Short
    Entry × (1 - targetPct)

    If 2R target:

    Risk
    Absolute distance between Entry and Stop.

    Short Target
    Entry - Risk × 2

    Any short target above entry is directionally incorrect for a standard profit-taking limit.

    === ISSUE 6 — BUY ALERT WHILE ALREADY LONG ===

    Severity
    HIGH

    Current Alert

    longSignal

    Actual Strategy Entry

    longSignal
    AND inSession
    AND positionFlat

    Root Cause

    Alert logic represents setup intent, not executable entry.

    If the desired BUY alert means

    "An actual confirmed strategy long entry is being generated"

    then the alert should use the same final entry condition.

    Recommended

    buyAlertEvent =
    finalLongEntryCondition

    Also add

    Bar confirmation if required by strategy design.

    One-shot protection if the execution model can evaluate multiple times on a realtime bar.

    === ISSUE 7 — SESSION WRAPPER BLOCKS EXITS ===

    Severity
    HIGH

    Current Architecture

    if inSession
        entries
        exits
    

    Problem

    Once the session closes, protective stop/target logic may no longer be updated/submitted as intended.

    Recommended Separation

    ENTRY SESSION

    Controls
    New Long Entry
    New Short Entry

    PROTECTIVE EXIT LOGIC

    Remains active according to strategy risk rules.

    Conceptual

    if inEntrySession
        evaluate new entries
    
    if positionLong
    
    manage long stop / target / trail
    

    if positionShort
    manage short stop / target / trail

    This prevents session restrictions intended for entries from silently disabling risk management.

    === ISSUE 8 — ENTRY AT 16:00 ===

    Status
    REQUIRES TIMEZONE / BAR-TIMESTAMP VERIFICATION

    Supplied intended end
    15:50 America/New_York

    Check

    Session string
    Timezone argument
    Chart timezone
    Exchange timezone
    Bar open timestamp
    Bar close timestamp

    Potential Explanation

    A bar may begin before the cutoff but close later.

    The entry condition may be evaluated according to the bar's timestamp semantics rather than the visual time interpretation assumed by the user.

    Required Test

    Plot

    inEntrySession
    bar time
    longEntry condition

    around:

    15:45
    15:48
    15:50
    15:51
    15:55
    16:00

    Do not modify the session until the exact timestamp behavior is reproduced.

    === ISSUE 9 — 15-MINUTE FILTER LOOKS HISTORICALLY PERFECT ===

    Severity
    CRITICAL UNTIL REVIEWED

    Concern

    Higher-timeframe values can create misleading historical behavior if the completed 15-minute value is made available to earlier 3-minute bars.

    Required Audit

    Inspect

    Requested Timeframe
    Requested Expression
    Lookahead Configuration
    Offsets
    Bar Confirmation
    Historical Mapping
    Realtime Mapping

    Requirement

    A 3-minute decision must not use the final 15-minute value before that 15-minute bar was actually complete unless the strategy explicitly allows incomplete HTF data and accepts the realtime instability.

    If future HTF values are confirmed

    Classification
    Critical lookahead defect.

    Expected Backtest Impact

    Potentially substantial.

    === ISSUE 10 — REENTRY SOMETIMES FAILS AFTER STOP ===

    Severity
    HIGH

    Likely Cause

    Persistent state is not reset on all exit pathways.

    Audit

    trailActive
    entryLock
    cooldown
    lastSignal
    tradeCycle
    stopState
    targetState

    Flat reset should occur based on actual position transition rather than only one specific exit condition.

    Recommended conceptual transition

    previousPosition != flat
    AND currentPosition == flat

    Then reset trade-specific state.

    However

    If one-trade-per-trend behavior is intended, do not reset the crossover-cycle lock until a new opposite/reset condition occurs.

    This distinction must be preserved.

    === ISSUE 11 — PLOTTED BUY VS STRATEGY ENTRY ONE BAR LATER ===

    Status
    LIKELY EXPECTED EXECUTION TIMING

    Possible sequence

    Bar N
    Long condition becomes confirmed at close.

    Bar N close
    Order is created.

    Bar N+1:
    Market order is filled according to strategy execution settings.

    Plot marker
    May currently be drawn on Bar N.

    Strategy trade marker
    May appear on Bar N+1.

    Therefore

    Visual signal time and simulated fill time are not automatically identical.

    Required

    Document separately

    Signal Bar
    Order Creation
    Order Fill
    Displayed Marker

    Do not force same-bar execution merely to visually align the markers unless it matches the intended model.

    === ISSUE 12 — STOP AND TARGET TOUCHED IN SAME BAR ===

    Status
    BACKTEST-MODEL LIMITATION

    Timeframe
    3 minutes

    Problem

    OHLC confirms

    High
    Low

    but does not necessarily reveal which was reached first.

    If both protective stop and target fall inside the bar range, the result depends on intrabar sequencing.

    Recommended Validation

    Use finer-resolution data / supported intrabar validation.

    Or

    Adopt conservative assumptions for ambiguous bars.

    Do not claim precise historical order when standard OHLC cannot prove it.

    === PYRAMIDING AUDIT ===

    Intended
    Disabled.

    Required

    Verify strategy configuration.

    Also ensure

    Position state is part of final entry condition.

    Do not rely exclusively on the pyramiding setting to express the trading model.

    Reason

    Unique order IDs, reversals, and persistent conditions can still create behavior that surprises users.

    === ORDER-ID ARCHITECTURE ===

    Recommended

    Long Entry
    L

    Short Entry
    S

    Long Exit
    L-EXIT

    Short Exit
    S-EXIT

    If partial targets are introduced later

    L-TP1
    L-TP2
    S-TP1
    S-TP2

    Avoid unnecessary ID proliferation.

    === RECOMMENDED MODULE ARCHITECTURE ===

    1. Inputs
    2. Constants
    3. Entry Session
    4. Indicators
    5. Higher-Timeframe Data
    6. Long / Short Signal Events
    7. Position Transition Detection
    8. Entry-Time State Capture
    9. Stop / Target Calculation
    10. Trailing-State Management
    11. Orders
    12. Alerts
    13. Visuals
    14. Debug Diagnostics

    === PINE VERSION MIGRATION ===

    Current
    v5

    Recommendation

    Migrate only after existing behavior has been stabilized and baseline results recorded.

    Migration Sequence

    1. Freeze current inputs.
    2. Record Strategy Tester baseline.
    3. Repair known logic defects.
    4. Record corrected baseline.
    5. Migrate syntax.
    6. Resolve compiler changes.
    7. Compare trade-by-trade behavior.
    8. Investigate every unexplained difference.

    Compile success alone is not sufficient.

    === ALERT ARCHITECTURE ===

    Required Events

    BUY
    Actual final long-entry event.

    SELL
    Actual final short-entry event.

    EXIT
    Confirmed transition from non-flat to flat.

    Recommended payload fields

    event
    symbol
    timeframe
    side
    price
    stop
    target
    strategy
    version
    timestamp

    Exact webhook fields depend on the external integration and must not be invented.

    === RESET ARCHITECTURE ===

    On new long

    Capture
    entry price
    entry ATR
    long stop
    long target

    Reset
    short trail state

    On new short

    Capture
    entry price
    entry ATR
    short stop
    short target

    Reset
    long trail state

    On flat transition

    Reset
    active stop state
    target state
    trailing state
    breakeven state
    trade-specific flags

    Preserve
    signal-cycle state only when required by one-trade-per-trend rules.

    === REGRESSION TEST SUITE ===

    TEST 1 — LONG ENTRY

    Condition
    Fresh bullish crossover + RSI confirmation + session + flat.

    Expected
    Exactly one long entry.

    TEST 2 — PERSISTENT BULL CONDITION

    Condition
    fastEMA remains above slowEMA for 20 bars.

    Expected
    No additional long entry without a new qualifying crossover.

    TEST 3 — INITIAL LONG STOP

    Expected
    1.5 entry-time ATR below original entry.

    Before trailing
    Stop remains fixed.

    TEST 4 — LONG TRAILING ACTIVATION

    Condition
    Price reaches +1R.

    Expected
    Trail activates once.

    TEST 5 — LONG TRAILING RETRACEMENT

    Condition
    Candidate trail becomes lower than existing trail.

    Expected
    Existing trail is preserved.

    TEST 6 — SHORT TARGET

    Expected
    Target below short entry.

    TEST 7 — STOP EXIT

    Expected
    Position closes.
    Trade-specific state resets.

    TEST 8 — NEW CROSSOVER AFTER STOP

    Expected
    New trade allowed when all fresh-entry requirements are satisfied.

    TEST 9 — END OF ENTRY SESSION

    Expected
    No new trade after cutoff.

    TEST 10 — PROTECTIVE EXIT OUTSIDE ENTRY WINDOW

    Expected
    Risk management remains active according to strategy specification.

    TEST 11 — ALERT WHILE ALREADY LONG

    Expected
    No additional BUY entry alert.

    TEST 12 — HTF CONFIRMATION

    Expected
    No historical use of unavailable 15-minute information.

    TEST 13 — REALTIME BAR

    Expected
    No unintended duplicate alert caused by repeated intrabar recalculation.

    TEST 14 — OPPOSITE SIGNAL

    Expected
    Behavior matches explicit ignore/close/reverse rule.

    === DEBUG TABLE RECOMMENDATION ===

    Temporarily display

    Long Cross
    Short Cross
    RSI Long
    RSI Short
    HTF Long
    HTF Short
    Entry Session
    Position
    Entry Price
    Initial Stop
    Current Stop
    Target
    Trail Active
    Trail Candidate
    Final Trail
    Cooldown / Cycle Lock

    This will make state errors visible directly on the chart.

    === CHANGE PRIORITY ===

    P0 — CRITICAL

    Audit 15-Minute HTF Lookahead

    P1 — HIGH

    Fix Fixed-Stop Architecture
    Fix Trailing Monotonicity
    Separate Long / Short Trail State
    Correct Short Target
    Synchronize Alerts
    Separate Entry Session from Protective Exits
    Fix Flat-State Reset

    P2 — MEDIUM

    Convert Persistent EMA Condition to Explicit Crossover Event
    Clarify Signal-vs-Fill Visualization
    Validate Session Boundary

    P3 — REFACTOR

    Reorganize Modules
    Improve Naming
    Add Debug Table
    Add Regression Harness
    Migrate Pine Version

    === FINAL ENGINEERING DIRECTION ===

    Primary Debugging Principle
    Preserve strategy intent while correcting implementation behavior.

    Primary Entry Principle
    Use explicit transition events for transition-based strategies.

    Primary Stop Principle
    A fixed entry stop should not move unless the strategy explicitly says it should.

    Primary Trailing Principle
    Trailing state must activate, tighten, and reset predictably.

    Primary Repainting Principle
    Never use future information to improve historical appearance.

    Primary Session Principle
    Restrict new entries independently from protective position management.

    Primary Alert Principle
    Entry alerts should use the same final executable conditions as strategy entries when the alert represents an actual trade event.

    Primary Migration Principle
    Compare behavior, not merely compilation.

    Primary Backtest Principle
    A visually perfect chart is less important than historically honest execution.

    Status
    Ready for Source-Level Repair, Pine Migration, Regression Testing, and TradingView Verification

    pine-script-trading-strategy-debugger-op.pdf

    PDF · document

    Generated

    Example file from a real run - the skill writes it into your workspace.

    Connects securely to your tools. The creator never sees your data.

    What you get

    Repair compiler errors and logical bugs in TradingView strategies.Eliminate repainting and future lookahead bias from historical signals.Synchronize strategy alerts with actual order execution events.Migrate legacy Pine Script v3 or v4 codebases to the latest v5 standard.Convert visual indicators into executable strategies with risk management.

    About this skill

    Pine Script Trading Strategy Debugger & Optimizer is a specialist TradingView engineering skill built exclusively for debugging, repairing, converting, refactoring, validating, and improving Pine Script indicators and strategies.

    It is designed for traders, Pine Script developers, quantitative researchers, strategy creators, automation developers, agencies, educators, and TradingView users who need more than a generic code assistant.

    The skill understands that Pine Script has a unique execution model and that a script can:

    Compile Successfully Yet Trade Incorrectly

    Plot Correct Signals Yet Place Orders on Different Bars

    Backtest Profitably Yet Use Future Information

    Display Correct Stops Yet Submit Incorrect Exit Orders

    Fire Alerts Yet Never Trigger the Corresponding Strategy Entry

    Work Historically Yet Behave Differently in Realtime

    The skill therefore uses a structured engineering process:

    Intent → Reproduce → Classify → Isolate → Trace → Explain → Correct → Verify → Regression Test → Document

    It does not blindly rewrite code.

    The first objective is to understand the intended strategy behavior.

    The second objective is to determine what the existing script actually does.

    The third objective is to identify the smallest safe change that reconciles those two behaviors.

    The skill can diagnose:

    Compiler Errors Runtime Errors Type Errors Scope Problems Invalid Function Calls Deprecated Syntax Namespace Errors Incorrect Arguments Logical Bugs State Bugs Entry Bugs Exit Bugs Stop-Loss Bugs Take-Profit Bugs Trailing-Stop Bugs Breakeven Bugs Pyramiding Bugs Reversal Bugs Session Bugs Timezone Bugs Date-Filter Bugs Alert Bugs Higher-Timeframe Bugs Intrabar Assumption Problems Historical/Realtime Divergence Backtest Mismatches

    Compiler problems can be classified separately from behavioral defects.

    Typical compiler issues include:

    Unknown Identifier Wrong Function Signature Type Mismatch Invalid Argument Deprecated Construct Missing Parenthesis Scope Misuse Unsupported Syntax

    The skill explains:

    Where the problem occurs Why Pine rejects the construct What the correct pattern is Whether downstream changes are required

    It avoids rewriting a complete script when a local correction is sufficient.

    Logical debugging focuses on actual trading behavior.

    The skill can trace:

    Signal Generation Position State Entry Permission Entry Order Position Transition Exit Activation Stop Price Target Price Trailing State Session State Cooldown State Alert State

    Complex bugs can be reduced to a state trace such as:

    Bar Signal Session Position Before Order Position After Stop Target Alert

    This is useful for:

    Missed Entries Duplicate Entries Unexpected Reversals Incorrect Stop Movement Wrong Alert Timing State That Does Not Reset

    The skill audits every entry using an explicit specification.

    Potential entry fields include:

    Entry ID Direction Signal Confirmation Position Requirement Session Requirement Cooldown Order Type Expected Timing

    It checks whether:

    The condition remains true across multiple bars. The same signal can trigger repeatedly. Position state is checked. Long and short signals can become true simultaneously. Pyramiding is intentional. A reversal is intentional. The signal uses confirmed information. A visual offset makes the historical signal appear earlier than it was actually known.

    Duplicate-entry bugs are diagnosed carefully.

    Common causes include:

    Persistent Conditions Missing Flat-State Check Missing Transition Detection Incorrect Pyramiding Multiple strategy.entry() Calls Stale State Variables Reentry and Primary Entry Both Triggering Session State Not Resetting

    Possible corrections include:

    Position-State Checks Crossing Logic One-Shot Latches Entry Locks Cooldown Rules State Reset

    The skill does not add restrictions unless they match the intended strategy.

    It distinguishes:

    fast > slow

    from:

    fast crosses above slow

    because the first condition may remain true for many bars while the second represents a transition event.

    The skill can define:

    One Trade per Signal One Trade per Session One Trade per Trend Cooldown After Entry Cooldown After Exit Long-Only Mode Short-Only Mode

    All reset behavior is made explicit.

    Reversal behavior is also explicitly defined.

    An opposite signal may:

    Be Ignored Close the Current Position Reverse Immediately Wait Until Flat Wait Until the Next Bar Require Additional Confirmation

    The skill prevents accidental reversal caused by implicit order behavior.

    Exit logic receives a dedicated audit.

    For every exit, the skill can identify:

    Exit ID Linked Entry Exit Type Activation Exit Price Quantity Priority Expected Timing

    It checks whether:

    The exit references the correct entry ID. The exit remains active when expected. Multiple exits overwrite or compete with one another. Partial exit quantities are valid. The remaining position is managed correctly. A market exit collides with a protective stop or target. A reversal bypasses intended exit handling.

    The skill creates clear order-ID architecture.

    Possible conventions include:

    L S

    L-TP1

    L-SL

    L-TRAIL

    S-TP1

    S-SL

    S-TRAIL

    Every exit should have clear ownership.

    The skill audits stop-loss architecture.

    Supported stop types include:

    Fixed Price Percentage Points Ticks

    ATR

    Structure-Based Breakeven Trailing

    Every stop can define:

    Reference Price Distance Calculation Time Direction Update Rule Gap Behavior Intrabar Sensitivity

    Common stop bugs include:

    Long Stop Above Entry Short Stop Below Entry Fixed Stop Recalculated Every Bar Dynamic Stop Accidentally Frozen Stop Based on Current Close Instead of Entry Stop Reset After Scale-In Stop Linked to Wrong Entry Multiple Exits Overwriting Stop Stop Becoming NA Stop Activating Before Position Exists Stop Remaining Active After Position Closes

    For a fixed stop, the skill can preserve the stop value from entry instead of recalculating it from changing market values.

    ATR stops can explicitly distinguish:

    Entry-Time ATR Dynamic ATR

    because these produce materially different behavior.

    The skill audits take-profit logic.

    Supported targets include:

    Fixed Price Percentage Points Ticks ATR Multiple R-Multiple Structure Target Partial Target Ladder

    Common target bugs include:

    Target Based on Current Close Instead of Entry Wrong Short-Side Sign Target Reset Every Bar Target Linked to Wrong Entry Partial Quantity Exceeding Remaining Position Unexpected Stop/Target Competition Misunderstood Same-Bar Fill

    R-multiple targets can use:

    Risk = Absolute Difference Between Entry and Stop

    Long Target: Entry + Risk × R

    Short Target: Entry - Risk × R

    The skill makes directional price mathematics explicit.

    Partial-exit systems can define:

    Target Sequence Quantity Percentage Remaining Position Remaining Stop Breakeven Activation Final Exit

    It verifies that requested exit quantities do not unintentionally exceed the position.

    Breakeven behavior can define:

    Activation Threshold Breakeven Price Offset One-Time Activation Interaction with Trailing Stop Reset Condition

    The skill can detect breakeven states that oscillate on and off because activation was not latched.

    Trailing-stop engineering is a major capability.

    Supported approaches include:

    Built-In Trailing Custom Trailing Price ATR Trail Percentage Trail Highest-High Trail Lowest-Low Trail Structure Trail Chandelier-Style Trail

    Every trailing system can define:

    Activation Trail Source Trail Distance Update Frequency Whether It May Loosen Reset Condition Long Behavior Short Behavior

    For monotonic trailing behavior:

    Long: The stop normally moves upward or stays unchanged.

    Short: The stop normally moves downward or stays unchanged.

    The skill detects:

    Trailing Stop Moving Backward Repeated Activation Trail Resetting from Entry Every Bar Trail Activating Too Early Future Pivot Used for Trailing Trail Becoming NA Trail State Persisting After Exit Long and Short Trail State Contamination Built-In and Custom Trailing Logic Conflicts

    The skill audits pyramiding.

    It can review:

    Strategy Pyramiding Setting Intended Maximum Entries Entry IDs Same-Direction Additions Scale-In Behavior Opposite-Direction Signals Average Position Price Stop Recalculation Target Recalculation

    Common pyramiding problems include:

    Pyramiding Enabled Accidentally Pyramiding Disabled When Scaling Is Intended Unique Entry IDs Producing Unexpected Position Additions Persistent Signal Adding Positions Exit Closing Only Part of What User Expected Average Position Price Changing Risk Levels

    The skill can define scale-in systems.

    Potential fields include:

    Maximum Additions Add Condition Price Spacing Quantity Stop Update Target Update Exit Ownership

    It can also define scale-out systems.

    Potential fields include:

    Target Ladder Quantity Percentages Remaining Stop Breakeven Transition Final Exit

    The skill reviews position-state architecture.

    Potential information sources include:

    Position Size Average Position Price Entry Price Persistent Flags Last Signal Last Entry Bar Last Exit Bar Cooldown State

    Redundant custom state is avoided where platform position state is sufficient.

    Persistent variables are reserved for behavior that genuinely needs memory, such as:

    One-Time Activation Breakeven Latch Trailing Latch Delayed Reentry Sequential Exit State One Trade per Session One Trade per Trend

    Every persistent state should define:

    Initialization Activation Update Reset Opposite-Direction Reset Session Reset Flat Reset

    The skill audits NA handling.

    It checks:

    Initial Bars Conditional Assignments Entry Price Stop Variables Target Variables Trailing Variables Indicator Warmup Reset Logic

    It audits historical references for:

    Off-by-One Errors Insufficient History Wrong Prior-Bar Reference Incorrect State Referencing Using Previous Values After Reset

    The skill includes dedicated repainting and lookahead auditing.

    Repainting is divided into:

    Benign Realtime Recalculation Signal Repainting Future Leakage Confirmation Delay Misrepresented as Earlier Knowledge

    Potential sources include:

    Unconfirmed Realtime Bars Higher-Timeframe Values Pivot Functions Future-Dependent Calculations Realtime-Only Branches Plot Offsets Incorrect Bar-State Logic

    The skill can determine whether a visually perfect historical signal was actually known on that historical bar.

    Higher-timeframe requests receive special scrutiny.

    The skill can define:

    Requested Timeframe Source Confirmation Policy Historical Alignment Realtime Behavior Whether the Current HTF Bar Can Change

    The objective is always:

    Use Only Information Available at the Decision Time

    Material future leakage is treated as a critical defect.

    Lower-timeframe data is reviewed for:

    Historical Availability Intrabar Completeness Ordering Realtime Differences Strategy Tester Interpretation

    The skill handles same-bar ambiguity.

    If a historical candle touches both stop and target, OHLC history may not prove which occurred first.

    The skill can recommend:

    Lower-Timeframe Validation Bar Magnifier or Equivalent Platform Functionality Conservative Fill Assumptions Avoiding Dependence on Unresolved Same-Bar Sequencing

    It can distinguish:

    Signal Bar Order Creation Time Simulated Fill Time Displayed Strategy Marker

    This is essential when users believe TradingView entered "one bar late."

    A signal that becomes confirmed at Bar N close may correctly result in an order filled on Bar N+1 depending on the strategy settings and order model.

    The skill audits TradingView strategy properties.

    Potential areas include:

    Initial Capital Default Quantity Type Default Quantity Pyramiding Commission Slippage Margin Currency Order Processing Calculation Behavior Overlay Execution-Related Settings

    Differences between the Strategy Tester properties and code assumptions are flagged.

    The skill audits transaction-cost assumptions.

    Commission and slippage are not strategy logic bugs, but they can explain why backtest results differ from expected results.

    The skill can inspect:

    Commission Type Commission Value Slippage Order Frequency Scalping Sensitivity

    It does not claim that a profitable result is realistic merely because the code is correct.

    The skill includes deep session-filter engineering.

    Every session can define:

    Session Hours Timezone Trading Days Overnight Behavior Entry Permission Exit Permission Session Reset

    Common bugs include:

    Wrong Timezone Exchange Time vs User Time Confusion Overnight Session Split Incorrectly Friday/Sunday Handling Daylight-Saving Assumptions Entry Filters Accidentally Blocking Protective Exits Session State Not Reset New Session Starting with Stale State

    A key rule is:

    Entry Restrictions and Risk-Exit Restrictions Are Not Automatically the Same Thing.

    If the strategy should stop opening new positions outside the session but still allow protective exits, the skill separates those behaviors.

    Date filters can define:

    Start Date End Date Inclusivity Timezone Behavior for Open Positions After the End Date

    The skill can implement and audit:

    One Trade per Session One Trade per Trend Bar-Based Cooldowns Minute-Based Cooldowns Session-Based Cooldowns

    Cooldown logic can define:

    Start Duration Unit Reset Reentry Condition

    The skill includes comprehensive alert engineering.

    Possible alert types include:

    Setup Alert Confirmed Signal Actual Strategy Entry Exit Stop Target Trailing Update Position Closed State Change

    A central distinction is:

    Signal Intent

    versus

    Executed Strategy Event

    These are not automatically identical.

    Common alert defects include:

    Alert Condition Broader Than Entry Condition Alert Firing Outside Session Alert Firing While Already in Position Alert on Unconfirmed Bar Alert Repeating Every Bar Exit Alert Using Stale State Long and Short Alerts Firing Together Alert and Strategy Using Different Session Conditions Incorrect Payload Price Alert Fired Before Stop/Target Values Are Finalized

    The skill can synchronize alerts with the final executable strategy condition.

    It can create alert-debouncing logic using:

    Bar Confirmation One-Shot State Signal Transition Last Alert Bar Position Change

    Alert payloads can include fields such as:

    Event Symbol Timeframe Side Price Stop Target Strategy Version Timestamp

    Broker-specific webhook requirements are never invented.

    The skill performs indicator-to-strategy conversion.

    The conversion workflow is:

    Identify Signal Conditions → Identify Visual-Only Logic → Define Executable Entry Rules → Define Entry Timing → Define Exit Model → Define Risk → Define Pyramiding → Define Session → Define Costs → Verify Repainting → Compare Visual Signals with Executed Trades

    The skill recognizes that some visual indicators cannot be backtested honestly without modification.

    Examples include indicators whose signals:

    Repaint Use Future Pivots Use Synthetic Chart Values Depend on Intrabar Behavior Unavailable Historically Use Plot Offsets to Move Confirmed Signals Backward

    It does not fabricate an unrealistically perfect strategy conversion.

    The skill also converts strategies into indicators.

    It can preserve:

    Signal Logic Trend Filters Session Logic Entry Markers Exit Markers Stop Levels Target Levels Trade-State Visualization Alerts

    Strategy order functions can be replaced by explicit indicator state.

    For example:

    0 = Flat 1 = Long -1 = Short

    The indicator state must reset correctly after exits.

    The skill clearly states that an indicator emulating trade state is not equivalent to TradingView Strategy Tester execution.

    The skill performs Pine version migration.

    Migration is not limited to making the code compile.

    It follows:

    Compile Compatibility → Semantic Compatibility → Behavioral Compatibility → Backtest Comparison

    Potential migration areas include:

    Version Declaration Namespaces Renamed Functions Input Functions Type Rules Color Syntax Plotting Signatures Request Functions Timeframe Helpers Session Helpers Deprecated Constructs Stricter Compiler Requirements

    The skill identifies whether a migrated script produces different trading behavior despite successful compilation.

    The skill investigates Strategy Tester discrepancies.

    When a user says:

    "The backtest does not match what I see."

    the skill checks:

    Signal Bar vs Fill Bar Bar Close vs Next Bar Limit/Stop Semantics Strategy Execution Settings Pyramiding Reversal Chart Type Higher-Timeframe Confirmation Repainting Intrabar Ambiguity Commission Slippage Session Date Range Position Quantity Stop/Target Recalculation Visual Plot Offsets Partial Exits

    It can create a reproducibility snapshot containing:

    Script Version Pine Version Symbol Timeframe Chart Type Session Date Range Inputs Initial Capital Position Quantity Pyramiding Commission Slippage

    This allows two backtests to be compared under identical conditions.

    The skill can add temporary debugging instrumentation.

    Potential diagnostic tools include:

    plot plotshape plotchar Labels Background State Tables Entry Price Lines Stop Lines Target Lines Session Flags Condition Booleans Position State

    A debugging table can show:

    Long Signal Short Signal In Session Current Position Entry Price Stop Price Target Price Trailing Active Trailing Price Cooldown HTF Confirmation

    Instrumentation should be removed or disabled from production code when no longer needed unless requested.

    For difficult bugs, the skill can create a minimal reproduction containing only:

    The Failing Input Relevant Calculation Relevant Order Logic Observed Failure

    This isolates Pine behavior from unrelated script complexity.

    The skill performs structured refactoring.

    Refactoring goals include:

    Clearer Variables Fewer Duplicated Conditions Better Logical Separation Consistent Naming Explicit State Fewer Hidden Dependencies Predictable Resets Reusable Helper Logic Better Testability

    A recommended architecture is:

    Inputs Constants Session / Date Filters Indicators / Features Signal Logic State Logic Entry Prices Risk Levels Orders Alerts Visuals Debugging

    The skill favors meaningful names such as:

    longSignal shortSignal longEntryAllowed shortEntryAllowed longStopPrice longTargetPrice trailActive inTradeSession

    instead of vague variables such as:

    x cond1 flag2 tmp

    Complex logic can be broken into explicit booleans such as:

    trendLong momentumLong sessionAllowed positionFlat longSignal

    This makes strategy behavior easier to inspect.

    The skill can optimize code architecture while preserving behavior.

    Before and after refactoring, compare:

    Entry Bars Exit Bars Trade Count Position Direction Stop Values Target Values Alert Events Strategy Tester Results

    Optimization should never silently alter the trading model.

    The skill also supports strategy optimization methodology.

    Optimization should not mean:

    Maximize Historical Net Profit at Any Cost

    A safer workflow is:

    Fix Bugs → Freeze Core Logic → Define Objective → Define Parameter Ranges → Separate Development and Holdout Data → Evaluate Parameter Neighborhoods → Avoid Isolated Optima → Stress Costs → Test Multiple Periods → Validate on Unseen Data

    Potential optimization objectives include:

    Expectancy Profit Factor Return / Drawdown Sharpe Sortino Stability Trade Count Out-of-Sample Retention

    The skill does not blindly optimize one metric.

    Each parameter can define:

    Purpose Range Step Selected Value Nearby Behavior Interactions Risk

    Large parameter spaces are flagged for overfitting risk.

    The skill complements dedicated backtest-overfitting analysis and can recommend a separate robustness audit when optimization exposure becomes substantial.

    The skill can build regression tests.

    Example:

    NORMAL LONG

    Expected: One long entry. Stop initialized. Target initialized. No duplicate order.

    NORMAL SHORT

    Expected: One short entry. Correct short stop. Correct short target.

    REPEATED SIGNAL

    Expected: No duplicate entry when pyramiding is disabled.

    STOP HIT

    Expected: Position closes. Trade state resets. Trailing state resets.

    TARGET HIT

    Expected: Position closes or partially exits according to specification.

    SESSION END

    Expected: No new entries. Protective exits behave according to design.

    OPPOSITE SIGNAL

    Expected: Ignore, close, or reverse according to explicit strategy rules.

    REALTIME BAR

    Expected: No unintended repeated alert behavior.

    The skill can provide a structured change log.

    Each change can document:

    Change Reason Behavioral Impact Backtest Impact Risk

    It can provide before/after explanations:

    Before Problem After Why Expected Effect

    Supported operating modes include:

    Compiler Error Debugger: Diagnoses and repairs Pine compiler errors with minimal safe edits.

    Logical Strategy Debugger: Traces signals, state, entries, exits, risk levels, and reset behavior.

    Repainting & Lookahead Auditor: Audits confirmation, higher-timeframe data, pivots, offsets, historical/realtime behavior, and future leakage.

    Entry/Exit Architect: Rebuilds the strategy order lifecycle while preserving the intended trading model.

    SL/TP & Trailing Stop Engineer: Implements and repairs fixed, percentage, ATR, R-multiple, breakeven, partial-exit, and trailing-stop architecture.

    Session & Pyramiding Auditor: Handles sessions, timezone, one-trade rules, scaling, repeated entries, and reversal behavior.

    Alerts Synchronization Engineer: Aligns alerts with confirmed executable strategy events.

    Indicator-to-Strategy Converter: Transforms visual indicator logic into testable TradingView strategy logic.

    Strategy-to-Indicator Converter: Transforms strategy logic into visual signal, state, risk-level, and alert architecture.

    Pine Version Migration Engineer: Updates legacy scripts while preserving behavior.

    Backtest Mismatch Investigator: Explains why TradingView Strategy Tester behavior differs from visual chart expectations.

    Strategy Refactoring & Optimization Architect: Improves code clarity, maintainability, testability, parameter organization, and debugging visibility without silently changing strategy behavior.

    The core commercial promise is: take a Pine Script that is broken, inconsistent, difficult to understand, repainting, logically fragile, or producing unexpected Strategy Tester results and turn it into a clearer, auditable, testable TradingView implementation with explicit entries, exits, state transitions, risk controls, sessions, alerts, platform assumptions, and validation procedures.

    How to install

    Works the same in every agent - Claude, Cursor, Codex, Copilot and 20+ more.

    ~30 seconds
    1. 1

      Download the ZIP

      Free skills download straight away. Paid skills unlock right after purchase.

    2. 2

      Unzip into your skills folder

      Every agent reads skills from one folder on your machine. Drop the unzipped folder in there.

    3. 3

      Ask your agent to use it

      Restart the agent if it was already running. It picks the skill up automatically - no config needed.

    Skills folder by agent

    Click the path to copy it. Create the folder if it does not exist yet.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill passes our trust checks below.

    Security scanned

    Passed our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    30-day refund

    Not a fit? Get your money back

    Trust & safety

    Security scanned

    Verified clean 1 month ago

    • Passed all security checks, Safe to install

    Listed1 month ago

    What's inside

    Frequently Asked Questions