FMZ PINE Script documentation is provided.

Author: Inventors quantify - small dreams, Created: 2022-05-06 14:27:06, Updated: 2024-10-12 15:27:04

Returns the valueThe median of an array element.

Parameters - id(int[]/float[]) array objects.

See you later


### array.mode

该函数返回阵列元素的模式。如果有多个具有相同频率的值,则返回最小值。

array.mode(id)


**例子**
```pine
// 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.percentile_linear_interpolation

返回数组值的指定百分比(百分位数)小于或等于它的值,使用线性插值。

array.percentile_linear_interpolation(id, percentage)


**参数**
- ```id``` (int[]/float[]) 阵列对象。
- ```percentage``` (series int/float) 必须等于或小于返回值的值的百分比。

**备注**
在统计数据中,百分位是出现在某个分数或低于某个分数的排名项目的百分比。此测量显示低于您测量的百分等级的标准频率分布中的分数百分比。线性插值估计两个排名之间的值。

**另见**
```array.new_float``` ```array.insert``` ```array.slice``` ```array.reverse``` ```order.ascending``` ```order.descending```

### array.percentile_nearest_rank

使用最近秩方法返回指定百分比的数组值(百分位数)小于或等于它的值。

array.percentile_nearest_rank(id, percentage)


**参数**
- ```id``` (int[]/float[]) 阵列对象。
- ```percentage``` (series int/float) 必须等于或小于返回值的值的百分比。

**备注**
在统计数据中,百分位是出现在某个分数或低于某个分数的排名项目的百分比。 此测量显示低于您正在测量的百分排名的标准频率分布中的分数百分比。

**另见**
```array.new_float``` ```array.insert``` ```array.slice``` ```array.reverse``` ```order.ascending``` ```order.descending```

### array.percentrank

返回阵列中值的百分位排名。

array.percentrank(id, index)


**参数**
- ```id``` (int[]/float[]) 阵列对象。
- ```index``` (series int) 计算其百分排名的值。

**备注**
百分位排名是数组中有多少元素小于或等于参考值的百分比。

**另见**
```array.new_float``` ```array.insert``` ```array.slice``` ```array.reverse``` ```order.ascending``` ```order.descending```

### array.range

该函数返回给定数组的最小值和最大值之间的差。

array.range(id)


**例子**
```pine
// 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.remove

该函数通过删除具有指定索引的元素来更改阵列的内容。

```array.remove(id, index)```

**例子**
```pine
// 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. - What?index(series int) The index of the elements to be deleted.

See you later


### array.reverse

此函数反转阵列。第一个阵列元素变成最后一个,最后一个阵列元素变成第一个。

array.reverse(id)


**例子**
```pine
// 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.from

该函数采用以下类型之一的可变数量的参数:int、float、bool、string、line、color、linefill,并返回相应类型的阵列。

array.from(arg0, arg1, …)


**例子**
```pine
// 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 parameters

array.new

This 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 - sizeThe initial size of the (series int) series is "0" (optional). - What?initial_value(series <type>) The initial value of all sequence elements↑ Optional↑ The default value is na

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.new_bool

此函数创建一个由bool类型的元素组成的新阵列对象。

array.new_bool(size, initial_value)


**例子**
```pine
// 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 - sizeThe initial size of the (series int) series is "0" (optional). - What?initial_value(series bool) The initial value of all sequence elements↑ optional↑ the default value is na

NotesThe array index starts at 0.

See you later


### array.new_float

此函数创建一个新的浮点型元素阵列对象。

array.new_float(size, initial_value)


**例子**
```pine
// 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 - sizeThe initial size of the (series int) series is "0" (optional). - What?initial_value(series int/float) Initial value of all sequence elements. Optional. Default is na.

NotesThe array index starts at 0.

See you later


### array.new_int

该函数创建一个由int类型的元素组成的新阵列对象。

array.new_int(size, initial_value)


**例子**
```pine
// 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 - sizeThe initial size of the (series int) series is "0" (optional). - What?initial_value(series int) The initial value of all sequence elements↑ is optional↑ the default value is na

