Skip to content

strategy ​

How do you place orders and read what your strategy holds? Declare the script with strategy(), place orders with strategy.entry, strategy.exit and strategy.close, and read the position and the results through the strategy.* values. Each fill of an entry is a lot: a position is one or more lots on the same side, and exits close them. Every value reads the account as it stands at this bar's close, after every fill so far. When each order fills, and at what price, is on How a strategy fills.

pine
//@version=6
strategy("Moving-average cross", overlay = true,
      default_qty_type = strategy.percent_of_equity, default_qty_value = 50)
float fast = ta.sma(close, 10)
float slow = ta.sma(close, 30)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")
// A fill shows here from the bar after the order:
// the close that placed it was already over.
plot(strategy.position_size, "Units held", display = display.data_window)
plot(strategy.equity, "Equity", display = display.data_window)

strategy.entry ​

pine
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void

Places an order that opens a position, or adds to it up to pyramiding, and reverses a position held the other way.

Placed at a close, a market entry fills at the next open, and one with limit or stop rests until the price reaches it. Calling strategy.entry again with the same id before it fills replaces the waiting order. An entry against the position held closes it and opens its own size the other way. A size under 0 or over 1e12 stops the script with an error. A refused entry, past pyramiding, a risk rule or strategy.risk.allow_entry_in, adds a warning and places nothing. See sizes and reversals.

ParameterDefaultDescription
id
series string
The order's name. Exits and closes name the entry by it, and the trade list shows it.
direction
series strategy_direction
strategy.long or strategy.short.
qty
series int/float
Units to trade. Left out or na, strategy()'s default_qty_type and default_qty_value size the order. 0 places nothing.
limit
series int/float
A limit price. The order fills at this price or better.
stop
series int/float
A stop price. With limit too, the order is a stop-limit.
oca_name
series string
A group name. Orders sharing it cancel or reduce each other as they fill.
oca_type
input string
strategy.oca.nonestrategy.oca.cancel, strategy.oca.reduce or strategy.oca.none.
comment
series string
Text for the trade list.
alert_messageNo effect here
series string
Accepted. Order fills raise no alerts in this engine.
disable_alertNo effect here
series bool
falseAccepted.

strategy.order ​

pine
strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void

Places an order that nets against what you hold, with no pyramiding check.

It takes strategy.entry's arguments. At its fill it trades against the open position first: a sell of 5 against a long of 3 closes the 3 and opens a short of 2. Use it to build a position in steps that pyramiding would refuse.

ParameterDefaultDescription
id
series string
The order's name.
direction
series strategy_direction
strategy.long to buy or strategy.short to sell.
qty
series int/float
Units to trade. Left out or na, the strategy's default size applies.
limit
series int/float
A limit price.
stop
series int/float
A stop price. With limit too, the order is a stop-limit.
oca_name
series string
A group name.
oca_type
input string
strategy.oca.noneHow the group's orders treat each other.
comment
series string
Text for the trade list.
alert_messageNo effect here
series string
Accepted. Order fills raise no alerts in this engine.
disable_alertNo effect here
series bool
falseAccepted.

strategy.exit ​

pine
strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, comment_profit, comment_loss, comment_trailing, alert_message, alert_profit, alert_loss, alert_trailing, disable_alert) → void

Places a take-profit, a stop-loss or a trailing stop for an entry, or for every open lot.

The exit rests from the next bar and fills on whichever of its levels the bar's path reaches first. Levels come as prices (limit, stop) or as ticks from the entry price (profit, loss). Given both for one side, the one the price reaches first counts. Call it again with the same id to move its levels. A call whose every level is na places nothing and leaves an exit already resting as it is.

The exit's size belongs to the order, so a second exit with no size on the same entry never fills. See exits and closes and trailing stops.

ParameterDefaultDescription
id
series string
The exit's name.
from_entry
series string
The entry to exit. Left out, the exit applies to every open lot.
qty
series int/float
Units to close. Left out with qty_percent also left out, the exit takes what the entry has left.
qty_percent
series int/float
A percent of what the lot filled.
profit
series int/float
The take-profit distance in ticks from the entry price.
limit
series int/float
The take-profit price.
loss
series int/float
The stop-loss distance in ticks from the entry price.
stop
series int/float
The stop-loss price.
trail_price
series int/float
The price that arms a trailing stop.
trail_points
series int/float
The distance in ticks, from the entry price, that arms a trailing stop.
trail_offset
series int/float
How far in ticks the trailing stop follows behind the best price.
oca_nameNo effect here
series string
Accepted. An exit's own levels already cancel each other.
comment
series string
Text for the trade list, whichever level fills.
comment_profit
series string
Text when the take-profit fills.
comment_loss
series string
Text when the stop-loss fills.
comment_trailing
series string
Text when the trailing stop fills.
alert_messageNo effect here
series string
Accepted. Order fills raise no alerts in this engine.
alert_profitNo effect here
series string
Accepted.
alert_lossNo effect here
series string
Accepted.
alert_trailingNo effect here
series string
Accepted.
disable_alertNo effect here
series bool
falseAccepted.

