---
title: "TradingView Indicator Template: Backtest Any Signal as a Strategy"
slug: tradingview-indicator-template-backtest-strategy
date: 2026-02-03
modified: 2026-04-07
author: PickMyTrade
excerpt: ""
meta_description: "Use this professional TradingView Indicator Template to backtest any signal as a strategy. Includes ATR stops, tiered take profits, and automated trading hooks."
focus_keyword: TradingView Indicator Template
canonical_url: "https://blog.pickmytrade.trade/tradingview-indicator-template-backtest-strategy/"
og_title: "TradingView Indicator Template: Backtest Any Signal as a Strategy"
og_description: "Use this professional TradingView Indicator Template to backtest any signal as a strategy. Includes ATR stops, tiered take profits, and automated trading hooks."
og_image: "https://blog.pickmytrade.trade/wp-content/uploads/2026/02/20260204_0024_Image-Generation_simple_compose_01kgjdmgexfs3tmwps5pysgymj-1024x683.avif"
schema_type: FAQPage
categories:
  - AUTOMATED TRADINGVIEW STRATEGIES
  - Trading
  - TradingView
tags: []
reading_time: 16
word_count: 3823
robots: "index, follow"
lang: en-US
---

# Advanced TradingView Indicator Template: Backtest Any Signal as a Professional Strategy

The Advanced Strategy Template v6 is a strategy execution and risk-management framework designed to test external indicators under consistent and repeatable conditions.

Table of Contents