NotesThe array index starts at 0.

See you later


### array.new_string

该函数创建一个字符串类型元素的新阵列对象。

array.new_string(size, initial_value)


**例子**
```pine
// 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 - sizeThe initial size of the (series int) series is "0" (optional). - What?initial_value(series string) Initial value of all sequence elements↑ Optional↑ Default value is na

NotesThe array index starts at 0.

See you later


### array.get

该函数返回指定索引处元素的值。

```array.get(id, index)```

**例子**
```pine
// 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. - What?index(series int) The index of the element to return its value.

See you later


### array.push

该函数将一个值附加到阵列。

array.push(id, value)


**例子**
```pine
// 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. - What?value (series <type of the array's elements>) is added to the element value at the end of the array.

See you later


### array.set

该函数将元素的值设置为指定的索引。

array.set(id, index, value)


**例子**
```pine
// 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. - What?index(series int) to modify the index of the element. - What?value (series <type of the array's elements>) The new value to be set.

See you later


### array.sum

该函数返回阵列元素的总和。

array.sum(id)


**例子**
```pine
// 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.avg

该函数返回阵列元素的均值。

array.avg(id)


**例子**
```pine
// 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.indexof

此函数返回值首次出现的索引。如果找不到该值,则返回 -1。

array.indexof(id, value)


