Pine Script v6 Strategy Code Examples

Pine Script v6 opens up powerful new ways to build, test, and share trading strategies on TradingView. In this post, we'll walk through practical v6 code examples—ranging from dynamic stop-loss setups to unique position sizing tactics.

Pine Script logo with trademarked name and v6 with text code examples

Pine Script v6 introduced some meaningful changes and new capabilities for TradingView developers, and for traders using CrossTrade, it means even more powerful strategy automation. In this post, we'll break down some of the latest improvements in v6, particularly around how to define stop losses, take profit targets, and dynamic quantity sizing using smart variables like ATR, volatility, or even account equity.

Whether you're writing your own strategies or adapting open-source scripts to work with CrossTrade's automation tools, this guide will show you how to implement more intelligent position management.


What's New in Pine Script v6?

While not as radical as v4 to v5, Pine Script v6 brings several important improvements:

  • Enhanced type safety – stricter type checking helps prevent silent runtime errors and requires explicit type declarations for functions
  • varip keyword – allows variables to persist across realtime bar updates, enabling calculations that span multiple price updates within the same bar
  • Dynamic requests by default – all request.*() functions can now execute dynamically without special configuration
  • Improved boolean logic – boolean values can no longer be na, eliminating the confusing third boolean state
  • Function overloading support – enables multiple functions with the same name but different parameter signatures
  • Enhanced array handling – more robust array operations with improved performance
  • Better error messages – clearer compilation errors that make debugging faster and easier

If you're building strategies designed to send alerts via alert_message, v6 gives you cleaner control over logic, especially for custom position sizing and trade routing.


💡 5 Examples of Smarter Stops, Targets, and Quantity Logic

Here are five v6-compatible Pine Script strategy snippets, each with a unique approach to managing quantity, stop losses, or take profits using real-world logic.


1. ATR-Based Stop and Target

Use a multiple of Average True Range to determine both the stop loss and profit target.

//@version=6
strategy("ATR Stop/Target", overlay=true, process_orders_on_close=true)

atrLen = input.int(14, title="ATR Length")
atrMult = input.float(1.5, title="ATR Multiplier")

atr = ta.atr(atrLen)
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))

if (longCondition)
    stop = close - atr * atrMult
    target = close + atr * atrMult
    strategy.entry("Long", strategy.long)
    strategy.exit("Exit Long", from_entry="Long", stop=stop, limit=target)

2. Fixed $ Risk per Trade Based on ATR Stop

Dynamically calculate quantity based on a fixed dollar risk and ATR-based stop distance.

//@version=6
strategy("Fixed $ Risk with ATR Stop", overlay=true, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

riskPerTrade = input.float(100.0, title="Risk $ per Trade")
atrLen = input.int(14)
atrMult = input.float(2.0)

atr = ta.atr(atrLen)
stopDist = atr * atrMult
qty = riskPerTrade / stopDist
qtyRounded = math.round(qty)

longSignal = ta.crossover(ta.rsi(close, 14), 30)

if (longSignal)
    stop = close - stopDist
    target = close + stopDist * 1.5
    strategy.entry("Long", strategy.long, qty=qtyRounded)
    strategy.exit("Exit", from_entry="Long", stop=stop, limit=target)

3. Percent-Based Stop and Target

Stop loss and take profit are calculated based on a percentage of the entry price.

//@version=6
strategy("Percent-Based Stop/Target", overlay=true, process_orders_on_close=true)

percentStop = input.float(1.0, title="Stop %") / 100
percentTarget = input.float(2.0, title="Target %") / 100

longCondition = ta.crossover(ta.sma(close, 10), ta.sma(close, 30))

if (longCondition)
    stopPrice = close * (1 - percentStop)
    targetPrice = close * (1 + percentTarget)
    strategy.entry("Long", strategy.long)
    strategy.exit("TP/SL", from_entry="Long", stop=stopPrice, limit=targetPrice)

4. Volatility-Weighted Quantity

Adjust quantity inversely to volatility so you trade smaller during more volatile conditions.

//@version=6
strategy("Volatility-Weighted Qty", overlay=true, process_orders_on_close=true)

volatility = ta.stdev(close, 20)
baseVol = 1.0
maxQty = 10

scaling = baseVol / volatility
qty = math.min(maxQty, math.round(scaling))

entryCondition = ta.crossover(close, ta.sma(close, 20))

if entryCondition
    strategy.entry("Vol Entry", strategy.long, qty=qty)

5. Equity-Based Scaling

Use a percentage of current equity to determine trade size dynamically.

//@version=6
strategy("Equity-Based Sizing", overlay=true, default_qty_type=strategy.fixed, process_orders_on_close=true)

equityPercent = input.float(5, title="Equity % per Trade")
riskCapital = strategy.equity * (equityPercent / 100)
atr = ta.atr(14)
stopDistance = atr * 1.5
qty = math.round(riskCapital / stopDistance)

signal = ta.crossover(ta.ema(close, 12), ta.ema(close, 26))

if signal
    stop = close - stopDistance
    target = close + stopDistance * 2
    strategy.entry("EquityEntry", strategy.long, qty=qty)
    strategy.exit("Exit", from_entry="EquityEntry", stop=stop, limit=target)

Using These Scripts with CrossTrade

When you're ready to automate strategies, you can wrap the alerts in a format compatible with CrossTrade Webhooks. Just use the strategy.entry() alert_message argument with dynamic variables:

if longCondition
  stopLossPrice = close - stopLossTicks
  targetPrice = close + targetTicks
  alertMessage = 'key=your-secret-key;'
  alertMessage := alertMessage + 'command=PLACE;'
  alertMessage := alertMessage + 'account=sim101;'
  alertMessage := alertMessage + 'instrument={{ticker}};'
  alertMessage := alertMessage + 'action=BUY;'
  alertMessage := alertMessage + 'qty=1;'
  alertMessage := alertMessage + 'order_type=MARKET;'
  alertMessage := alertMessage + 'tif=DAY;'
  alertMessage := alertMessage + 'flatten_first=true;'
  alertMessage := alertMessage + 'take_profit=' + str.tostring(targetPrice) + ';'
  alertMessage := alertMessage + 'stop_loss=' + str.tostring(stopLossPrice) + ';'

 strategy.entry('Long', strategy.long, alert_message = alertMessage)

This bridges TradingView and NinjaTrader (or any supported platform) with zero manual order input. To fully sync your TradingView strategy with NinjaTrader 8, you can utilize our Sync Strategy feature to keep your position state in sync between platforms and enable seamless automation.


Final Thoughts

Pine Script v6 makes it easier to write flexible, reliable strategies, and when paired with CrossTrade, it opens the door to fully automated trading setups. By using ATR, volatility, or even account equity to define your stops, targets, and position sizes, you can create more adaptive systems that respond to market conditions in real time.

The enhanced type safety and varip functionality in v6 allow for more sophisticated real-time calculations, while the improved error handling makes development faster and more reliable. Whether you're trading futures, crypto, or stocks, these dynamic methods let you scale smarter and manage risk better.


Ready to use Pine Script V6 for full automated trading?

Start your free trial

Try CrossTrade for 7 days.

Sign Up