strategy.close ​

pine
strategy.close(id, comment, qty, qty_percent, alert_message, immediately, disable_alert) → void

Closes as many units as the entry named id holds, at the next open, or at this close with immediately = true. By default they come off the oldest lots first, whichever entry opened them, as TradingView does; with close_entries_rule = "ANY" in strategy() they come off that entry's own lots. See which lot closes.

With nothing of that id open, the call does nothing, so an entry placed just before it on the same bar stands. Its order id in the trade list is Close entry(s) order <id>.

ParameterDefaultDescription
id
series string
The entry to close.
comment
series string
Text for the trade list.
qty
series int/float
Units to close. Left out, all of them.
qty_percent
series int/float
A percent of the position to close.
alert_messageNo effect here
series string
Accepted. Order fills raise no alerts in this engine.
immediately
series bool
falsetrue fills at this bar's close instead of the next open.
disable_alertNo effect here
series bool
falseAccepted.

strategy.close_all ​

pine
strategy.close_all(comment, alert_message, immediately, disable_alert) → void

Closes the whole position, at the next open, or at this close with immediately = true. When flat, it does nothing.

ParameterDefaultDescription
comment
series string
Text for the trade list.
alert_messageNo effect here
series string
Accepted. Order fills raise no alerts in this engine.
immediately
series bool
falsetrue fills at this bar's close instead of the next open.
disable_alertNo effect here
series bool
falseAccepted.

strategy.cancel ​

pine
strategy.cancel(id) → void

Cancels the waiting orders with this id, and takes away a trailing stop an exit of that id holds.

ParameterDescription
id
series string
The order to cancel.

strategy.cancel_all ​

pine
strategy.cancel_all() → void

Cancels every waiting order.

strategy.default_entry_qty ​

pine
strategy.default_entry_qty(fill_price) → series float

The size a default-sized entry would take if it filled at fill_price now, on this bar's equity.

ParameterDescription
fill_price
series int/float
The price to size at.

strategy.convert_to_account ​

Pine v6No effect here
pine
strategy.convert_to_account(value) → series float

The value it's given, unchanged. Money stays in the symbol's currency in this engine, so there is nothing to convert.

ParameterDescription
value
series int/float
An amount in the symbol's currency.

strategy.convert_to_symbol ​

Pine v6No effect here
pine
strategy.convert_to_symbol(value) → series float

The value it's given, unchanged. Money stays in the symbol's currency in this engine, so there is nothing to convert.

ParameterDescription
value
series int/float
An amount in the account's currency.

strategy.commission ​

AmenoScript onlyNo effect here
ameno
strategy.commission(value, type) → void

Does nothing. TradingView has no such function, only the strategy.commission.* constants, and this engine accepts the call so that a script naming it still runs. Set the commission with strategy()'s commission_type and commission_value.

ParameterDescription
value
simple float
Ignored.
type
simple string
Ignored.

strategy.risk.allow_entry_in ​

pine
strategy.risk.allow_entry_in(value) → void

Allows entries on one side only. An entry on the other side closes what it faces and opens nothing.

ParameterDescription
value
simple string
strategy.direction.long, strategy.direction.short or strategy.direction.all.

strategy.risk.max_cons_loss_days ​

pine
strategy.risk.max_cons_loss_days(count, alert_message) → void

Stops trading for good after this many losing days in a row: every order is cancelled and what's open closes. A day is a UTC calendar day here, where TradingView counts the symbol's trading day: the two differ on a symbol whose session doesn't start at midnight UTC, such as a US share.

ParameterDescription
count
simple int
The losing days allowed.
alert_messageNo effect here
simple string
Accepted.

strategy.risk.max_drawdown ​

pine
strategy.risk.max_drawdown(value, type, alert_message) → void

Stops trading for good once equity falls this far from its peak: every order is cancelled and what's open closes.

ParameterDescription
value
simple int/float
The drawdown allowed.
type
simple string
strategy.cash for money, or strategy.percent_of_equity for a percent of the peak. Left out, cash.
alert_messageNo effect here
simple string
Accepted.

strategy.risk.max_intraday_filled_orders ​

pine
strategy.risk.max_intraday_filled_orders(count, alert_message) → void

Stops the day once this many orders have filled, exits included: every order is cancelled, what's open closes, and entries wait for the next UTC day, where TradingView waits for the next trading day.

ParameterDescription
count
simple int
The fills allowed in a day.
alert_messageNo effect here
simple string
Accepted.

strategy.risk.max_intraday_loss ​

pine
strategy.risk.max_intraday_loss(value, type, alert_message) → void