**例子**
```pine
// 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. - What?value (series <type of the array's elements>The value to be searched in the array.

See you later


## strategy

在```strategy```相关的内置函数中,止损点数、止盈点数定义为价格一跳的倍数。例如```strategy.exit```函数的```profit```、```loss```参数以点表示止损、止盈,参数```profit```设置为10,即价格一跳乘以10作为止盈价差,价格一跳即内置变量```syminfo.mintick```。

### strategy

该函数设置了多个策略属性。
注意,传参仅支持```title```,```shorttitle```,```overlay```,```pyramiding```,```default_qty_type```,```default_qty_value```参数,其它参数可以通过PINE语言策略的界面参数设置。

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)


**例子**
```pine
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. - What?shorttitle(const string) will show the short title of the indicator seen in the chart example. The parameter is optional. - What?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. - What?format(const string) The type of possible value for a formatted indicator value on the price axis is: format.inherit、format.price、format.volume、default format.inherit。 - What?precision(const int) The number of digits after the floating point number of the indicator value on the price axis. It must be a non-negative integer and not greater than 16. If omitted, the format of the parent series is used. If format is format.inherit and this parameter is set, the format becomes format.price. - What?scale(scale_type) The indicator should follow the price coordinates. Possible values are scale.right, scale.left, scale.none. - What?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 orders will be rejected. The default value is 0. - What?calc_on_order_fills(const bool) Extra intrabar order computation. If the parameter is set to consttrue, the policy recalculates once the string K is filled after the order. The default is constfalse. - What?calc_on_every_tick(const bool) Additional intrabar policy calculation. If the parameter is set to true, the policy will calculate each time step in real-time without closing the k-string. This parameter does not affect the policy calculation of historical data. The default is false. - What?max_bars_back(const int) is the maximum buffer size that can be used for historical reference policies. If the script code refers to the historical data of a variable (using the buffer operator), this parameter will be applied to each built-in variable or user variable in the script. The size of the variable buffer area in a pine script is usually detected automatically. However, in some cases this is not possible, which is why the parameter allows the user to manually set the lower limit of this value. - What?backtest_fill_limits_assumption(const int) Limit order execution assumption. The limit order is only traded in the intrabar when the market price exceeds the number of ticks specified at the limit order level. - What?default_qty_type(const string) is defined forqtyThe value of the parameter is the content expressed in the strategy.entry or strategy.order functions. Possible values are: strategy.fixed for contracts/stocks/hands, strategy.cash for monetary amounts, or strategy.percent_of_equity for percentages of available equity. - What?default_qty_value(const int/float) The default number of transactions of the strategy.entry or strategy.order functions, when their qty parameters are undefined, is determined by the parameters used in conjunction with the default_qty_type parameters. - What?currency(const string) The account currency of this policy is; optional; the default value is the currency of the commodity on the chart. Possible values are: currency.NONE, currency.USD, currency.EUR, currency.AUD, currency.GBP, currency.NZD, currency.CAD, currency.CHF, currency.HKD, currency.JPY, currency.NOK, currency.SEK, currency.SGD, currency.TRY, currency.ZAR, currency.BTC, currency.ETH, currency.MYR, currency.KRW. - What?slippage(const int) A tick as the unit of the bidding slippage is added/subtracted from the transaction price of the buy/sell order or stop loss order. If mintick = 0.01 and the slippage is 5, then the total slippage will be 5 * 0.01 = 0.05. - What?commission_type(const string) Type of commission for each order. Allowed values are: strategy.commission.percent (percentage of ordered cash), strategy.commission.cash_per_contract (amount shown in account currency for each contract), strategy.commission.cash_per_order (amount shown in account currency for each order). - What?commission_value(const int/float) Order commission value. Depending on the type selected (commission type includes percentage or amount). - What?process_orders_on_close(const bool) When set to true-to-true, other attempts to generate execution orders after the chart closes and the strategy calculation is completed. If the order is a market order, the broker simulator will execute them before the next chart opens. If the order is a price limit, the order will only be executed when the price conditions are met. This option is useful if you want to close the current chart position. - What?close_entries_rule(const string) Determines the order of order closure. The allowed value is: FIFO string or ANY string. FIFO (first come, first served; First-In, First-Out) means that the first trade must be closed when multiple trades are open. This rule applies to stocks, futures, and U.S. foreign exchange (NFA compliance rule 2-43b). - What?max_lines_count(const int) Displays the number of recent line graphs. The default is 50, the maximum allowed is 500. - What?max_labels_count(const int) Displays the number of recent tabs. The default is 50, and the maximum allowed is 500. - What?max_boxes_count(const int) The number of last box drawings displayed. The default is 50, the maximum allowed is 500. - What?margin_long(const int/float) Multi-headed collateral is the percentage of the purchase price of a security for which a multi-headed position must be backed by cash or collateral. It must be non-negative. It is optional. - What?margin_short(const int/float) The buyer's margin is the percentage of the purchase price of a security that must be backed by cash or collateral. It must be non-negative. Optional. Default is 100. - What?explicit_plot_zorder(const bool) Specifies the order in which the plots, fillings, and horizontal lines are plotted. If true, the graphs are plotted in the order in which they appear in the indicator code, with each newer graph drawn on top of the previous one. This only applies to the plot*() function, fill, and hline. - What?initial_capital(const int/float) The amount of money initially available for strategic trading, expressed in a currency defined in the currency parity. Optional. Default is 1000000. - What?risk_free_rate(const int/float) The risk-free rate of return is the annual percentage change in the value of an investment with minimal or zero risk, used to calculate the Sharpe and Sortino ratios. The default value is 2.

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


### strategy.entry

这是进入市场的命令。 如果具有相同ID的订单已经挂起,则可修改订单。 如果没有指定ID的订单,则会发出新的订单。 要停用进场指令,应使用命令strategy.cancel或strategy.cancel_all。 与函数strategy.order相比,strategy.entry功能受金字塔影响,可以正确反转市场位置。 如果“Limit”和“stop”参数均为“NaN”,则订单类型为市场订单。

strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)


