t value is ‘NaN’.
trail_price
(series int/float) An optional argument. Trailing stop activation level (requires a specific price). If it is specified, a trailing stop order will be placed when the specified price level is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the ‘trail_offset’ argument: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is ‘NaN’.trail_points
(series int/float) An optional argument. Trailing stop activation level (profit specified in ticks). If it is specified, a trailing stop order will be placed when the calculated price level (specified amount of profit) is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the ‘trail_offset’ argument: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is ‘NaN’.trail_offset
(series int/float) An optional argument. Trailing stop price (specified in ticks). The offset in ticks to determine initial price of the trailing stop order: X ticks lower than ‘trail_price’ or ‘trail_points’ to exit long position; X ticks higher than ‘trail_price’ or ‘trail_points’ to exit short position. The default value is ‘NaN’.oca_name
comment
(series string) An optional argument. Additional instructions for the order.when
(series bool) An optional argument. Condition of the order. The order is placed if condition is “true”. If condition is “false”, nothing happens (the previously placed order with the same ID is not cancelled). Default value is “true”.alert_message
(series string) An optional argument when using the {{strategy.order.alert_message}} placeholder in the “Message” field of the “Create Alert” dialog.It is a command to cancel/deactivate pending orders by referencing their names, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
strategy.cancel(id, when)
Example
strategy(title = "simple order cancellation example")
conditionForBuy = open > high[1]
strategy.entry("long", strategy.long, 1, limit = low, when = conditionForBuy) // enter long using limit order at low price of current bar if conditionForBuy is true
strategy.cancel("long", when = not conditionForBuy) // cancel the entry order with name "long" if conditionForBuy is false
Arguments
id
(series string) A required argument. The order identifier. It is possible to cancel an order by referencing its identifier.when
(series bool) An optional argument. Condition to cancel an order with specified ID. If condition is “true”, then the order with specified ID will be cancelled. Default value is “true”.It is a command to cancel/deactivate all pending orders, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
strategy.cancel_all(when)
Example
strategy(title = "simple all orders cancellation example")
conditionForBuy1 = open > high[1]
strategy.entry("long entry 1", strategy.long, 1, limit = low, when = conditionForBuy1) // enter long by limit if conditionForBuy1 is true
conditionForBuy2 = conditionForBuy1 and open[1] > high[2]
strategy.entry("long entry 2", strategy.long, 1, limit = ta.lowest(low, 2), when = conditionForBuy2) // enter long by limit if conditionForBuy2 is true
conditionForStopTrading = open < ta.lowest(low, 2)
strategy.cancel_all(conditionForStopTrading) // cancel both limit orders if the conditon conditionForStopTrading is true
Arguments
when
(series bool) An optional argument. Condition to cancel all orders. If condition is true, then all active orders will be cancelled. Default value is ‘true’.It is a command to place order. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.entry, the function strategy.order is not affected by pyramiding. If both ‘limit’ and ‘stop’ parameters are ‘NaN’, the order type is market order.
strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)
Example
strategy(title = "simple strategy order example")
strategy.order("buy", strategy.long, 1, when = open > high[1]) // buy by market if current open great then previous high
strategy.order("sell", strategy.short, 1, when = open < low[1]) // sell by market if current open less then previous low
Arguments
id
(series string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.direction
(strategy_direction) A required parameter. Order direction: ‘strategy.long’ is for buy, ‘strategy.short’ is for sell.qty
(series int/float) An optional parameter. Number of contracts/shares/lots/units to trade. The default value is ‘NaN’.limit
(series int/float) An optional parameter. Limit price of the order. If it is specified, the order type is either ‘limit’, or ‘stop-limit’. ‘NaN’ should be specified for any other order type.stop
(series int/float) An optional parameter. Stop price of the order. If it is specified, the order type is either ‘stop’, or ‘stop-limit’. ‘NaN’ should be specified for any other order type.oca_name
oca_type
comment
(series string) An optional parameter. Additional notes on the order.when
(series bool) An optional parameter. Condition of the order. The order is placed if condition is “true”. If condition is “false”, nothing happens (the previously placed order with the same ID is not cancelled). Default value is “true”.alert_message
(series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the “Create Alert” dialog box’s “Message” field.Returns the bar_index of the open trade’s entry.
strategy.opentrades.entry_bar_index(trade_num)
Wait for 10-bars and close the position.
Example
strategy("`strategy.opentrades.entry_bar_index` Example")
barsSinceLastEntry() =>
strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
// Enter a long position if there are no open positions.
if strategy.opentrades == 0
strategy.entry("Long", strategy.long)
// Close the long position after 10 bars.
if barsSinceLastEntry() >= 10
strategy.close("Long")
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.See also
strategy.closedtrades.entry_bar_index
strategy.closedtrades.exit_bar_index
Returns the id of the open trade’s entry.
strategy.opentrades.entry_id(trade_num)
Example
strategy("`strategy.opentrades.entry_id` Example", overlay = true)
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
strategy.entry("Long entry at bar #" + str.tostring(bar_index), strategy.long)
if shortCondition
strategy.entry("Short entry at bar #" + str.tostring(bar_index), strategy.short)
// Display ID of the latest open position.
if barstate.islastconfirmedhistory
runtime.log("Last opened position is " + strategy.opentrades.entry_id(strategy.opentrades - 1))
Returns Returns the ID of the open trade’s entry.
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.Remarks The function returns na if trade_num is not in the range: 0 to strategy.opentrades-1.
See also
strategy.opentrades.entry_bar_index
strategy.opentrades.entry_time
Returns the price of the open trade’s entry.
strategy.opentrades.entry_price(trade_num)
Example
strategy("strategy.closedtrades.entry_price Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price for the latest closed trade.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryPrice, "Long entry price")
Calculate the average open position price.
Example
strategy("strategy.opentrades.entry_price Example 2", pyramiding = 2)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average open position price.
avgOpenPositionPrice() =>
sumOpenPositionPrice = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenPositionPrice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
result = nz(sumOpenPositionPrice / strategy.opentrades)
plot(avgOpenPositionPrice())
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.See also
strategy.closedtrades.exit_price
Returns the UNIX time of the open trade’s entry.
strategy.opentrades.entry_time(trade_num)
Example
strategy("strategy.opentrades.entry_time Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculates duration in milliseconds since the last position was opened.
timeSinceLastEntry()=>
strategy.opentrades > 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades - 1)) : na
plot(timeSinceLastEntry() / 1000 * 60 * 60 * 24, "Days since last entry")
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.See also
strategy.closedtrades.entry_time
strategy.closedtrades.exit_time
Returns the profit/loss of the open trade. Losses are expressed as negative values.
strategy.opentrades.profit(trade_num)
Return the profit of the last opened trade.
Example
strategy("`strategy.opentrades.profit` Example 1", commission_type = strategy.commission.percent, commission_value = 0.1)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
plot(strategy.opentrades.profit(strategy.opentrades - 1), "Profit of the latest open trade")
Calculate the profit of all open positions.
Example
strategy("`strategy.opentrades.profit` Example 2", pyramiding = 5)
// Strategy calls to enter 5 long positions every 2 bars.
if bar_index % 2 == 0
strategy.entry("Long", strategy.long, qty = 5)
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
plot(tradeOpenPL(), "Profit of all open trades")
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.See also
strategy.closedtrades.profit
strategy.openprofit
strategy.netprofit
strategy.grossprofit
Returns the direction and the number of contracts traded in the open trade. If the value is > 0, the market position was long. If the value is < 0, the market position was short.
strategy.opentrades.size(trade_num)
Example
strategy("`strategy.opentrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
strategy.close("Long")
// Plot the number of contracts in the latest open trade.
plot(strategy.opentrades.size(strategy.opentrades - 1), "Amount of contracts in latest open trade")
Calculate the average profit percentage of open positions.
Example
strategy("`strategy.opentrades.size` Example 2")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for all open trades.
profitPct = 0.0
for tradeNo = 0 to strategy.opentrades - 1
entryP = strategy.opentrades.entry_price(tradeNo)
exitP = close
profitPct += (exitP - entryP) / entryP * strategy.opentrades.size(tradeNo) * 100
// Calculate average profit percent for all open trades.
avgProfitPct = nz(profitPct / strategy.opentrades)
Arguments
trade_num
(series int) The trade number of the open trade. The number of the first trade is zero.See also
strategy.closedtrades.size
strategy.position_size
strategy.opentrades
strategy.closedtrades
Returns the bar_index of the closed trade’s entry.
strategy.closedtrades.entry_bar_index(trade_num)
Example
strategy("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / strategy.closedtrades)
plot(avgBarsPerTrade())
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.closedtrades.exit_bar_index
strategy.opentrades.entry_bar_index
Returns the exit price of a closed trade.
strategy.closedtrades.exit_price(trade_num)
Example
strategy("strategy.closedtrades.exit_price Example 1")
// We are creating a long trade every 5 bars
if bar_index % 5 == 0
strategy.entry("Long", strategy.long)
strategy.close("Long")
// Return the exit price from the latest closed trade.
exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
plot(exitPrice, "Long exit price")
Calculate the average profit percentage for all closed trades.
Example
strategy("strategy.closedtrades.exit_price Example 2")
// Strategy calls to create single short and long trades.
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("Short")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
Arguments
trade_num
(series int) Transaction number of the closed transaction. The number of the first transaction is zero.See also
strategy.closedtrades.entry_price
Return the bar_index of the closed trade exit.
strategy.closedtrades.exit_bar_index(trade_num)
Example
strategy("strategy.closedtrades.exit_bar_index Example 1")
// Strategy calls to place a single short trade. We enter the trade at the first bar and exit the trade at 10 bars before the last chart bar.
if bar_index == 0
strategy.entry("Short", strategy.short)
if bar_index == last_bar_index - 10
strategy.close("Short")
// Calculate the amount of bars since the last closed trade.
barsSinceClosed = strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) : na
plot(barsSinceClosed, "Bars since last closed trade")
Calculate the average number of K-lines per transaction.
Example
strategy("strategy.closedtrades.exit_bar_index Example 2")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars per trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / strategy.closedtrades)
plot(avgBarsPerTrade())
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
bar_index
Returns the id of the closed trade’s entry.
strategy.closedtrades.entry_id(trade_num)
Example
strategy("strategy.closedtrades.entry_id Example", overlay = true)
var isOpen = false
var openIndex = -1
// Enter a short position and close at the previous to last bar.
if not barstate.ishistory and not isOpen
strategy.entry("Short at bar #" + str.tostring(bar_index), strategy.short)
isOpen := true
openIndex := bar_index
if openIndex != -1 and bar_index > openIndex + 100
strategy.close_all()
// Display ID of the last entry position.
if barstate.islastconfirmedhistory
runtime.log("Last Entry ID is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))
Returns Returns the id of the closed trade’s entry.
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.Remarks The function returns na if trade_num is not in the range: 0 to strategy.closedtrades-1.
See also
strategy.closedtrades.entry_bar_index
strategy.closedtrades.entry_time
Returns the price of the closed trade’s entry.
strategy.closedtrades.entry_price(trade_num)
Example
strategy("strategy.closedtrades.entry_price Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price for the latest entry.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryPrice, "Long entry price")
Calculate the average profit percentage for all closed trades.
Example
strategy("strategy.closedtrades.entry_price Example 2")
// Strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("Short")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.closedtrades.exit_price
strategy.closedtrades.size
strategy.closedtrades
Returns the UNIX time of the closed trade’s entry.
strategy.closedtrades.entry_time(trade_num)
Example
strategy("strategy.closedtrades.entry_time Example", overlay = true)
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumTradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
runtime.log(str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.opentrades.entry_time
strategy.closedtrades.exit_time
time
Returns the profit/loss of the closed trade. Losses are expressed as negative values.
strategy.closedtrades.profit(trade_num)
Example
strategy("`strategy.closedtrades.profit` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossProfit() =>
sumGrossProfit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossProfit / strategy.closedtrades)
plot(avgGrossProfit(), "Average gross profit")
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.opentrades.profit
strategy.closedtrades.commission
Returns the direction and the number of contracts traded in the closed trade. If the value is > 0, the market position was long. If the value is < 0, the market position was short.
strategy.closedtrades.size(trade_num)
Example
strategy("`strategy.closedtrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
strategy.close("Long")
// Plot the number of contracts traded in the last closed trade.
plot(strategy.closedtrades.size(strategy.closedtrades - 1), "Number of contracts traded")
Calculate the average profit percentage on closed trades.
Example
strategy("`strategy.closedtrades.size` Example 2")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryP = strategy.closedtrades.entry_price(tradeNo)
exitP = strategy.closedtrades.exit_price(tradeNo)
profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)
plot(avgProfitPct)
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.opentrades.size
strategy.position_size
strategy.closedtrades
strategy.opentrades
Returns the UNIX time of the closed trade’s exit.
strategy.closedtrades.exit_time(trade_num)
Example
strategy("strategy.closedtrades.exit_time Example 1")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration.
avgTradeDuration() =>
sumTradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumTradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")
Reopen closed trades after X seconds.
Example
strategy("strategy.closedtrades.exit_time Example 2")
// Strategy calls to emulate a single long trade at the first bar.
if bar_index == 0
strategy.entry("Long", strategy.long)
reopenPositionAfter(timeSec) =>
if strategy.closedtrades > 0
if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timeSec * 1000
strategy.entry("Long", strategy.long)
// Reopen last closed position after 120 sec.
reopenPositionAfter(120)
if ta.change(strategy.opentrades)
strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)
Arguments
trade_num
(series int) The trade number of the closed trade. The number of the first trade is zero.See also
strategy.closedtrades.entry_time
This function can be used to specify in which market direction the strategy.entry function is allowed to open positions.
strategy.risk.allow_entry_in(value)
Example
strategy("strategy.risk.allow_entry_in")
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", strategy.long, when = open > close)
// Instead of opening a short position with 10 contracts, this command will close long entries.
strategy.entry("Short", strategy.short, when = open < close, qty = 10)
Arguments
value
(simple string) The allowed direction. Possible values: strategy.direction.all
, strategy.direction.long
, strategy.direction.short
The purpose of this rule is to determine maximum size of a market position. The rule affects the following function: strategy.entry
. The ‘entry’ quantity can be reduced (if needed) to such number of contracts/shares/lots/units, so the total position size doesn’t exceed the value specified in ‘strategy.risk.max_position_size’. If minimum possible quantity still violates the rule, the order will not be placed.
strategy.risk.max_position_size(contracts)
Example
strategy("risk.max_position_size Demo", default_qty_value = 100)
strategy.risk.max_position_size(10)
strategy.entry("buy", strategy.long, when = open > close)
plot(strategy.position_size) // max plot value will be 10
Arguments
contracts
(simple int/float) A required parameter. Maximum number of contracts/shares/lots/units in a position.Absolute value of number
is number
if number
>= 0, or -number
otherwise.
math.abs(number)
Returns
The absolute value of number
.
The acos function returns the arccosine (in radians) of number such that cos(acos(y)) = y for y in range [-1, 1].
math.acos(angle)
Returns The arc cosine of a value; the returned angle is in the range [0, Pi], or na if y is outside of range [-1, 1].
Returns a pseudo-random value. The function will generate a different sequence of values for each script execution. Using the same value for the optional seed argument will produce a repeatable sequence.
math.random(min, max, seed)
Returns A random value.
Arguments
min
(series int/float) The lower bound of the range of random values. The value is not included in the range. The default is 0.max
(series int/float) The upper bound of the range of random values. The value is not included in the range. The default is 1.seed
(input int) Optional argument. When the same seed is used, allows successive calls to the function to produce a repeatable set of values.The asin function returns the arcsine (in radians) of number such that sin(asin(y)) = y for y in range [-1, 1].
math.asin(angle)
Returns The arcsine of a value; the returned angle is in the range [-Pi/2, Pi/2], or na if y is outside of range [-1, 1].
The atan function returns the arctangent (in radians) of number such that tan(atan(y)) = y for any y.
math.atan(angle)
Returns The arc tangent of a value; the returned angle is in the range [-Pi/2, Pi/2].
The ceil function returns the smallest (closest to negative infinity) integer that is greater than or equal to the argument.
math.ceil(number)
Returns The smallest integer less than or equal to the given number.
See also
math.floor
math.round
The cos function returns the trigonometric cosine of an angle.
math.cos(angle)
Returns The trigonometric cosine of an angle.
Arguments
angle
(series int/float) Angle, in radians.The exp function of number
is e raised to the power of number
, where e is Euler’s number.
math.exp(number)
Returns
A value representing e raised to the power of number
.
See also
math.pow
math.floor(number)
Returns The largest integer less than or equal to the given number.
See also
math.ceil
math.round
Natural logarithm of any number
> 0 is the unique y such that e^y = number
.
math.log(number)
Returns
The natural logarithm of number
.
See also
math.log10
The common (or base 10) logarithm of number
is the power to which 10 must be raised to obtain the number
. 10^y = number
.
math.log10(number)
Returns
The base 10 logarithm of number
.
See also
math.log
Mathematical power function.
math.pow(base, exponent)
Example
// math.pow
plot(math.pow(close, 2))
Returns
base
raised to the power of exponent
. If base
is a series, it is calculated elementwise.
Arguments
base
(series int/float) Specify the base to use.exponent
(series int/float) Specifies the exponent.See also
math.sqrt
math.exp
Sign (signum) of “number” is zero if “number” is zero, 1.0 if “number” is greater than zero, -1.0 if “number” is less than zero.
math.sign(number)
Returns The sign of the argument.
The sin function returns the trigonometric sine of an angle.
math.sin(angle)
Returns The trigonometric sine of an angle.
Arguments
angle
(series int/float) Angle, in radians.Square root of any number
>= 0 is the unique y >= 0 such that y^2 = number
.
math.sqrt(number)
Returns
The square root of number
.
See also
math.pow
The tan function returns the trigonometric tangent of an angle.
math.tan(angle)
Returns The trigonometric tangent of an angle.
Arguments
angle
(series int/float) Angle, in radians.Returns the value of number
rounded to the nearest integer, with ties rounding up. If the precision
parameter is used, returns a float value rounded to that amount of decimal places.
math.round(number)
math.round(number, precision)
Returns
The value of number
rounded to the nearest integer, or according to precision.
Arguments
number
(series int/float) The value to be rounded.precision
(series int) Optional argument. Decimal places to which number
will be rounded. When no argument is supplied, rounding is to the nearest integer.Remarks Note that for ‘na’ values function returns ‘na’.
See also
math.ceil
math.floor
Returns the greatest of multiple values.
math.max(number0, number1, ...)
Example
// math.max
plot(math.max(close, open))
plot(math.max(close, math.max(open, 42)))
Returns The greatest of multiple given values.
See also
math.min
Returns the smallest of multiple values.
math.min(number0, number1, ...)
Example
// math.min
plot(math.min(close, open))
plot(math.min(close, math.min(open, 42)))
Returns The smallest of multiple given values.
See also
math.max
Calculates average of all given series (elementwise).
math.avg(number0, number1, ...)
Returns Average.
See also
math.sum
ta.cum
ta.sma
Returns the value rounded to the symbol’s mintick, i.e. the nearest value that can be divided by syminfo.mintick, without the remainder, with ties rounding up.
math.round_to_mintick(number)
Returns
The number
rounded to tick precision.
Arguments
number
(series int/float) The value to be rounded.See also
math.ceil
math.floor
The sum function returns the sliding sum of last y values of x.
math.sum(source, length)
Returns
Sum of source
for length
bars back.
Arguments
source
(series int/float) Series of values to process.length
(series int) Number of bars (length).See also
ta.cum
for
Returns an approximately equivalent angle in degrees from an angle measured in radians.
math.todegrees(radians)
Returns The angle value in degrees.
Arguments
radians
(series int/float) Angle in radians.Returns an approximately equivalent angle in radians from an angle measured in degrees.
math.toradians(degrees)
Returns The angle value in radians.
Arguments
degrees
(series int/float) Angle in degrees.For a given series replaces NaN values with previous nearest non-NaN value.
fixnan(source)
Returns Series without na gaps.
Arguments
source
(series int/float/bool/color)See also
na
nz
Replaces NaN values with zeros (or given value) in a series.
nz(source, replacement)
nz(source)
Example
// nz
plot(nz(ta.sma(close, 100)))
Returns
The value of source
if it is not na
. If the value of source
is na
, returns zero, or the replacement
argument when one is used.
Arguments
source
(series int/float/bool/color) Series of values to process.replacement
(series int/float/bool/color) Value that will replace all ‘na’ values in the source
series.See also
na
fixnan
Test value if it’s a NaN.
na(x)
Returns true if x is not a valid number (x is NaN), otherwise false.
See also
fixnan
nz
Casts na or truncates float value to int.
int(x)
Returns The value of the argument after casting to int.
See also
float
bool
color
string
Casts na to float.
float(x)
Returns The value of the argument after casting to float.
See also
int
bool
color
string
Triggers an alert event when called during the real-time bar and an alert based on alert function events was previously created for the indicator or strategy through the “Create Alert” dialog box.
alert(message, freq)
Example
// alert() example
ma = ta.sma(close, 14)
xUp = ta.crossover(close, ma)
if xUp
// Trigger the alert the first time a cross occurs during the real-time bar.
alert("Price (" + str.tostring(close) + ") crossed over MA (" + str.tostring(ma) + ").", alert.freq_once_per_bar)
plot(ma)
plotchar(xUp, "xUp", "▲", location.top, size = size.tiny)
Arguments
message
(series string)Message sent when the alert triggers. Required argument.freq
(input string) The triggering frequency. Possible values are: alert.freq_all (all function calls trigger the alert), alert.freq_once_per_bar (the first function call during the bar triggers the alert), alert.freq_once_per_bar_close (the function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it closes). The default is alert.freq_once_per_bar.Remarks The Help Center explains how to create such alerts. Contrary to alertcondition, alert calls do NOT count as an additional plot. Function calls can be located in both global and local scopes. Function calls do not display anything on the chart. The ‘freq’ argument only affects the triggering frequency of the function call where it is used.
See also
alertcondition
Creates alert condition, that is available in Create Alert dialog. Please note, that alertcondition does NOT create an alert, it just gives you more options in Create Alert dialog. Also, alertcondition effect is invisible on chart.
alertcondition(condition, title, message)
Example
// alertcondition
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')
Arguments
condition
(series bool) Series of boolean values that is used for alert. True values mean alert fire, false - no alert. Required argument.title
(const string) Title of the alert condition. Optional argument.message
(const string) Message to display when alert fires. Optional argument.Remarks Please note that in Pine Script v4/v5 an alertcondition call generates an additional plot. All such calls are taken into account when we calculate the number of the output series per script.
See also
alert
In order to be compatible with the Trading View
strategy code, it is not actually required to be called.
See also
strategy
The time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session. Note that FMZ does not support session
arguments.
time(timeframe, session, timezone)
time(timeframe, session)
time(timeframe)
Example
timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=color.red)
// This plots 1.0 at every start of 10 minute bar on a 1 minute chart:
newbar(res) => ta.change(time(res)) == 0 ? 0 : 1
plot(newbar("10"))
While setting up a session you can specify not just the hours and minutes but also the days of the week that will be included in that session. If the days aren’t specified, the session is considered to have been set from Sunday (1) to Saturday (7), i.e. “1100-2000” is the same as “1100-1200:1234567”. You can change that by specifying the days. For example, on a symbol that is traded seven days a week with the 24-hour trading session the following script will not color Saturdays and Sundays:
Example
// Time
t1 = time(timeframe.period, "0000-0000:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
One session
argument can include several different sessions, separated by commas. For example, the following script will highlight the bars from 10:00 to 11:00 and from 14:00 to 15:00 (workdays only):
Example
// Time
t1 = time(timeframe.period, "1000-1100,1400-1500:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
Returns UNIX time.
Arguments
timeframe
(simple string) Timeframe. An empty string is interpreted as the current timeframe of the chart.session
timezone
(simple string) Timezone of the session
argument. It can only be used when a “session” is specified. Optional. The default is syminfo.timezone. Can be specified in GMT notation (e.g. “GMT-5”) or as an IANA time zone database name (e.g. “America/New_York”).Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
year(time)
year(time, timezone)
Returns Year (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional argument. Timezone.Reamrks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp. Note that this function returns the year based on the time of the bar’s open. For overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00 UTC-4) this value can be lower by 1 than the year of the trading day.
See also
year
time
month
dayofmonth
dayofweek
hour
minute
second
month(time)
month(time, timezone)
Returns Month (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional argument. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp. Note that this function returns the month based on the time of the bar’s open. For overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00 UTC-4) this value can be lower by 1 than the month of the trading day.
See also
month
time
year
dayofmonth
dayofweek
hour
minute
second
hour(time)
hour(time, timezone)
Returns Hour (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional parameter. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp.
See also
hour
time
year
month
dayofmonth
dayofweek
minute
second
minute(time)
minute(time, timezone)
Returns Minute (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional argument. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp.
See also
minute
time
year
month
dayofmonth
dayofweek
hour
second
second(time)
second(time, timezone)
Returns Second (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional parameter. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp.
See also
second
time
year
month
dayofmonth
dayofweek
hour
minute
weekofyear(time)
weekofyear(time, timezone)
Returns Week of year (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional parameter. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp. Note that this function returns the week based on the time of the bar’s open. For overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00) this value can be lower by 1 than the week of the trading day.
See also
weekofyear
time
year
month
dayofmonth
dayofweek
hour
minute
second
dayofweek(time)
dayofweek(time, timezone)
Returns Day of week (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) UNIX time in milliseconds.timezone
(series string) An optional parameter. Timezone.Remarks Note that this function returns the day based on the time of the bar’s open. For overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00) this value can be lower by 1 than the day of the trading day. UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp.
See also
time
dayofmonth
dayofmonth(time)
dayofmonth(time, timezone)
Returns Day of month (in exchange timezone) for provided UNIX time.
Arguments
time
(series int) unix time in milliseconds.timezone
(series string) An optional parameter. Timezone.Remarks UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970. By default, the Timezone is syminfo.timezone, possible values can be seen in timestamp. Note that this function returns the day based on the time of the bar’s open. For overnight sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00 UTC-4) this value can be lower by 1 than the day of the trading day.
See also
time
dayofweek
Function timestamp returns UNIX time of specified date and time.
timestamp(dateString)
timestamp(year, month, day, hour, minute, second)
timestamp(timezone, year, month, day, hour, minute, second)
Example
// timestamp
plot(timestamp(2016, 01, 19, 09, 30), linewidth=3, color=color.green)
plot(timestamp(syminfo.timezone, 2016, 01, 19, 09, 30), color=color.blue)
plot(timestamp(2016, 01, 19, 09, 30), color=color.yellow)
plot(timestamp("GMT+6", 2016, 01, 19, 09, 30))
plot(timestamp(2019, 06, 19, 09, 30, 15), color=color.lime)
plot(timestamp("GMT+3", 2019, 06, 19, 09, 30, 15), color=color.fuchsia)
plot(timestamp("Feb 01 2020 22:10:05"))
plot(timestamp("2011-10-10T14:48:00"))
The BeggarWhy the strategy of the square replica of the strategy of the pine can not be realized
Inventors quantify - small dreamsWell, let's have a look.
The BeggarChang's Optimized Trend Tracker is a great tool.
Inventors quantify - small dreamsHello, what exactly is the strategy?