Closes everything and stops the day once equity falls this far from the day's high-water mark, checked at every point of each bar's path.

The mark starts at the day's first open and rises at each close. When the loss reaches the limit, the position closes there as Close Position (Max intraday Loss), every order is cancelled, and entries wait for the next UTC day, where TradingView waits for the next trading day. See risk rules.

ParameterDescription
value
simple int/float
The loss allowed.
type
simple string
strategy.cash for money, or strategy.percent_of_equity for a percent of the mark. Left out, cash.
alert_messageNo effect here
simple string
Accepted.

strategy.risk.max_position_size ​

pine
strategy.risk.max_position_size(contracts) → void

Caps the units held in one direction. An entry past the cap is cut to the room left, and refused when there is none.

ParameterDescription
contracts
simple int/float
The most units to hold.

strategy.position_size ​

pine
series float strategy.position_size

The position in units at this bar's close: positive when long, negative when short, 0 when flat.

It includes every fill up to this close. A market order placed at a close fills at the next open, so the position shows it at the next bar's close.

strategy.position_avg_price ​

pine
series float strategy.position_avg_price

The average entry price of the open lots, or na when flat.

strategy.position_entry_name ​

pine
series string strategy.position_entry_name

The id of the oldest open lot's entry, or "" when flat.

strategy.equity ​

pine
series float strategy.equity

Initial capital plus net profit plus the open position's profit, marked at this bar's close, rounded to the tick, syminfo.mintick.

strategy.netprofit ​

pine
series float strategy.netprofit

The profit of all closed trades, less every commission paid so far, the open lots' entry commission included.

strategy.openprofit ​

pine
series float strategy.openprofit

The open position's profit at this bar's close, before its commission.

strategy.initial_capital ​

pine
series float strategy.initial_capital

The capital the strategy started with: strategy()'s initial_capital, 1,000,000 by default.

strategy.account_currency ​

pine
simple string strategy.account_currency

Reads "USD", whatever strategy()'s currency or the symbol's own currency is. No amount is converted, so every money figure is in the symbol's currency, and on a symbol quoted in euros the figures are euros under a "USD" label.

strategy.closedtrades ​

pine
series int strategy.closedtrades

How many trades have closed. The trade accessors number them from 0, the oldest.

strategy.closedtrades.first_index ​

pine
int strategy.closedtrades.first_index

Always 0: every closed trade is kept, so the oldest is trade 0.

strategy.opentrades ​

pine
series int strategy.opentrades

How many lots are open. The open-trade accessors number them from 0, the oldest.

strategy.opentrades.capital_held ​

pine
series float strategy.opentrades.capital_held

The open lots' value at their entry prices, or na when margin_long and margin_short are both 0.

strategy.margin_liquidation_price ​

pine
series float strategy.margin_liquidation_price

The price at which the open position would take a margin call, rounded to the tick. It reads na when flat, when margin is off, and for a long held at 100% margin, which a fall can't call.

strategy.max_drawdown ​

pine
series float strategy.max_drawdown

The largest drawdown so far, as TradingView reads it: how far capital plus net profit, with the open lots at their worst, has fallen under the highest that capital plus net profit has been. See the report.

strategy.max_runup ​

pine
series float strategy.max_runup

The largest run-up so far, as TradingView reads it: how far capital plus net profit, with the open lots at their best, has risen over the lowest that capital plus net profit has been.

strategy.closedtrades.* ​

What one closed trade was, read by its number. trade_num counts from 0, the oldest, up to strategy.closedtrades - 1. Past the last trade, a number reads na and a text reads "". A trade's profit, run-up and drawdown are in money, in the symbol's currency.

NameGivesWhat it means
strategy.closedtrades.commissionseries floatThe commission it paid, entry and exit together.
strategy.closedtrades.entry_bar_indexseries intThe bar index where it entered.
strategy.closedtrades.entry_commentseries stringThe comment on its entry, or "".
strategy.closedtrades.entry_idseries stringIts entry's id.
strategy.closedtrades.entry_priceseries floatThe price its entry filled at.
strategy.closedtrades.entry_timeseries intIts entry bar's time, in milliseconds since 1970 UTC.
strategy.closedtrades.exit_bar_indexseries intThe bar index where it exited.
strategy.closedtrades.exit_commentseries stringThe comment on its exit, or "".
strategy.closedtrades.exit_idseries stringThe id of the order that closed it, or "".
strategy.closedtrades.exit_priceseries floatThe price its exit filled at.
strategy.closedtrades.exit_timeseries intIts exit bar's time, in milliseconds since 1970 UTC.
strategy.closedtrades.max_drawdownseries floatThe most it was down while open, plus its entry commission, as TradingView's trade list reads it.
strategy.closedtrades.max_drawdown_percentseries floatIts drawdown as a percent of its entry cost, commission included.
strategy.closedtrades.max_runupseries floatThe most it was up while open, less its entry commission, as TradingView's trade list reads it.
strategy.closedtrades.max_runup_percentseries floatIts run-up as a percent of its entry cost, commission included.
strategy.closedtrades.profitseries floatIts profit, after commission.
strategy.closedtrades.profit_percentseries floatIts profit as a percent of what it cost to enter.
strategy.closedtrades.sizeseries floatIts size in units, negative for a short.
Each takesDescription
trade_num
series int
The trade's number, from 0, the oldest.