**例子**
```pine
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. - What?direction(strategy_direction) A necessary parameter. The direction of the market holdings: the strategy.long direction is multiheaded, the strategy.short direction is empty headed. - What?qty(series int/float) Optional parameters↑ contract/number of shares/number of hands/number of units traded↑ default value is NaN↑ - What?limit(series int/float) Optional parameters. Limit price of the order. If specified, order type is limit or stop-limit. Other order type is NaN. - What?stop(series int/float) Optional parameter. Stop-loss price of order. If specified, order type is stop-loss order or stop-limit order. Other order types are stop-loss order. - What?oca_name(series string) Optional parameter. The order belongs to the OCA group name. If the order does not belong to any OCA group, it should have a blank character.Note: FMZ does not support this parameter. - oca_type(input string) Optional parameters. OCA order group type. Allowed values are: strategy.oca.none - orders should not belong to any specific OCA group; strategy.oca.cancel - orders should belong to the OCA group and all other orders in the same group will be canceled once the order has been placed; strategy.oca.reduce - orders should belong to the OCA group, if X number of orders has been placed, the number of other orders in the same OCA group will be reduced by X.Note: FMZ does not support this parameter. - comment(series string) Optional parameters. Other instructions for the order. - What?when(series bool) Optional parameter. Status of the order. If it is a true string, the order is placed. If it is a false string, nothing happens. - What?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.

strategy.close

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. - What?when(series bool) Optional parameters. Conditions of the command. - What?qty(series int/float) Optional parameters ⇒ number of contracts/number of shares/number of hands/units withdrawn ⇒ default value is NaN ⇒ - What?qty_percent(series int/float) defines the percentage of the placement ((0-100)). Its priority is lower than the priority of the qty parameter. Optional. Default is 100. - What?comment(series string) Optional parameters. Other instructions for the order. - What?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.

strategy.close_all

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. - What?comment(series string) Optional parameters. Other instructions for the order. - What?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.

strategy.exit

This is an exit order that specifies an entry or entire market position. If an order with the same ID is already pending, the order can be modified. If an entry order is not executed, but an exit order occurs, the exit order will be suspended until an exit order can be placed after the entry order has been executed. To terminate an exit order, the command strategy.cancel or strategy.cancel_all should be used. If the strategy.exit function is called once, the exit will be only one time. If the exit strategy is called multiple times, the order strategy.exit should be called multiple times.

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. - What?from_entry(series string) Optional parameter↑ to specify input command identifier exit↑ to exit all positions, use empty string↑ the default is empty string↑ - What?qty(series int/float) Optional parameters ⇒ number of contracts/number of shares/number of hands/units withdrawn ⇒ default value is NaN ⇒ - What?qty_percent(series int/float) defines the percentage of the placement ((0-100)). Its priority is lower than the priority of the qty parameter. Optional. Default is 100. - What?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 ∞. - What?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. - What?loss(series int/float) Optional parameter↑ stop loss (dotted)↑ If specified, exit the market position with a stop loss when the specified loss amount (dotted) is reached. - What?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 (priority of the stop loss parameter). - What?trail_price(series int/float) Optional parameter ‧tracking stop loss activation level (requires price specification) ‧ If specified, the stop loss tracking list will be placed when the specified price level is reached ‧ Specify the deviation used to determine the initial price of the tracking stop loss tracking list in the filtertrail_offset filter parameter (point count): X points below the activation level to exit multiple heads; X points above the activation level to exit blank heads ‧Default value is NaN‧ - What?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. - What?trail_offset(series int/float) Optional parameter. Track stop loss activation level (indicated by dots). The deviation of the pointer is used to determine the initial price of the track stop loss order: X points lower than the trail_price string or the trail_points string to exit multiple heads; X points higher than the trail_price string or the trail_points string to exit blank heads. - What?oca_name(series string) Optional parameters ⇒ The name of the OCA group (oca_type = strategy.oca.reduce) ⇒ The profit target, stop/track stop loss ⇒ If no name is specified, the name will be generated automatically ⇒Note: FMZ does not support this parameter. - comment(series string) Optional parameters. Other instructions for the order. - What?when(series bool) Optional parameter. Status of the order. If it is a true string, the order is placed. If it is a false string, nothing happens. - What?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.

strategy.cancel

This is a name reference for the cancellation/deactivation of all preloaded commands, generated by the following functions: strategy.order, strategy.entry and strategy.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↑ - What?when(series bool) Optional parameter ⇒ Cancel an order based on ID ⇒ If the string is set to true, the order will be canceled ⇒ Default is true ⇒

strategy.cancel_all

这是取消/停用所有预挂单命令,由以下功能生成: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 true

strategy.order

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. - What?direction(strategy_direction) A necessary parameter. The order direction is: buy strategy. long strategy, sell strategy. short strategy. - What?qty(series int/float) Optional parameters↑ contract/number of shares/number of hands/number of units traded↑ default value is NaN↑ - What?limit(series int/float) Optional parameters. Limit price of the order. If specified, order type is limit or stop-limit. Other order type is NaN. - What?stop(series int/float) Optional parameter. Stop-loss price of order. If specified, order type is stop-loss order or stop-limit order. Other order types are stop-loss order. - What?oca_name(series string) Optional parameter. The order belongs to the OCA group name. If the order does not belong to any OCA group, it should have a blank character.Note: FMZ does not support this parameter. - oca_type(input string) Optional parameters. OCA order group type. Allowed values are: strategy.oca.none - orders should not belong to any specific OCA group; strategy.oca.cancel - orders should belong to the OCA group and all other orders in the same group will be canceled once the order has been placed; strategy.oca.reduce - orders should belong to the OCA group, if X number of orders has been placed, the number of other orders in the same OCA group will be reduced by X.Note: FMZ does not support this parameter. - comment(series string) Optional parameters. Other instructions for the order. - What?when(series bool) Optional parameter. Status of the order. If it is a true string, the order is placed. If it is a false string, nothing happens. - What?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.

strategy.opentrades.entry_bar_index

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.opentrades.entry_id

返回未平仓交易的入场的ID。

strategy.opentrades.entry_id(trade_num)


**例子**
```pine
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_price

