Skip to content

A strategy as a value ​

How do you use a strategy's own results inside another script, for example to act only while it is winning? Read it through request.security: the strategy trades a simulated account of its own on that series, and its equity and position come back as values.

Save this strategy as Trend:

pine
//@version=6
strategy("Trend", overlay = true, initial_capital = 10000,
  default_qty_type = strategy.percent_of_equity, default_qty_value = 100,
  process_orders_on_close = true)
int len = input.int(50, "Length")
float ma = ta.sma(close, len)
if ta.crossover(close, ma)
    strategy.entry("Long", strategy.long)
if ta.crossunder(close, ma)
    strategy.close("Long")
plot(ma, "MA")

Then read it from another script. trend.run(...) is the AmenoScript addition here, so that script is AmenoScript and runs leak-safe:

ameno
indicator("Trend as a filter")
import Me/Trend/1 as trend

// Its equity and position, from its own account on this chart's symbol
[eq, size] = request.security(syminfo.tickerid, "1D",
  trend.run(strategy.equity, strategy.position_size))
// The same strategy with a 20-bar average, in an account of its own
float eqFast = request.security(syminfo.tickerid, "1D",
  trend.run(strategy.equity, len = 20))

bool winning = eq > ta.sma(eq, 50)
plot(eq, "Trend equity, 50")
plot(eqFast, "Trend equity, 20")
bgcolor(size > 0 and winning ? color.new(color.teal, 90) : na)

How it works ​

  • trend.run(strategy.equity, strategy.position_size) reads two expressions in the strategy's own scope, after its last statement, as a tuple.
  • Inside request.security, the strategy gets an account of its own. Its strategy() arguments set that account, and its orders fill by the emulator's rules on that series' bars.
  • Each request is its own account, so the 50-bar and 20-bar versions trade side by side.
  • What comes back equals the strategy's own equity curve when it runs alone on a chart, to the bit.
  • eq > ta.sma(eq, 50) is true while the strategy's equity is above its own 50-day average: a simple "is it working" filter.

You can write the strategy inline instead, as a function that holds a strategy() call. Language extensions shows how.

Traps ​

  • size lags the decision by a bar. Trend fills at the close it decides on, after its code has run there, so strategy.position_size shows the fill on the next bar, as on TradingView.
  • No request, no account. Called on the chart directly, a strategy held in a function has no account and the run stops. Always read it through a request.
  • request.pairs can't hold one, since a pair has no single series to trade. request.each can: an account per member.

See also ​

AmenoScript is compatible with Pine Script v6. Pine Script is a trademark of TradingView, Inc., which has no part in AmenoScript.