strategy.opentrades.* ​

What one open lot is, read by its number. trade_num counts from 0, the oldest, up to strategy.opentrades - 1. Past the last lot, a number reads na and a text reads "". Profit, run-up and drawdown are in money, in the symbol's currency, marked at this bar's close.

NameGivesWhat it means
strategy.opentrades.commissionseries floatThe entry commission it paid.
strategy.opentrades.entry_bar_indexseries intThe bar index where it entered.
strategy.opentrades.entry_commentseries stringThe comment on its entry, or "".
strategy.opentrades.entry_idseries stringIts entry's id.
strategy.opentrades.entry_priceseries floatThe price its entry filled at.
strategy.opentrades.entry_timeseries intIts entry bar's time, in milliseconds since 1970 UTC.
strategy.opentrades.max_drawdownseries floatThe most it has been down so far.
strategy.opentrades.max_drawdown_percentseries floatIts drawdown as a percent of its entry value.
strategy.opentrades.max_runupseries floatThe most it has been up so far.
strategy.opentrades.max_runup_percentseries floatIts run-up as a percent of its entry value.
strategy.opentrades.profitseries floatIts profit at this bar's close, less its entry commission.
strategy.opentrades.profit_percentseries floatIts profit as a percent of what it cost to enter.
strategy.opentrades.sizeseries floatIts size in units, negative for a short.
Each takesDescription
trade_num
series int
The lot's number, from 0, the oldest.

strategy.oca.* ​

Values for an order's oca_type.

Each is a const string.

NameWhat it means
strategy.oca.cancelThe first fill in the group cancels the group's other orders.
strategy.oca.noneThe order belongs to no group.
strategy.oca.reduceEach fill reduces the group's other orders by its size.

strategy.commission.* ​

Values for strategy()'s commission_type.

Each is a const string.

NameWhat it means
strategy.commission.cash_per_contractAn amount per unit traded.
strategy.commission.cash_per_orderAn amount per order, shared by size among the lots it closes and opens.
strategy.commission.percentA percent of each fill's value.

strategy.direction.* ​

Values for strategy.risk.allow_entry_in.

Each is a const string.

NameWhat it means
strategy.direction.allBoth sides.
strategy.direction.longLong entries only.
strategy.direction.shortShort entries only.

strategy.* ​

The strategy's other figures and constants, each read at this bar's close.

NameTypeWhat it means
strategy.avg_losing_tradeseries floatThe mean loss of the losing trades.
strategy.avg_losing_trade_percentseries floatThe mean loss percent of the losing trades, negative.
strategy.avg_tradeseries floatThe mean profit per closed trade.
strategy.avg_trade_percentseries floatThe mean profit percent per closed trade.
strategy.avg_winning_tradeseries floatThe mean profit of the winning trades.
strategy.avg_winning_trade_percentseries floatThe mean profit percent of the winning trades.
strategy.cashconst stringdefault_qty_type for an amount of money, and the cash type for a risk limit.
strategy.eventradesseries intHow many closed trades broke even.
strategy.fixedconst stringdefault_qty_type for a fixed number of units.
strategy.grosslossseries floatThe sum of the losing trades' losses, as a positive number.
strategy.grossloss_percentseries floatGross loss as a percent of the initial capital.
strategy.grossprofitseries floatThe sum of the winning trades' profits.
strategy.grossprofit_percentseries floatGross profit as a percent of the initial capital.
strategy.longconst strategy_directionThe buy direction for an order.
strategy.losstradesseries intHow many closed trades lost money.
strategy.max_contracts_held_allseries floatThe most units held at once, either side.
strategy.max_contracts_held_longseries floatThe most units held long at once.
strategy.max_contracts_held_shortseries floatThe most units held short at once.
strategy.max_drawdown_percentseries floatThe largest drawdown as a percent.
strategy.max_runup_percentseries floatThe largest run-up as a percent.
strategy.netprofit_percentseries floatNet profit as a percent of the initial capital.
strategy.openprofit_percentseries floatThe open profit as a percent of the initial capital plus net profit.
strategy.percent_of_equityconst stringdefault_qty_type for a percent of equity, and the percent type for a risk limit.
strategy.shortconst strategy_directionThe sell direction for an order.
strategy.wintradesseries intHow many closed trades made money.

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