返回未平仓交易的入场价格。

strategy.opentrades.entry_price(trade_num)


**例子**
```pine
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.opentrades.entry_time

返回未平仓交易入场的UNIX时间。

strategy.opentrades.entry_time(trade_num)


**例子**
```pine
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.opentrades.profit

返回未平仓交易的盈亏。损失表示为负值。

strategy.opentrades.profit(trade_num)


返回最后开仓交易的利润

**例子**
```pine
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.opentrades.size

返回未平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。如果该值<0,则市场仓位为空头。

strategy.opentrades.size(trade_num)


**例子**
```pine
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.entry_bar_index

返回已平仓交易入场的bar_index。

strategy.closedtrades.entry_bar_index(trade_num)


**例子**
```pine
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_price

返回已平仓交易的出场价格。

strategy.closedtrades.exit_price(trade_num)


**例子**
```pine
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.exit_bar_index

返回已平仓交易退出的bar_index。

strategy.closedtrades.exit_bar_index(trade_num)


**例子**
```pine
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


### strategy.closedtrades.entry_id

返回已平仓交易的入场的id。

strategy.closedtrades.entry_id(trade_num)


**例子**
```pine
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_price

返回已平仓交易的入场价格。

strategy.closedtrades.entry_price(trade_num)


**例子**
```pine
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.entry_time

返回已平仓交易入场的UNIX时间。

strategy.closedtrades.entry_time(trade_num)


**例子**
```pine
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.closedtrades.profit

返回已平仓交易的盈亏。损失表示为负值。

strategy.closedtrades.profit(trade_num)


**例子**
```pine
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.closedtrades.size

返回已平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。 如果该值<0,则市场仓位为空头。

strategy.closedtrades.size(trade_num)


**例子**
```pine
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

Examplespine 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


More

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.