Returns the valueThe median of an array element.
Parameters
id
(int[]/float[]) array objects.See you later
array.avg
array.variance
array.min
The function returns the pattern of the array element. It returns the minimum value if there are multiple values of the same frequency.
array.mode(id)
Examples
// array.mode example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.mode(a))
Returns the valueThe pattern of array elements.
Parameters
id
(int[]/float[]) array objects.See you later
array.new_float
array.avg
array.variance
array.min
Returns a specified percentage of an array value that is less than or equal to its value, using a linear insertion.
array.percentile_linear_interpolation(id, percentage)
Parameters
id
(int[]/float[]) array objects.percentage
(series int/float) must be the percentage of the value that is less than or equal to the returned value.NotesIn statistics, a percentage is the percentage of ranked items that appear at or below a certain score. This measurement shows the percentage of fractions in the standard frequency distribution that are below the percentage rank you are measuring. Linear insertion estimates the value between two rankings.
See you later
array.new_float
array.insert
array.slice
array.reverse
order.ascending
order.descending
Returns an array value for a specified percentage (percentage) that is less than or equal to it using the nearest order method.
array.percentile_nearest_rank(id, percentage)
Parameters
id
(int[]/float[]) array objects.percentage
(series int/float) must be the percentage of the value that is less than or equal to the returned value.NotesIn statistics, a percentage is the percentage of ranked items that appear at or below a certain score. This measurement shows the percentage of fractions in the standard frequency distribution below the percentage rank you are measuring.
See you later
array.new_float
array.insert
array.slice
array.reverse
order.ascending
order.descending
Returns the percentage rank of the median of the array.
array.percentrank(id, index)
Parameters
id
(int[]/float[]) array objects.index
(series int) calculates the value of its percentage ranking.NotesThe percentage rank is the percentage of how many elements are less than or equal to the reference value in the array.
See you later
array.new_float
array.insert
array.slice
array.reverse
order.ascending
order.descending
The function returns the difference between the minimum and maximum values of the given array.
array.range(id)
Examples
// array.range example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.range(a))
Returns the valueThe difference between the minimum and maximum values in the array.
Parameters
id
(int[]/float[]) array objects.See you later
array.new_float
array.min
array.max
array.sum
This function changes the contents of the array by removing elements with specified indexes.
array.remove(id, index)
Examples
// array.remove example
a = array.new_float(5,high)
removedEl = array.remove(a, 0)
plot(array.size(a))
plot(removedEl)
Returns the valueThe value of the deleted element.
Parameters
id
(any array type) Array object.index
(series int) The index of the elements to be deleted.See you later
array.new_float
array.set
array.push
array.insert
array.pop
array.shift
This function reverses the array. The first array element becomes the last, and the last array element becomes the first.
array.reverse(id)
Examples
// array.reverse example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))
Parameters
id
(any array type) Array object.See you later
array.new_float
array.sort
array.push
array.set
array.avg
The function takes a variable number of arguments of one of the following types: int, float, boolean, string, line, color, linefill, and returns an array of the corresponding type.
array.from(arg0, arg1, ...)
Examples
// array.from_example
arr = array.from("Hello", "World!") // arr (string[]) will contain 2 elements: {Hello}, {World!}.
plot(close)
Returns the valueThe value of the array element.
Parameters
arg0, arg1, ...
(series int/float/bool/color/string/line/linefill) Array of parametersThis function creates a new<type>
Elementary array objects.
array.new(size, initial_value)
Examples
// array.new<string> example
a = array.new<string>(1, "Hello, World!")
runtime.log(array.get(a, 0))
Examples
// array.new<color> example
a = array.new<color>()
array.push(a, color.red)
array.push(a, color.green)
plot(close, color = array.get(a, close > open ? 1 : 0))
Examples
// array.new<float> example
length = 5
var a = array.new<float>(length, close)
if array.size(a) == length
array.remove(a, 0)
array.push(a, close)
plot(array.sum(a) / length, "SMA")
Examples
// array.new<line> example
// draw last 15 lines
var a = array.new<line>()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
Returns the valueAn ID of an array object that can be used with other arrays.
Parameters
size
(series int) The initial size of the series is "0".initial_value
(series NotesThe array index starts at 0. If you want to initialize an array and specify all its elements at the same time, use the function array.from.
See you later
array.from
array.push
array.get
array.size
array.remove
array.shift
array.sum
This function creates a new array object consisting of elements of type bool.
array.new_bool(size, initial_value)
Examples
// array.new_bool example
length = 5
a = array.new_bool(length, close > open)
plot(array.get(a, 0) ? close : open)
Returns the valueAn ID of an array object that can be used with other arrays.
Parameters
size
(series int) The initial size of the series is "0".initial_value
(series bool) The initial value of all sequence elements↑ optional↑ the default value is NotesThe array index starts at 0.
See you later
array.new_float
array.get
array.slice
array.sort
This function creates a new floating-point element array object.
array.new_float(size, initial_value)
Examples
// array.new_float example
length = 5
a = array.new_float(length, close)
plot(array.sum(a) / length)
Returns the valueAn ID of an array object that can be used with other arrays.
Parameters
size
(series int) The initial size of the series is "0".initial_value
(series int/float) Initial value of all sequence elements. Optional. Default is NotesThe array index starts at 0.
See you later
array.new_bool
array.get
array.slice
array.sort
The function creates a new array object consisting of elements of type int.
array.new_int(size, initial_value)
Examples
// array.new_int example
length = 5
a = array.new_int(length, int(close))
plot(array.sum(a) / length)
Returns the valueAn ID of an array object that can be used with other arrays.
Parameters
size
(series int) The initial size of the series is "0".initial_value
(series int) The initial value of all sequence elements↑ is optional↑ the default value is NotesThe array index starts at 0.
See you later
array.new_float
array.get
array.slice
array.sort
This function creates a new array object with a string type element.
array.new_string(size, initial_value)
Examples
// array.new_string example
length = 5
a = array.new_string(length, "text")
runtime.log(array.get(a, 0))
Returns the valueAn ID of an array object that can be used with other arrays.
Parameters
size
(series int) The initial size of the series is "0".initial_value
(series string) Initial value of all sequence elements↑ Optional↑ Default value is NotesThe array index starts at 0.
See you later
array.new_float
array.get
array.slice
The function returns the value of the specified index element.
array.get(id, index)
Examples
// array.get example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i] - open[i])
plot(array.get(a, 9))
Returns the valueThe value of the array element.
Parameters
id
(any array type) Array object.index
(series int) The index of the element to return its value.See you later
array.new_float
array.set
array.slice
array.sort
The function appends a value to the array.
array.push(id, value)
Examples
// array.push example
a = array.new_float(5, 0)
array.push(a, open)
plot(array.get(a, 5))
Parameters
id
(any array type) Array object.value
(series <type of the array's elements>
) is added to the element value at the end of the array.See you later
array.new_float
array.set
array.insert
array.remove
array.pop
array.unshift
The function sets the value of the element to the specified index.
array.set(id, index, value)
Examples
// array.set example
a = array.new_float(10)
for i = 0 to 9
array.set(a, i, close[i])
plot(array.sum(a) / 10)
Parameters
id
(any array type) Array object.index
(series int) to modify the index of the element.value
(series <type of the array's elements>
) The new value to be set.See you later
array.new_float
array.get
array.slice
The function returns the sum of the elements of the array.
array.sum(id)
Examples
// array.sum example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
Returns the valueThe sum of the elements of the array.
Parameters
id
(int[]/float[]) array objects.See you later
array.new_float
array.max
array.min
The function returns the mean of the array elements.
array.avg(id)
Examples
// array.avg example
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
Returns the valueThe mean value of the array element.
Parameters
id
(int[]/float[]) array objects.See you later
array.new_float
array.max
array.min
array.stdev
This function returns the index in which the value first appeared. If the value cannot be found, it returns −1.
array.indexof(id, value)
Examples
// array.indexof example
a = array.new_float(5,high)
index = array.indexof(a, high)
plot(index)
Returns the valueThe index of the element.
Parameters
id
(any array type) Array object.value
(series <type of the array's elements>
The value to be searched in the array.See you later
array.lastindexof
array.get
array.lastindexof
array.remove
array.insert
In thestrategy
In the related built-in functions, stop-loss number, stop-loss number is defined as the multiple of the price jump; for examplestrategy.exit
of the functionprofit
、loss
Parameters with points indicate stop loss, stop leakage, parametersprofit
Set to 10, i.e. price jump multiplied by 10 as the stop-gap, price jump is the built-in variablesyminfo.mintick
。
The function sets several policy attributes.
Please note that the information is for support only.title
,shorttitle
,overlay
,pyramiding
,default_qty_type
,default_qty_value
Parameters, other parameters can be set by the interface parameters of the PINE language policy.
strategy(title, shorttitle, overlay, format, precision, scale, pyramiding, calc_on_order_fills, calc_on_every_tick, max_bars_back, backtest_fill_limits_assumption, default_qty_type, default_qty_value, initial_capital, currency, slippage, commission_type, commission_value, process_orders_on_close, close_entries_rule, margin_long, margin_short, explicit_plot_zorder, max_lines_count, max_labels_count, max_boxes_count, risk_free_rate)
Examples
strategy("Strategy", overlay = true)
// Enter long by market if current open is greater than previous high.
strategy.entry("Long", strategy.long, 1, when = open > high[1])
// Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".
strategy.exit("Exit", "Long", profit = 10, loss = 5)
Parameters
title
(const string) will show the indicator title seen in the indicator/strategy plugin. Parameters are required.shorttitle
(const string) will show the short title of the indicator seen in the chart example. The parameter is optional.overlay
(const bool) If true, the pointer is added to the overlay of the main series. If false - it is added to a separate chart pane. Default false.format
precision
scale
pyramiding
(const int) Maximum number of entries allowed in the same direction. If this value is 0, only one entry order can be opened in the same direction, and any other entry order will be rejected. The default value is 0.calc_on_order_fills
calc_on_every_tick
max_bars_back
backtest_fill_limits_assumption
default_qty_type
(const string) is defined forqty
The value of the parameter is the content expressed in the strategy.entry or strategy.order functions. Possible values are: strategy.fixed for contracts/stocks/number of hands, strategy.cash for monetary amount, or strategy.percent_of_equity for percentage of equity available.default_qty_value
(const int/float) The default number of transactions of the strategy.entry or strategy.order functions, when their currency
slippage
commission_type
commission_value
process_orders_on_close
close_entries_rule
max_lines_count
max_labels_count
max_boxes_count
margin_long
margin_short
explicit_plot_zorder
initial_capital
risk_free_rate
NotesEvery strategy script must have a strategy call. PineScript code that uses the parameter calc_on_every_tick = true can perform different calculations on historical records and real-time data. When using a chart of non-standard type as the basis of the strategy, you need to know that the results will be different. Orders will be executed at the price of the table (e.g. for Heikin Ashi will use the price of Heikin Ashi (average) not the true market price). Therefore, we strongly recommend that you use the standard chart type in your strategy.
See you later
indicator
This is the order to enter the market. If an order with the same ID is already hung, the order can be modified. If an order with the same ID is not specified, a new order will be issued. To stop using the entry order, the command strategy.cancel or strategy.cancel_all should be used. Compared to the strategy.order function, the strategy.entry function is influenced by the pyramid and can correctly reverse the market position.
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)
Examples
strategy(title = "simple strategy entry example")
strategy.entry("enter long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.entry("enter short", strategy.short, 1, when = open < low[1]) // enter short by market if current open less then previous low
Parameters
id
(series string) Required parameters. Order ID. You can cancel or modify an order by referring to its ID.direction
(strategy_direction) A necessary parameter. The direction of the market holdings: strategy.long for multihead, strategy.short for empty head.qty
(series int/float) Optional parameters↑ contract/number of shares/number of hands/number of units traded↑ default value is limit
(series int/float) Optional parameters ∞ Limit price of order ∞ If specified, order type is "limit" or "stop-limit"∞ Other order type is "NaN"∞stop
(series int/float) Optional parameters ∞ Stop-loss price of the order ∞ If specified, order type is "stop" or "stop-limit"; other order type is "NaN".oca_name
oca_type
comment
(series string) Optional parameters. Other instructions for the order.when
(series bool) Optional parameter. Status of the order. If true, the order is placed. If false, nothing happens.alert_message
(series string) An optional parameter when using the {{strategy.order.alert_message}} prefix in the string message field of the string dialog box to create an alert string.This is an order for an exit order with a specified ID. If there are multiple entry orders with the same ID, they will all exit at the same time. The order will not take effect if the open order does not have the specified ID when the order is triggered. The order uses a market order. Each entry is closed by a separate market order.
strategy.close(id, when, comment, qty, qty_percent, alert_message)
Examples
strategy("closeEntry Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close("buy", when = open < close, qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)
Parameters
id
(series string) Necessary parameters. The order identifier. The order can be closed by referring to its identifier.when
(series bool) Optional parameters. Conditions of the command.qty
(series int/float) Optional parameter ⇒ number of contracts/number of shares/number of hands/units withdrawn ⇒ default value ⇒ NaN ⇒qty_percent
(series int/float) defines the percentage of the placement ((0-100)). Its priority is lower than the priority of the comment
(series string) Optional parameters. Other instructions for the order.alert_message
(series string) An optional parameter when using the {{strategy.order.alert_message}} prefix in the string message field of the string dialog box to create an alert string.In addition, the government has announced that it will withdraw from the current market position and keep it flat.
strategy.close_all(when, comment, alert_message)
Examples
strategy("closeAll Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close_all(when = open < close, comment = "close all entries")
plot(strategy.position_size)
Parameters
when
(series bool) Optional parameters. Conditions of the command.comment
(series string) Optional parameters. Other instructions for the order.alert_message
(series string) An optional parameter when using the {{strategy.order.alert_message}} prefix in the string message field of the string dialog box to create an alert string.This is an exit order that specifies an entry or an entire market position. The order can be modified if an order with the same ID has already been placed. If an entry order is not executed, but a withdrawal order appears, the withdrawal order will be suspended until the exit order can be placed after the entry order has been executed. To stop using an exit order, the command strategy.cancel or strategy.cancel_all should be used. If the strategy.exit function is called once, it will withdraw only once.应该多次调用命令strategy.exitIf you use stop loss and track stop loss, the order type is a stop loss, only one of which will be placed (will be traded first). If all of the following parameters are set to NaN, the order will fail if the stop loss, stop loss, stop profit, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss, stop loss.
strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, when, alert_message)
Examples
strategy(title = "simple strategy exit example")
strategy.entry("long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"
Parameters
id
(series string) Required parameters. Order ID. You can cancel or modify an order by referring to its ID.from_entry
(series string) Optional parameter↑ to specify input command identifier exit↑ to exit all positions, use empty string↑ the default is empty string↑qty
(series int/float) Optional parameter ⇒ number of contracts/number of shares/number of hands/units withdrawn ⇒ default value ⇒ NaN ⇒qty_percent
(series int/float) defines the percentage of the placement ((0-100)). Its priority is lower than the priority of the profit
(series int/float) Optional parameter ∞ Profit target ∞ If specified, exit the market position with a limit order when the specified profit amount ∞ is reached. Default is ∞ NaN ∞.limit
(series int/float) Optional parameter. Profit objective (price to be specified). If specified, exit the market position at the specified price (or better). The priority of the parameter is higher than the priority of the parameter is higher.loss
(series int/float) Optional parameter ─ Stop loss (indicated by a dot) ─ If specified, exit the market position with a stop loss when the specified loss amount (indicated by a dot) is reached ─ Default value is stop
(series int/float) Optional parameter. Stop-loss (price to be specified). If specified, exit the market position at the specified price (price) or worse. Priority of the stop-loss parameter is higher than the priority of the stop-loss parameter.trail_price
(series int/float) Optional parameter. Track stop loss activation level (requires price specification). If specified, when the specified price level is reached, the track stop loss list will be placed. Specify the deviation used to determine the initial price of the track stop loss list in the stringtrail_offset string parameter (point count): X points below the activation level to exit multiple heads; X points above the activation level to exit blank heads.trail_points
(series int/float) Optional parameter. Track stop-loss activation level. If specified, when the calculated price level is reached. Specify the amount of profit.trail_offset
(series int/float) Optional parameter. Tracking stop loss activation level (indicated in dots) The deviation of the pointer is used to determine the initial price of the tracking stop loss order: X points lower than the trail_price or 'trail_points' button to exit multiple heads; X points higher than the trail_price button or 'trail_points' button to exit blank heads.oca_name
comment
(series string) Optional parameters. Other instructions for the order.when
(series bool) Optional parameter. Status of the order. If true, the order is placed. If false, nothing happens.alert_message
(series string) An optional parameter when using the {{strategy.order.alert_message}} prefix in the string message field of the string dialog box to create an alert string.This is a name reference to cancel/disallow all pending list commands, generated by the following functions: strategy.order, strategy.entry andstrategy.exit。
strategy.cancel(id, when)
Examples
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
Parameters
id
(series string) Must select parameter↑ order symbol↑ locate this symbol to revoke an order↑when
(series bool) Optional parameter↑ Cancel an order based on ID↑ If true, the order will be canceled↑ Default is true↑这是取消/停用所有预挂单命令,由以下功能生成:strategy.order,strategy.entry和strategy.exit。
strategy.cancel_all(when)
Examples
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
Parameters
when
(series bool) Optional parameter↑ Cancel all orders conditions↑ If the condition is true, all active orders will be canceled↑ Default is This is the command to place the order. If an order with the same ID is already hung, the order can be modified. If an order with no ID is specified, a new order is issued. To stop the order, the command strategy.cancel or strategy.cancel_all should be used. Compared to the strategy.entry function, the strategy.order function is not affected by the pyramid form.
strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)
Examples
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
Parameters
id
(series string) Required parameters. Order ID. You can cancel or modify an order by referring to its ID.direction
(strategy_direction) A necessary parameter. The order direction:'strategy.long' is for buying,'strategy.short' is for selling.qty
(series int/float) Optional parameters↑ contract/number of shares/number of hands/number of units traded↑ default value is limit
(series int/float) Optional parameters ∞ Limit price of order ∞ If specified, order type is "limit" or "stop-limit"∞ Other order type is "NaN"∞stop
(series int/float) Optional parameters ∞ Stop-loss price of the order ∞ If specified, order type is "stop" or "stop-limit"; other order type is "NaN".oca_name
oca_type
comment
(series string) Optional parameters. Other instructions for the order.when
(series bool) Optional parameter. Status of the order. If true, the order is placed. If false, nothing happens.alert_message
(series string) An optional parameter when using the {{strategy.order.alert_message}} prefix in the string message field of the string dialog box to create an alert string.Returns the bar_index of the unbroken trade entry.
strategy.opentrades.entry_bar_index(trade_num)
Wait for 10 K lines and level
Examples
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")
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.See you later
strategy.closedtrades.entry_bar_index
strategy.closedtrades.exit_bar_index
Returns the ID of the entry of the unbroken transaction.
strategy.opentrades.entry_id(trade_num)
Examples
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 the valueReturns the ID of the entry of the unbroken transaction.
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.NotesIf trade_num is not in the range, the function returns na:0 to strategy.opentrades−1.
See you later
strategy.opentrades.entry_bar_index
strategy.opentrades.entry_time
Return the entry price of the unbroken transaction.
strategy.opentrades.entry_price(trade_num)
Examples
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 unbalanced price
Examples
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())
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.See you later
strategy.closedtrades.exit_price
Returns the UNIX time of entry of the unbroken transaction.
strategy.opentrades.entry_time(trade_num)
Examples
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")
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.See you later
strategy.closedtrades.entry_time
strategy.closedtrades.exit_time
Returns the gain or loss on the unbroken transaction.
strategy.opentrades.profit(trade_num)
Returning the profit from the last trade
Examples
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 unbroken trades
Examples
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")
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.See you later
strategy.closedtrades.profit
strategy.openprofit
strategy.netprofit
strategy.grossprofit
Returns the direction of the trade and the number of contracts in the unbroken trade. If the value is > 0, the market position is multi-headed. If the value is < 0, the market position is blank.
strategy.opentrades.size(trade_num)
Examples
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 percentage of average profits from unbroken trades
Examples
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)
Parameters
trade_num
(series int) Transaction number of unbroken transaction. The first transaction is numbered zero.See you later
strategy.closedtrades.size
strategy.position_size
strategy.opentrades
strategy.closedtrades
Returns the bar_index of the transaction that has already been settled.
strategy.closedtrades.entry_bar_index(trade_num)
Examples
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())
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
strategy.closedtrades.exit_bar_index
strategy.opentrades.entry_bar_index
Returns the exit price of a transaction that has been liquidated.
strategy.closedtrades.exit_price(trade_num)
Examples
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 percentage of average profit on all trades that have been settled
Examples
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)
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
strategy.closedtrades.entry_price
Returns bar_index which has been deleted from the trading.
strategy.closedtrades.exit_bar_index(trade_num)
Examples
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")
Calculates the average number of K lines per transaction.
Examples
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())
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
bar_index
Returns the login id of the transaction that has been settled.
strategy.closedtrades.entry_id(trade_num)
Examples
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 the valueReturns the login id of the transaction that has been settled.
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.NotesIf the trade_num is not in range, the function returns na:0 to strategy.closedtrades−1.
See you later
strategy.closedtrades.entry_bar_index
strategy.closedtrades.entry_time
Return the entry price of a transaction that has already been liquidated.
strategy.closedtrades.entry_price(trade_num)
Examples
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 percentage of average profit on all trades that have been settled
Examples
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)
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
strategy.closedtrades.exit_price
strategy.closedtrades.size
strategy.closedtrades
Returns the UNIX time of entry into the trading floor.
strategy.closedtrades.entry_time(trade_num)
Examples
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")
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
strategy.opentrades.entry_time
strategy.closedtrades.exit_time
time
Return the profit and loss of the transaction that has been settled.
strategy.closedtrades.profit(trade_num)
Examples
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")
Parameters
trade_num
(series int) The transaction number of the transaction that has been settled. The first transaction number is zero.See you later
strategy.opentrades.profit
strategy.closedtrades.commission
Returns the direction of the trade and the number of contracts in the transaction that has been settled. If the value is > 0, the market position is multi-headed. If the value is < 0, the market position is blank.
strategy.closedtrades.size(trade_num)
Examples
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 percentage of average profit on a spot transaction
Examples
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.closedtrade
wuhuoyanHow do you do it if you want to have multiple transactions running simultaneously?
Light cloudsPlease tell me, can pine do more transactions? Can it also go through transactions like JS? Thank you.
lisa20231Thank you for providing detailed documentation.
artistryWow! How does this pine script use the okex simulation on the platform?
artistryThis is equivalent to copying the tradingview platform's strategy directly to the inventor platform and using it!
Inventors quantify - small dreamsThe PINE language can only do single-variety strategies, multi-variety strategies are best written in python, javascript, c++.
Inventors quantify - small dreamsOh, yes, OKX is special, their analog environment and the real disk environment have the same address, only the difference is made elsewhere.
Light cloudsI can't use the okx analogue disc.
Inventors quantify - small dreamsThis multi-variety architecture problem cannot be solved, because each exchange has a different interface, and the frequency limitation of the interface is not the same, which causes many problems.
Inventors quantify - small dreamsWell, thank you for the suggestion, please report this request here.
Light cloudsIt feels better to be able to mix with JS and JS can be better adapted to different trading methods.
The trend hunterIn the future, will we consider more varieties?
Inventors quantify - small dreamsI'm not being polite.
Light cloudsGood, thank you very much.
Inventors quantify - small dreamsHello, the PINE language policy is currently only for single varieties.
Inventors quantify - small dreamsThank you for your support. The documentation will continue to be improved.
Inventors quantify - small dreamsYes, I did.
Inventors quantify - small dreamsPINE template library, where parameters can be set to switch exchange base addresses.