1. [What is an Indicator Template?](https://blog.pickmytrade.trade/#what-is-an-indicator-template)
2. [Purpose and Originality](https://blog.pickmytrade.trade/#purpose-and-originality)
3. [How the Signal Connector Works](https://blog.pickmytrade.trade/#how-the-signal-connector-works)
4. [Example Connector Code (Indicator Side)](https://blog.pickmytrade.trade/#example-connector-code-indicator-side)
5. [How to Connect the Indicator to the Strategy](https://blog.pickmytrade.trade/#how-to-connect-the-indicator-to-the-strategy)
6. [Execution and Risk-Management Features](https://blog.pickmytrade.trade/#execution-and-risk-management-features)
7. [Strategy Properties and Results](https://blog.pickmytrade.trade/#strategy-properties-and-results)
8. [Intended Use](https://blog.pickmytrade.trade/#intended-use)
9. [Advanced Strategy Template](https://blog.pickmytrade.trade/#advanced-strategy-template)

This script does not generate buy or sell signals internally. Instead, all trade entries and exits are driven by a user-supplied indicator through a numeric connector. This design intentionally separates signal generation from trade execution, allowing users to evaluate indicators without rewriting complex strategy logic.

## What is an Indicator Template? {#user-content-what-is-an-indicator-template}

An indicator template in this context refers to a standardized execution framework. Traditionally, TradingView indicators only provide visual signals. To backtest them, you would typically need to convert the entire script into a strategy, which requires manual coding for every new indicator.

This “Indicator Template” acts as a universal bridge. It provides a fixed environment where any signal—whether based on RSI, MACD, or a custom algorithm—can be plugged in and immediately benchmarked against professional risk management constraints. It allows traders to focus on the quality of their signals while the template handles the heavy lifting of position management, stop losses, and take profits.

## Purpose and Originality {#user-content-purpose-and-originality}

The purpose of this template is to provide a standardized execution framework rather than a specific trading methodology. By decoupling the signal source from the execution engine, the script focuses on how trades are managed after a signal occurs.

This allows users to:

- Benchmark different indicators under identical execution rules.
- Compare stop-loss and take-profit models objectively.
- Study the impact of specific risk constraints on performance.
- Reduce bias caused by inconsistent trade management.

This makes the script suitable for educational testing and experimentation, rather than presenting a standalone profitable strategy.

## How the Signal Connector Works {#user-content-how-the-signal-connector-works}

The strategy listens to a single numeric data source supplied by an external indicator. The indicator must output values using the following convention:

- **1**: Open long position
- **-1**: Open short position
- **0**: No action
- **2**: Custom close for long positions (optional)
- **-2**: Custom close for short positions (optional)

The strategy reacts only to these specific values and ignores all other internal logic from the source indicator.

### Example Connector Code (Indicator Side) {#user-content-example-connector-code-indicator-side}

To make any indicator compatible with this template, users must add a connector snippet to their script. Below is a standard example:

```
// ─────────────────────────────
// 🔌 Strategy Connector
//  1  = Buy
// -1  = Sell
//  0  = No Signal
// ─────────────────────────────
signal = buySignal ? 1 : sellSignal ? -1 : 0
plot(signal, title="Connector", display=display. None)
```

In this example, `buySignal` and `sellSignal` represent the indicator’s own internal logic. The connector plot is hidden and used strictly as a data source for the strategy template.

## How to Connect the Indicator to the Strategy {#user-content-how-to-connect-the-indicator-to-the-strategy}

1. Add the indicator (with the connector snippet) to your TradingView chart.
2. Access the [Advanced Strategy Template v6](https://www.tradingview.com/script/DV83PYxg-Advanced-Strategy-Template/) and add it to the same chart.
3. Open the Strategy settings.
4. Set the “Data source” input to the indicator’s “Connector” plot.
5. Configure the risk, stop-loss, and take-profit settings as required.

![Connecting Indicator template with indicator](https://blog.pickmytrade.trade/wp-content/uploads/2026/02/image.avif)

The full strategy execution script is provided below for reference. The strategy will not execute trades unless a valid connector signal is received from the linked indicator.

## Execution and Risk-Management Features {#user-content-execution-and-risk-management-features}

This template provides a comprehensive suite of configurable execution modules, including:

- **Position Management**: Sizing and pyramiding control.
- **Risk Constraints**: Maximum drawdown and intraday loss limits.
- **Streak Protection**: Consecutive win, loss, and losing-day limits.
- **Stop-Loss Methods**: Percent-based, trailing, ATR, or structure-based (pivots).
- **Take-Profit Models**: Single target, tiered targets, risk-reward ratios, and Fibonacci levels.
- **Optimization Tools**: Optional breakeven logic and session-based trading controls.

All execution logic operates independently of the signal source, ensuring that the benchmark results accurately reflect the management settings rather than the signal’s bias.

## Strategy Properties and Results {#user-content-strategy-properties-and-results}

Default strategy properties are intentionally conservative and provided only as a demonstration baseline. Backtest results depend entirely on the connected indicator, the market and timeframe selected, and the user-defined execution parameters.

Results generated by this template do not represent a trading edge and should not be interpreted as financial advice.

## Intended Use {#user-content-intended-use}

This script is intended for:

- Educational study of trade execution and risk control.
- Indicator benchmarking under identical execution rules.
- Exploring how different exit strategies influence outcomes.

It is not intended to promote or present a standalone trading strategy. For those looking to automate their results, the template can be used in conjunction with third-party tools such as PickMyTrade to bridge signals to brokerage accounts once a robust execution model is established.

## Advanced Strategy Template {#advanced-strategy-template}

```
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Daveatt - Enhanced Version

//@version=6

// https://www.tradingview.com/blog/en/use-an-input-from-another-indicator-with-your-strategy-19584/

strategyName = "Advanced Strategy Template v6"
traderId = "DAVE"

// Strategy configuration values
initialCapital = 1000000
positionSize = 10.0
commissionRate = 0.075
maxPyramiding = 3
calcOnFills = true

strategy(title=strategyName, shorttitle=strategyName, 
 overlay=true, pyramiding=maxPyramiding, initial_capital=initialCapital, default_qty_type=strategy.percent_of_equity, 
 default_qty_value=positionSize, commission_type=strategy.commission.percent, commission_value=commissionRate, calc_on_order_fills=calcOnFills, 
 precision=6, max_lines_count=500, max_labels_count=500)

// ————— Indicator Connection
signalSource = input.source(close, title="Data source")

// Custom exit signal
enableCustomExit = input.bool(false, title="Use Custom Close?")

// ————— Visual Settings
colorBars = input.bool(true, title="Colour Candles to Trade Order state")

enableSessionClose = input.bool(false, title="Close positions at market at the end of each session ?")
tradingSession = input.session("0000-2345", title="Trading Session")

entryDirection  = input.string(defval="ALL", title="Open  Trading Direction", options=["ALL", "LONG", "SHORT"])
exitDirection = input.string(defval="ALL", title="Close Trading Direction", options=["ALL", "LONG", "SHORT"])

closeOnReversal = input.bool(true, title="Close on Opposite Signal")

// ————— Date range filtering
enableDateFilter = input.bool(false, title="═════════════ Date Range Filtering")

startDate = input.time(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time")
endDate = input.time(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time")

isDateAllowed() =&gt; enableDateFilter ? time &gt;= startDate and time &lt;= endDate : true

// ————— Consecutive loss/win limits
enableLossStreakLimit = input.bool(title=&quot;═════════════ Set Max number of consecutive loss trades&quot;, defval=false)
maxLossStreak = input.int(title=&quot;Max of consecutive loss trades&quot;, defval=15, minval=1)

enableWinStreakLimit = input.bool(title=&quot;═════════════ Set Max number of consecutive won trades&quot;, defval=false)
maxWinStreak = input.int(title=&quot;Max Winning Streak Length&quot;, defval=15, minval=1)

// ————— Consecutive losing days
enableLosingDaysLimit = input.bool(title=&quot;═════════════ Set MAX consecutive days with a loss in a row&quot;, defval=false)
maxLosingDays = input.int(title=&quot;Max of consecutive days with a loss in a row&quot;, defval=3, minval=1)

enableMaxDD = input.bool(title=&quot;═════════════ Set Max Total DrawDown&quot;, defval=false)
maxDrawdownPercent = input.int(title=&quot;Max Drawdown (%)&quot;, defval=10, minval=1, maxval=100)

enableIntradayLossLimit = input.bool(title=&quot;═════════════ Set Max Intraday Loss&quot;, defval=false)
maxIntradayLossPercent = input.int(title=&quot;Max Intraday Loss (%)&quot;, defval=3, minval=1, maxval=100)

enableDailyTradeLimit = input.bool(title=&quot;═════════════ Limit the number of trades per day&quot;, defval=false)
maxTradesPerDay = input.int(title=&quot;Number MAX of daily trades&quot;, defval=10, minval=1, maxval=100)

enableWeeklyTradeLimit = input.bool(title=&quot;═════════════ Limit the number of trades per week&quot;, defval=false)
maxTradesPerWeek = input.int(title=&quot;Number MAX of weekly trades&quot;, defval=50, minval=1, maxval=100)

// ————— Stop loss management
stopLossType = input.string(title=&quot;═════════════ Stop Type Selection&quot;, defval=&quot;None&quot;, options=[&quot;None&quot;, &quot;Percent&quot;, &quot;Trailing&quot;, &quot;ATR&quot;, &quot;Structure&quot;])

// Percent-based stops
stopLossPercent = input.float(title=&quot;Stop Loss (%)&quot;, minval=0.0, step=0.5, defval=1) * 0.01
trailingStopPercent = input.float(title=&quot;Trail Stop Loss (%)&quot;, minval=0.0, step=0.5, defval=3) * 0.01

// ATR stops
atrStopPeriod = input.int(title=&quot;═════════════ ATR Stop Length&quot;, defval=14)
atrStopMultiplier = input.float(defval=1, title=&quot;[ATR ONLY] Risk Ratio&quot;, step=0.10)

// Structure-based stops
swingLookback = input.int(title=&quot;═════════════ Structure Lookback Period&quot;, defval=5, minval=1)
swingStopBuffer = input.float(title=&quot;[STRUCTURE] Stop Offset (pips/points)&quot;, defval=0, step=0.1)

// ————— Take Profit
takeProfitType = input.string(title=&quot;════ Take Profit Type Selection&quot;, defval=&quot;None&quot;, options=[&quot;None&quot;, &quot;Percent&quot;, &quot;ATR&quot;, &quot;RiskReward&quot;, &quot;Tiered&quot;, &quot;Fibonacci&quot;])

// Percent TP
takeProfitPercent = input.float(title=&quot;Take Profit (%)&quot;, minval=0.0, step=0.5, defval=3) * 0.01

// ATR TP
atrTpPeriod = input.int(title=&quot;══════ ATR Take Profit Length&quot;, defval=14)
atrTpMultiplier = input.float(defval=2, title=&quot;[ATR ONLY] Reward Ratio&quot;, step=0.10)

// Risk:Reward Ratio
rrRatio = input.float(title=&quot;══════ [R:R] Risk:Reward Ratio&quot;, defval=2.0, minval=0.5, step=0.5)

// Tiered Targets
enableTieredTP = input.bool(title=&quot;══════ Enable Tiered Targets&quot;, defval=false)
tier1Percent = input.float(title=&quot;[TIERED] TP1 (%)&quot;, defval=1.0, step=0.5) * 0.01
tier1ClosePercent = input.int(title=&quot;[TIERED] TP1 Close % of Position&quot;, defval=33, minval=1, maxval=100)
tier2Percent = input.float(title=&quot;[TIERED] TP2 (%)&quot;, defval=2.0, step=0.5) * 0.01
tier2ClosePercent = input.int(title=&quot;[TIERED] TP2 Close % of Position&quot;, defval=33, minval=1, maxval=100)
tier3Percent = input.float(title=&quot;[TIERED] TP3 (%)&quot;, defval=3.0, step=0.5) * 0.01
tier3ClosePercent = input.int(title=&quot;[TIERED] TP3 Close % of Position&quot;, defval=34, minval=1, maxval=100)

// Fibonacci Targets
fibLookbackPeriod = input.int(title=&quot;══════ [FIBONACCI] Lookback Period&quot;, defval=20, minval=5)
enableFib382 = input.bool(title=&quot;[FIBONACCI] Use 0.382 Level&quot;, defval=false)
enableFib618 = input.bool(title=&quot;[FIBONACCI] Use 0.618 Level&quot;, defval=true)
enableFib100 = input.bool(title=&quot;[FIBONACCI] Use 1.0 Level&quot;, defval=true)
enableFib162 = input.bool(title=&quot;[FIBONACCI] Use 1.618 Level&quot;, defval=true)
enableFib262 = input.bool(title=&quot;[FIBONACCI] Use 2.618 Level&quot;, defval=false)
fib382ClosePercent = input.int(title=&quot;[FIBONACCI] 0.382 Close %&quot;, defval=25, minval=1, maxval=100)
fib618ClosePercent = input.int(title=&quot;[FIBONACCI] 0.618 Close %&quot;, defval=25, minval=1, maxval=100)
fib100ClosePercent = input.int(title=&quot;[FIBONACCI] 1.0 Close %&quot;, defval=25, minval=1, maxval=100)
fib162ClosePercent = input.int(title=&quot;[FIBONACCI] 1.618 Close %&quot;, defval=25, minval=1, maxval=100)

// Breakeven
enableBreakeven = input.bool(title=&quot;══════ Move to Breakeven after TP1&quot;, defval=false)
breakevenOffsetPercent = input.float(title=&quot;[BREAKEVEN] Offset (%)&quot;, defval=0.1, step=0.1) * 0.01

// ————— Colors
colorGreenRaw = color.new(color.lime,0)
colorGreenMedium = color.new(#00b300,0)
colorGreenSemiDark = color.new(#009900,0)
colorGreenDark = color.new(#006600,0)
colorGreenDarkDark = color.new(#003300,0)

colorRedRaw = color.new(color.red,0)
colorRedMedium = color.new(#cc0000,0)
colorRedSemiDark = color.new(#990000,0)
colorRedDark = color.new(#330000,0)
colorRedDarkDark = color.new(#330000,0)

colorFuchsiaRaw = color.new(color.fuchsia,0)
colorFuchsiaMedium = color.new(#c000c0,0)
colorFuchsiaDark = color.new(#800080,0)
colorFuchsiaDarkDark = color.new(#400040,0)

colorYellowRaw = color.new(color.yellow,0)
colorYellowMedium = color.new(#c0c000,0)
colorYellowDark = color.new(#808000,0)
colorYellowDarkDark = color.new(#404000,0)

colorOrangeRaw = color.new(#ffa500,0)
colorOrangeMedium = color.new(#cc8400,0)
colorOrangeDark = color.new(#996300,0)

colorBlueRaw = color.new(#4985E7,0)
colorBlueMedium = color.new(#4985E7,0)

colorGreenBg = color.new(#00FF00,93)
colorRedBg = color.new(#FF0000,90)

LARGE_NUMBER = 1000

// Signal interpretation
signalValue = nz(signalSource)

// 1 = bullish signal
isBullSignal = (signalValue == 1)
// -1 = bearish signal
isBearSignal = (signalValue == -1)

// 2 = custom exit long
customExitLong = enableCustomExit and (signalValue == 2)
// -2 = custom exit short
customExitShort = enableCustomExit and (signalValue == -2)

// Entry Price tracking
entryPriceLevel = ta.valuewhen(condition=isBearSignal or isBullSignal, source=close, occurrence=0)

// ————— RISK MANAGEMENT

intradayLossValue = (enableIntradayLossLimit) ? maxIntradayLossPercent : 100
strategy.risk.max_intraday_loss(value=intradayLossValue, type=strategy.percent_of_equity)

drawdownValue = (enableMaxDD) ? maxDrawdownPercent : 100
strategy.risk.max_drawdown(value=drawdownValue, type=strategy.percent_of_equity)

// Daily trades
dailyTradeCount = (enableDailyTradeLimit) ? maxTradesPerDay : LARGE_NUMBER
strategy.risk.max_intraday_filled_orders(count=dailyTradeCount)

// Weekly trades calculation
var int tradesAtWeekStart = 0

tradesAtWeekStart := if (dayofweek == dayofweek.monday) and (dayofweek != dayofweek[1])
    strategy.closedtrades[1] + strategy.opentrades[1]
else
    tradesAtWeekStart[1]

weeklyTradeCount = (strategy.closedtrades + strategy.opentrades) - tradesAtWeekStart
isWeeklyTradeAllowed = (enableWeeklyTradeLimit) ? (weeklyTradeCount  strategy.losstrades[1]) and
     (strategy.wintrades == strategy.wintrades[1]) and
     (strategy.eventrades == strategy.eventrades[1])

var int currentLossStreak = 0

currentLossStreak := if (hasNewLoss)
    nz(currentLossStreak[1]) + 1
else
    if (strategy.wintrades &gt; strategy.wintrades[1]) or (strategy.eventrades &gt; strategy.eventrades[1])
        0
    else
        nz(currentLossStreak[1])

isLossStreakOk = (enableLossStreakLimit) ? currentLossStreak  strategy.wintrades[1]) and
     (strategy.losstrades == strategy.losstrades[1]) and
     (strategy.eventrades == strategy.eventrades[1])

var int currentWinStreak = 0

currentWinStreak := if (hasNewWin)
    nz(currentWinStreak[1]) + 1
else
    if (strategy.losstrades &gt; strategy.losstrades[1]) or (strategy.eventrades &gt; strategy.eventrades[1])
        0
    else
        nz(currentWinStreak[1])

isWinStreakOk = (enableWinStreakLimit) ? currentWinStreak  0)
    stopValue = close * (1 - trailingStopPercent)
    math.max(stopValue, longTrailingStop[1])
else
    0

shortTrailingStop := if (strategy.position_size  0 and useStopLoss) ? finalStopLong : na,
     color=color.red, style=plot.style_cross,
     linewidth=2, title="Long Stop Loss")

plot(series=(strategy.position_size  0 ? math.abs(strategy.position_avg_price - finalStopLong) :
 strategy.position_size  0 ? strategy.position_avg_price * (1 + breakevenOffsetPercent) : 0.0
beStopShort = strategy.position_size  0 and useTakeProfit and not useTieredTp and not useFibonacciTp) ? tpLongPrice : na,
     color=color.green, style=plot.style_circles,
     linewidth=3, title="Long Take Profit")

plot(series=(strategy.position_size  0 and useTieredTp) ? tier1Long : na,
     color=colorGreenMedium, style=plot.style_circles, linewidth=2, title="TP1 Long")
plot(series=(strategy.position_size &gt; 0 and useTieredTp) ? tier2Long : na,
     color=colorGreenSemiDark, style=plot.style_circles, linewidth=2, title="TP2 Long")
plot(series=(strategy.position_size &gt; 0 and useTieredTp) ? tier3Long : na,
     color=colorGreenDark, style=plot.style_circles, linewidth=2, title="TP3 Long")

plot(series=(strategy.position_size &lt; 0 and useTieredTp) ? tier1Short : na,
     color=colorRedMedium, style=plot.style_circles, linewidth=2, title=&quot;TP1 Short&quot;)
plot(series=(strategy.position_size &lt; 0 and useTieredTp) ? tier2Short : na,
     color=colorRedSemiDark, style=plot.style_circles, linewidth=2, title=&quot;TP2 Short&quot;)
plot(series=(strategy.position_size  0 and useFibonacciTp and enableFib382) ? fib382Long : na,
     color=colorYellowRaw, style=plot.style_cross, linewidth=2, title="Fib 0.382 Long")
plot(series=(strategy.position_size &gt; 0 and useFibonacciTp and enableFib618) ? fib618Long : na,
     color=colorYellowMedium, style=plot.style_cross, linewidth=2, title="Fib 0.618 Long")
plot(series=(strategy.position_size &gt; 0 and useFibonacciTp and enableFib100) ? fib100Long : na,
     color=colorYellowDark, style=plot.style_cross, linewidth=2, title="Fib 1.0 Long")
plot(series=(strategy.position_size &gt; 0 and useFibonacciTp and enableFib162) ? fib162Long : na,
     color=colorOrangeMedium, style=plot.style_cross, linewidth=2, title="Fib 1.618 Long")
plot(series=(strategy.position_size &gt; 0 and useFibonacciTp and enableFib262) ? fib262Long : na,
     color=colorOrangeDark, style=plot.style_cross, linewidth=2, title="Fib 2.618 Long")

plot(series=(strategy.position_size &lt; 0 and useFibonacciTp and enableFib382) ? fib382Short : na,
     color=colorYellowRaw, style=plot.style_cross, linewidth=2, title=&quot;Fib 0.382 Short&quot;)
plot(series=(strategy.position_size &lt; 0 and useFibonacciTp and enableFib618) ? fib618Short : na,
     color=colorYellowMedium, style=plot.style_cross, linewidth=2, title=&quot;Fib 0.618 Short&quot;)
plot(series=(strategy.position_size &lt; 0 and useFibonacciTp and enableFib100) ? fib100Short : na,
     color=colorYellowDark, style=plot.style_cross, linewidth=2, title=&quot;Fib 1.0 Short&quot;)
plot(series=(strategy.position_size &lt; 0 and useFibonacciTp and enableFib162) ? fib162Short : na,
     color=colorOrangeMedium, style=plot.style_cross, linewidth=2, title=&quot;Fib 1.618 Short&quot;)
plot(series=(strategy.position_size  0 and beActivated) ? beStopLong : na,
     color=colorBlueMedium, style=plot.style_line,
     linewidth=3, title="Breakeven Stop Long")

plot(series=(strategy.position_size  not na(time(timeframe.period, sess))
inTradingSession = isInSession(tradingSession)
canTradeInSession = enableSessionClose ? inTradingSession : true
sessionJustStarted = inTradingSession and not inTradingSession[1]

bgcolor(color=(enableSessionClose and isInSession(tradingSession)[1]) ? color.new(color.green, 85) : na,
 title="Trading Session")

// Consolidate trading conditions
canTrade = isWeeklyTradeAllowed and isLossStreakOk and isWinStreakOk and isDateAllowed() and canTradeInSession

// Position tracking
hasLongPosition = strategy.position_size &gt; 0
hasShortPosition = strategy.position_size  0 and isBearSignal
    strategy.close(id="Long", alert_message="{{ticker}} Short Signal - Close Long Signal - Timeframe: {{interval}}", comment="Short Signal\nClose Long")

if closeOnReversal and strategy.position_size  0 and customExitLong)
    strategy.close(id="Long", alert_message="{{ticker}} Custom Close Long Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Long")
    alert(syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)

if (strategy.position_size  0 and useTieredTp
        if high &gt;= tier1Long
            beActivated := true
    if strategy.position_size &lt; 0 and useTieredTp
        if low  0 and canCloseLongs and useTieredTp)
    strategy.exit(id="TP1 Long", from_entry="Long", qty_percent=tier1ClosePercent, 
     stop=useStopLoss ? adjustedStopLong : na, limit=tier1Long, 
     alert_message="{{ticker}} TP1 Long Hit - Timeframe: {{interval}}")
    
    strategy.exit(id="TP2 Long", from_entry="Long", qty_percent=tier2ClosePercent, 
     stop=useStopLoss ? adjustedStopLong : na, limit=tier2Long, 
     alert_message="{{ticker}} TP2 Long Hit - Timeframe: {{interval}}")
    
    strategy.exit(id="TP3 Long", from_entry="Long", qty_percent=tier3ClosePercent, 
     stop=useStopLoss ? adjustedStopLong : na, limit=tier3Long, 
     alert_message="{{ticker}} TP3 Long Hit - Timeframe: {{interval}}")

if (strategy.position_size  0 and canCloseLongs and useFibonacciTp)
    if enableFib382
        strategy.exit(id="Fib 0.382 Long", from_entry="Long", qty_percent=fib382ClosePercent, 
         stop=useStopLoss ? adjustedStopLong : na, limit=fib382Long, 
         alert_message="{{ticker}} Fib 0.382 Long Hit - Timeframe: {{interval}}")
    
    if enableFib618
        strategy.exit(id="Fib 0.618 Long", from_entry="Long", qty_percent=fib618ClosePercent, 
         stop=useStopLoss ? adjustedStopLong : na, limit=fib618Long, 
         alert_message="{{ticker}} Fib 0.618 Long Hit - Timeframe: {{interval}}")
    
    if enableFib100
        strategy.exit(id="Fib 1.0 Long", from_entry="Long", qty_percent=fib100ClosePercent, 
         stop=useStopLoss ? adjustedStopLong : na, limit=fib100Long, 
         alert_message="{{ticker}} Fib 1.0 Long Hit - Timeframe: {{interval}}")
    
    if enableFib162
        strategy.exit(id="Fib 1.618 Long", from_entry="Long", qty_percent=fib162ClosePercent, 
         stop=useStopLoss ? adjustedStopLong : na, limit=fib162Long, 
         alert_message="{{ticker}} Fib 1.618 Long Hit - Timeframe: {{interval}}")
    
    if enableFib262
        strategy.exit(id="Fib 2.618 Long", from_entry="Long", 
         stop=useStopLoss ? adjustedStopLong : na, limit=fib262Long, 
         alert_message="{{ticker}} Fib 2.618 Long Hit - Timeframe: {{interval}}")

if (strategy.position_size  0 and canCloseLongs and not useTieredTp and not useFibonacciTp)
    strategy.exit(id="Exit Long", from_entry="Long", stop=useStopLoss ? adjustedStopLong : na, limit=useTakeProfit ? tpLongPrice : na, alert_message="{{ticker}} Close Long Signal - Timeframe: {{interval}}")
    alert(syminfo.tickerid + " Exit Long Signal - Exit Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)

if (strategy.position_size &lt; 0 and canCloseShorts and not useTieredTp and not useFibonacciTp)
    strategy.exit(id=&quot;Exit Short&quot;, from_entry=&quot;Short&quot;, stop=useStopLoss ? adjustedStopShort : na, limit=useTakeProfit ? tpShortPrice : na, alert_message=&quot;{{ticker}} Close Short Signal - Timeframe: {{interval}}&quot;)
    alert(syminfo.tickerid + &quot; Exit Short Signal - Exit Price: &quot; + str.tostring(close) + &quot;Timeframe: &quot; + timeframe.period, alert.freq_once_per_bar_close)

// ————— SESSION END CLOSE

if not canTradeInSession and hasAnyPosition
    strategy.close_all()

// ————— EMERGENCY FLATTEN

shouldFlatten = not isWeeklyTradeAllowed or not isLossStreakOk or not isWinStreakOk or not isDateAllowed()

if (shouldFlatten)
    strategy.close_all()

// ————— BAR COLORING

barColor = not colorBars ? na : strategy.position_size == 0 ? color.gray : 
 hasLongPosition ? color.lime :
 hasShortPosition ? color.red : color.gray

barcolor(barColor, title=&quot;Trade State Bar Colouring&quot;)
```

For AI tools &amp; developers:[View Markdown →](https://blog.pickmytrade.trade/tradingview-indicator-template-backtest-strategy.md)