The resource loading... loading...

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.avg array.variance array.min

array.mode

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

array.percentile_linear_interpolation

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

array.percentile_nearest_rank

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

array.percentrank

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

array.range

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

array.remove

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

array.reverse

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

array.from

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

  • size(series int) The initial size of the series is "0".
  • initial_value(series ) Initial value of all sequence elements↑ Optional↑ 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.from array.push array.get array.size array.remove array.shift array.sum

array.new_bool

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 na

NotesThe array index starts at 0.

See you later array.new_float array.get array.slice array.sort

array.new_float

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

NotesThe array index starts at 0.

See you later array.new_bool array.get array.slice array.sort

array.new_int

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 na

NotesThe array index starts at 0.

See you later array.new_float array.get array.slice array.sort

array.new_string

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 na

NotesThe array index starts at 0.

See you later array.new_float array.get array.slice

array.get

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

array.push

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

array.set

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

array.sum

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

array.avg

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

array.indexof

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

strategy

In thestrategyIn the related built-in functions, stop-loss number, stop-loss number is defined as the multiple of the price jump; for examplestrategy.exitof the functionprofitlossParameters with points indicate stop loss, stop leakage, parametersprofitSet to 10, i.e. price jump multiplied by 10 as the stop-gap, price jump is the built-in variablesyminfo.mintick

strategy

The function sets several policy attributes. Please note that the information is for support only.titleshorttitleoverlaypyramidingdefault_qty_typedefault_qty_valueParameters, 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(const string) The type of possible values for a formatted indicator value on the price axis is format.inherit、format.price、format.volume、default format.inherit。
  • 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.
  • scale(scale_type) The indicator should follow the price coordinates. Possible values are: scale.right, scale.left, scale.none. The value scale.none can only be used in conjunction with the overlay setting true.
  • 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(const bool) additional intrabar order computation. If the parameter is set to consttrue, the policy recalculates (not just when closing the k-line) once the line in K is filled after the order. The default is constfalse.
  • 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. The parameter does not affect the policy calculation for historical data. The default is false.
  • max_bars_back(const int) is the maximum number of bars that can be used for historical reference policies. If the script code refers to the historical data of the variable ((using the const[]' operator), this parameter will be applied to each built-in variable or user variable in the script. The size of the variable buffer in the 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.
  • 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.
  • 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/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 qty parameters are not defined, are determined by the parameters used with the default_qty_type parameters.
  • 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: 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♦
  • slippage(const int) with tick as the unit of the quote, the slippage will be added/subtracted from the transaction price of the buy/sell market order or stop loss order. If mintick = 0.01 and the slippage = 5, the total slippage will be 5 * 0.01 = 0.05.
  • 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 the account currency of each contract), strategy.commission.cash_per_order (amount shown in the account currency of each order).
  • commission_value(const int/float) Order commission value. Depending on the type chosen (commission type includes percentage or amount).
  • 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.
  • close_entries_rule(const string) Determines the order in which the order closes. 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).
  • max_lines_count(const int) Displays the number of recent line graphs. The default is 50, the maximum allowed is 500.
  • max_labels_count(const int) Displays the number of recent tabs. The default is 50, and the maximum allowed is 500.
  • max_boxes_count(const int) The number of last box drawings displayed. The default is 50, the maximum allowed is 500.
  • 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.
  • 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. It is optional.
  • 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.
  • initial_capital(const int/float) The amount of money initially available for strategic trading, expressed as a currency defined in a floating currency basket. Optional. Default is 1000000.
  • 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 indicator

strategy.entry

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 NaN
  • 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(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.
  • 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.

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.
  • 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 qty parameter. Optional. Default is 100.
  • 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.

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

strategy.exit

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 qty parameter. Optional. Default is 100.
  • 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 NaN
  • 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(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.
  • 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.

strategy.cancel

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.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.
  • 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 NaN
  • 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(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.
  • 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.

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.closedtrades.entry_bar_index strategy.closedtrades.exit_bar_index

strategy.opentrades.entry_id

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

strategy.opentrades.entry_price

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

strategy.opentrades.entry_time

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

strategy.opentrades.profit

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

strategy.opentrades.size

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

strategy.closedtrades.entry_bar_index

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

strategy.closedtrades.exit_price

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

strategy.closedtrades.exit_bar_index

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

strategy.closedtrades.entry_id

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

strategy.closedtrades.entry_price

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

strategy.closedtrades.entry_time

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

strategy.closedtrades.profit

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

strategy.closedtrades.size

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

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.