ceArray = array.new<float>(samplesInput) method maintainQueue(array<float> srcArray, float value, bool takeSample = true) => if takeSample srcArray.push(value) srcArray.shift() srcArray
method calcBB(array<float> srcArray, float mult, bool calculate = true) => var float mean = na var float dev = na if calculate mean := srcArray.avg() dev := srcArray.stdev() * mult [mean, mean + dev, mean - dev]
bool newSample = bar_index % n == 0
[sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample)
plot(sampleMean, “Basis”, color.orange) plot(highBand, “Upper”, color.lime) plot(lowBand, “Lower”, color.red)
可以看到使用关键字method声明的用户自定义方法:maintainQueue、calcBB的参数列表中第一个参数都是```array<float>```类型。表示该method是```array<float>```类型变量的方法,所以可以看到调用以下代码来计算布林指标。
```pine
[sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample)
Methods reloaded
User-defined methods can overlay and overwrite existing built-in methods and user-defined methods with the same identifier. This feature allows users to define multiple instances associated with different parameter signatures under the same method name. As a simple example, suppose we want to define a method to identify the type of a variable. Since we must explicitly specify the type of object associated with the user-defined method, we need to define overwrite for each type we want it to identify.
//@version=5
indicator("Type Inspection")
// @function Identifies an object's type.
// @param this Object to inspect.
// @returns (string) A string representation of the type.
method getType(int this) =>
na(this) ? "int(na)" : "int"
method getType(float this) =>
na(this) ? "float(na)" : "float"
method getType(bool this) =>
na(this) ? "bool(na)" : "bool"
method getType(color this) =>
na(this) ? "color(na)" : "color"
method getType(string this) =>
na(this) ? "string(na)" : "string"
a = 1 // a.getType(): float
b = 1.0 // b.getType(): float
c = true // c.getType(): bool
d = color.white // d.getType(): string(na)
e = "1" // e.getType(): string
runtime.log("a.getType():", a.getType())
runtime.log("b.getType():", b.getType())
runtime.log("c.getType():", c.getType())
runtime.log("d.getType():", d.getType())
runtime.log("e.getType():", e.getType())
runtime.error("stop")
The basic type of each variable is determinedgetType()
What type of overload will be used. In the FMZ platform, since the underlying implementation of the PINE script is the Javascript language, the numerical type is judged as float data.
When calling a function, parameters can be passed, parameters can be named, variables can be passed directly at the corresponding parameter location, and mixed use is also supported. For example:
plot(close, title="test plot") // 直接传参数 close ;指定参数 title ,赋值字符串"test plot"
Once the parameter name assignment is specified, the variable can no longer be passed directly as a parameter. All subsequent passwords must be written in the form of parameter name assignment.
// plot(close, title="test", color.red) // 虽然plot第三个参数是颜色值,但是这样写就会报错
plot(close, title="test", color=color.red) // 正确写法
plot(close, "test", color.red) // 正确写法
It will be forwarded totimeframe
The time period of the parameter is converted to seconds.
timeframe.in_seconds(timeframe)
Examples
// Get chart timeframe:
i_tf = input.timeframe("1D")
// Convert timeframe to the int value (number of seconds in 1 Day):
tf = timeframe.in_seconds(i_tf)
plot(tf)
Returns the value
timeframe
The int of the number of seconds in a K-line is given by the form
Parameters
timeframe
(simple string) Timeframe↑ Optional↑ The default is timeframe.period↑NotesFor thetimeframe
>=
See you later
input.timeframe
timeframe.period
Create a code identifier requesting smooth average K-line value.
ticker.heikinashi(symbol)
Examples
heikinashi_close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_aapl_60_close = request.security(ticker.heikinashi(syminfo.tickerid), "60", close)
plot(heikinashi_close)
plot(heikinashi_aapl_60_close)
Returns the value 股票代码的字符串值,可以提供给request.security函数。
Parameters
symbol
(simple string) Commodity code identifier.See you later
syminfo.tickerid
syminfo.ticker
request.security
Request external data.
request.data(url, attribute)
Examples
/*backtest
start: 2024-09-01 16:00:00
end: 2024-10-10 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
args: [["RunMode",1,358374],["ZPrecision",0,358374]]
*/
var chart_data = "https://www.datadata.com/api/v1/query/ebe46218-c5c6-4366-8c72-413694417976/data"
spotPrice = request.data(chart_data, "$.spot_close_price")
futuresPrice = request.data(chart_data, "$.future_close_price")
diff = futuresPrice - spotPrice
plot(diff, "永续-现货差价")
plot(futuresPrice, "期货价格", overlay=true)
plot(spotPrice, "现货价格", overlay=true)
if diff > 80 and strategy.position_size >= 0
runtime.log("diff > 80")
strategy.entry("Enter Short", strategy.short)
if diff < 60 and strategy.position_size <= 0
runtime.log("diff < 60")
strategy.entry("Enter Short", strategy.long)
Returns the valueParametersattribute
Specified data series.
Parameters
url
(simple string) The requested data source url, the data format of which the data source responds to, must meet the following requirements (including at least the time、data attributes):{"data": [], "schema": ["time", "data"]}
The following data formats can be used in the example:
{
"data": [
[1720051200000, "{\"spot_close_price\" : 57050.01, \"future_close_price\" : 57045.9}"],
[1720137600000, "{\"spot_close_price\" : 56628.79, \"future_close_price\" : 56604.9}"],
// ...
],
"schema": ["time", "data"]
}
attribute
(simple string) Specifies the attribute name and returns the desired data. For example:"$.spot_close_price"
, use$.
As a prefix, the attribute name matches the attribute in the data field in the data that was responded to when the requested data source was requested
Check if an error is indicatedrequest.data
Whether the time range of the request is consistent with the time range of the retest setup, data will return an error if it is not queried in the retest time sequence.
The data-data data query SQL statement in this example:
WITH latest_data AS (
SELECT
klines.spot_1d.Time AS time,
CONCAT('{\"spot_close_price\" : ', klines.spot_1d.Close, ', \"future_close_price\" : ', klines.future_1d.Close, '}') AS data
FROM
klines.spot_1d
JOIN
klines.future_1d
ON
klines.spot_1d.Time = klines.future_1d.Time
WHERE
klines.spot_1d.Symbol = 'btc_usdt'
AND
klines.future_1d.Symbol = 'btc_usdt.swap'
AND
klines.spot_1d.Exchange = 'Binance'
AND
klines.future_1d.Exchange = 'Binance'
ORDER BY
klines.spot_1d.Time DESC
LIMIT 100
)
SELECT * FROM latest_data
ORDER BY time ASC;
You can find it on the FMZ platformSearching for dataPage query, create data link, as used in the examplehttps://www.datadata.com/api/v1/query/ebe46218-c5c6-4366-8c72-413694417976/data
。
This is the first time I have seen this video.
request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency)
Examples
s = request.security(syminfo.tickerid, "D", close) // 1 Day
plot(s)
expr = ta.sma(close, 10)
s1 = request.security(syminfo.tickerid, "240", expr) // 240 Minutes
plot(s1)
// To avoid difference in calculation on history/realtime you can request not latest values and use merge strategy flags as follows:
s2 = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(s2)
f() => [open, high]
[o, h] = request.security(syminfo.tickerid, "D", f())
[l, c] = request.security(syminfo.tickerid, "D", [low, close])
plot((o + h + l + c) / 4)
Returns the valueRequired series
Parameters
symbol
(simple string) Commodity code.timeframe
(simple string) Time period. The empty string will be interpreted as the current time period of the graph.expression
(series int/float/bool/color) can be called from request.security and return an expression. It can be an array or an array containing elements that can be converted to a series.gaps
(barmerge_gaps) Policy for merging data requested ((requires data to be merged automatically with the main series of OHLC data)). Possible values: barmerge.gaps_on, barmerge.gaps_off。 barmerge.gaps_on - data requested is merged with possible gaps ((na value) ). barmerge.gaps_off - data requested is merged continuously without interruption, with all gaps filled with the previous most recent existing value。 The default is barmerge.gaps_off。lookahead
(barmerge_lookahead) gives the requested data merge policy. Possible values: barmerge.lookahead_on, barmerge.lookahead_off. Starting with version 3, the default is barmerge.lookahead_off. Note that the behavior is the same as in real time, only different in history.ignore_invalid_symbol
(const bool) An optional parameter. Determines the behavior of the function if the specified commodity is not found: if false, the script will stop and return an error at run time; if true, the function will return na and continue to execute.currency
(simple string) Converts the currency-related value (e.g. OHLC) of the commodity into the currency it is converted into. Then the conversion value is calculated based on the conversion value. The conversion rate used is based on the daily exchange rate of the previous day of the FX_IDC pair (relative to the K-line to be calculated). Optional. The default value is syminfo.currency. Possible value: a three-letter string or currency with an ISO 4217 format currency code (e.g. NotesUsing this feature, the code in PineScript can perform different calculations on historical records and real-time data.If you want to specify additional parameters for the requested commodity, such as transaction time intervals or adjustment type, you can use the following command to specify the type of transaction.您可以使用ticker.newLet's see if we can do this.
You can't pass a point error to this function using the ticker tick variable. You can use tick.ticker.newA string representation of a hash variable or stock code, such as hash AAPL+MSFT*TSLA hash.Currently, a script can have up to 40 request.security calls.
Please note that using this variable/function may result in a redrawing of the indicator.
The resolution parameter allows values of:
1S, 5S, 15S, 30S - second interval ((Chart cycle should be less than or equal to the requested cycle)
From 1 to 1440 minutes
From 1D to 365D days
From 1W to 52W in a few weeks.
From 1M to 12M in a few months
See you later
syminfo.ticker
syminfo.tickerid
timeframe.period
ta.correlation
barmerge.lookahead_off
barmerge.lookahead_on
What ifsource
String containsstr
If a string is a substring, it returns true, otherwise it returns false.
str.contains(source, str)
Examples
// If the current chart is a continuous futures chart, e.g “BTC1!”, then the function will return true, false otherwise.
var isFutures = str.contains(syminfo.tickerid, "!")
plot(isFutures ? 1 : 0)
Returns the valueWhat ifsource
Find in the string.str
, is true or false.
Parameters
source
(series string) The source stringstr
(series string) The substring to be searched.See you later
str.pos
str.match
What ifsource
String withstr
The end of the specified substring returns true or false.
str.endswith(source, str)
Returns the valueWhat ifsource
String withstr
The end of the specified substring is true or false.
Parameters
source
(series string) The source stringstr
(series string) The substring to be searched.See you later
str.startswith
What ifsource
String withstr
The start of the specified substring in the middle returns true, otherwise false.
str.startswith(source, str)
Returns the valueWhat ifsource
String withstr
The start of the substring specified in the string is true, otherwise false.
Parameters
source
(series string) The source stringstr
(series string) The substring to be searched.See you later
str.endswith
So we're going to return a new string, which issource
A substring of a string.begin_pos
Start with the character in the specified index and extend tosource
The end_pos of the string is
str.substring(source, begin_pos)
str.substring(source, begin_pos, end_pos)
Examples
sym= "EXCHANGE_NAME:SYMBOL_NAME"
pos = str.pos(sym, ":") // Get position of ":" character
tkr= str.substring(sym, pos+1) // "SYMBOL_NAME"
if barstate.islastconfirmedhistory
runtime.log(tkr)
Returns the valueA substring extracted from the source string.
Parameters
source
(series string) Extract the source string of the substring.begin_pos
(series int) is the starting position of the extracted substring. It is exclusive (the extracted substring includes characters from that position).end_pos
(series int) end position. It is exclusive (extracted string does not include characters from that position). Optional.source
String length.NotesThe string index starts at 0; ifbegin_pos
is equal toend_pos
, which returns an empty string.
See you later
str.contains
str.pos
str.match
str.tonumber(string)
Returns the valueIf it contains a valid number, it is the floating-point type of the string, otherwise it is na.
Parameters
string
(series string) int or float string representation form.Convert format strings and values to formatting strings. A format string can contain a placeholder in the text and a parenthesis {} in the parenthesis {} of each value to be formatted. Each placeholder includes an index that will replace its required parameter (starting from 0), and an optional format instruction. The index indicates the position of the parameter in the list of str.format parameters.
str.format(formatString, arg0, arg1, ...)
Examples
// The format specifier inside the curly braces accepts certain modifiers:
// - Specify the number of decimals to display:
s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3
runtime.log(s1)
// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1
runtime.log(s2)
// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34
runtime.log(s3)
// - Display a number as a percentage:
s4 = str.format("{0,number,percent}", 0.5) // returns: 50%
runtime.log(s4)
// EXAMPLES WITH SEVERAL ARGUMENTS
// returns: Number 1 is not equal to 4
s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
runtime.log(s5)
// returns: 1.34 != 1.3
s6 = str.format("{0} != {0, number, #.#}", 1.34)
runtime.log(s6)
// returns: 1 is equal to 1, but 2 is equal to 2
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52)
runtime.log(s7)
// returns: The cash turnover amounted to $1,340,000.00
s8 = str.format("The cash turnover amounted to {0, number, currency}", 1340000)
runtime.log(s8)
// returns: Expected return is 10% - 20%
s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
runtime.log(s9)
Returns the valueString formatted.
Parameters
formatString
(series string) String in the format.arg0, arg1, ...
(series int/float/bool/string/na/int[]/float[]/bool[]/string[]) is the value to be formatted.NotesAll parentheses in the unquoted style must be balanced. For example,
Returns the integer that corresponds to the number of characters in the string.
str.length(string)
Returns the valueThe number of characters in the source string.
Parameters
string
(series string) The source stringReturns a new string where all letters are converted to lower case.
str.lower(source)
Returns the valueAll the letters are converted into new lowercase strings.
Parameters
source
(series string) The string to be converted.See you later
str.upper
Returns a new string in which all letters are converted to capital letters.
str.upper(source)
Returns the valueAll the letters are converted into new strings in capital letters.
Parameters
source
(series string) The string to be converted.See you later
str.lower
If matchedregex
The normal expression returnssource
The new substring of the string, otherwise returns
str.match(source, regex)
Examples
s = input.string("It's time to sell some EXCHANGE_NAME:SYMBOL_NAME!")
// finding first substring that matches regular expression "[\w]+:[\w]+"
var string tickerid = str.match(s, "[\\w]+:[\\w]+")
if barstate.islastconfirmedhistory
runtime.log(tickerid) // "EXCHANGE_NAME:SYMBOL_NAME"
Returns the value
source
The new substring of the string, if it matches aregex
The normal expression, otherwise it is
Parameters
source
(series string) The source stringregex
(series string) The regular expression that matches this string.NotesThe function returnssource
The first regular expression in the string.regex
The inverse syllable \\ symbol in a string requires the use of additional inverse syllable translations, such as the regular expression \\d\\\.
See you later
str.contains
str.substring
Going backsource
First appearance in the stringstr
The position of the string, otherwise return
str.pos(source, str)
Returns the value
str
String is insource
Location in the string.
Parameters
source
(series string) The source stringstr
(series string) The substring to be searched.NotesThe string index starts at 0.
See you later
str.contains
str.match
str.substring
Returns a new string in which the first N+1 occurred.target
String and previouslytarget
The string is replaced withreplacement
String, where N is inoccurrence
Specifies n as the matching index of the target string to be replaced in the source string
str.replace(source, target, replacement, occurrence)
Examples
var source = "EXCHANGE1:SYMBOL1 / EXCHANGE1:SYMBOL2"
// Replace first occurrence of "EXCHANGE1" with "EXCHANGE2" replacement string
var newSource = str.replace(source, "EXCHANGE1", "EXCHANGE2", 0)
if barstate.islastconfirmedhistory
// Display "EXCHANGE2:SYMBOL1 / EXCHANGE1:SYMBOL2"
runtime.log(newSource)
Returns the valueString has been processed
Parameters
source
(series string) The source stringtarget
(series string) replaced stringreplacement
(series string) The string to be inserted instead of the target string.occurrence
(series int) The matching index of the target string to be replaced appears in the source string. The first matching index starts at 0. Optional. Default is 0.See you later
str.replace_all
str.match
Replace the target string every time it appears in the source string.
str.replace_all(source, target, replacement)
Returns the valueString has been processed
Parameters
source
(series string) The source stringtarget
(series string) replaced stringreplacement
(series string) Each time the target string appears, it replaces the stringSplits the string into a substring array and returns its array ID.
str.split(string, separator)
Returns the valueThe ID of the string array
Parameters
string
(series string) The source stringseparator
(series string) A string that separates each substring.str.tostring(value)
str.tostring(value, format)
str.tostring(value[])
str.tostring(value[], format)
Returns the value
value
String representation of the form of the parameter.
What ifvalue
If the parameter is a string, it returns as it was.
Whenvalue
For na, the function returns the string NaN.
Parameters
value
(series int/float/bool/string/int[]/float[]/bool[]/string[]) whose elements are converted to the value of the string or the array ID.format
(series string) Format string. Accepts these format.* constants: format.mintick, format.percent, format.volume. Optional. The default value is ‘#.##########’.NotesThe floating-point value format also quatrains these values when necessary, e.g. str.tostring ((3.99,
The function color specifies the transparency applied to the given color.
color.new(color, transp)
Examples
plot(close, color=color.new(color.red, 50))
Returns the valueThere is a certain transparency in the colours.
Parameters
color
(series color)transp
(series int/float) Available values range from 0 (not transparent) to 100 (not visible)NotesUsing a very large number of parameters (e.g. a simple button, input button, or series button) will affect the color displayed on the script button settings/stylesheet label page. See the user manual for more information.
Using the RGB color model to create new colors with transparency.
color.rgb(red, green, blue, transp)
Examples
plot(close, color=color.rgb(255, 0, 0, 50))
Returns the valueThere is a certain transparency in the colours.
Parameters
red
(series int/float) Tone red. Possible values are from 0 to 255.green
(series int/float) Tone green. Possible values range from 0 to 255.blue
(series int/float) Blue tone. Possible values range from 0 to 255transp
(series int/float) Optional. Colour transparent. Possible values from 0 (not transparent) to 100 (transparent). Default value is 0.NotesUsing a very large number of parameters (e.g. a simple button, input button, or series button) will affect the color displayed on the script button settings/stylesheet label page. See the user manual for more information.
Print the variable information on the controller.
The FMZ PINE language has a special function.runtime.debug(value)
, there is only one parameter.
Export the contents in the log.
The FMZ PINE language has a special function.runtime.log(1, 2, 3, close, high, ...)
, can pass multiple parameters.
When called, it can cause runtime errors and can be associated withmessage
Error message specified in the parameter.
runtime.error(message)
Parametersmessage (series string) error message.
Add input to the input label page of the script setting, which allows you to provide configuration options to the script user. This function automatically detects the type of parameters used for the undefval tab and uses the corresponding input plugin.
input(defval, title, tooltip, inline, group)
input(defval, title, inline, group, tooltip)
Examples
i_switch = input(true, "On/Off") // 设置true,默认勾选
plot(i_switch ? open : na)
i_len = input(7, "Length")
i_src = input(close, "Source") // 下拉框,默认选择close
plot(ta.sma(i_src, i_len))
i_col = input(color.red, "Plot Color")
plot(close, color=i_col)
i_text = input("Hello!", "Message")
runtime.log(i_text)
Returns the valueEnter the value of the variable
Parameters
defval
(const int/float/bool/string/color or source-type built-ins) Determines the default value of the input variable suggested in the script's float settings/input float label page, from which the script user can change it.close
、hlc3
And so on and so forth.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.NotesThe return value of the input function should always be assigned to the variable; see example above.
See you later
input.bool
input.color
input.int
input.float
input.string
input.timeframe
input.source
Adding input to the input label page of the script settings, which allows you to provide configuration options to the script user. This feature adds a drop-down menu that allows the user to select a computation source, such as close, hl2, etc. If the script contains only one input.source call, the user can also select the output of another indicator on the chart as the source.
input.source(defval, title, tooltip, inline, group)
Examples
i_src = input.source(close, "Source")
plot(i_src)
Returns the valueEnter the value of the variable
Parameters
defval
(series int/float) Determines the default value of the input variable suggested in the script's array settings/input array label page, from which the user can change it.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.Notes input.source函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.int
input.float
input.string
input.timeframe
input.color
input
Adding input to the input options tab of the script setting, which allows you to provide configuration options to the script user. This function adds a string input field to the input of the script.
input.string(defval, title, options, tooltip, inline, group, confirm)
Examples
i_text = input.string("Hello!", "Message")
runtime.log(i_text)
Returns the valueEnter the value of the variable
Parameters
defval
(const string) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the user can change it.options
When the arguments are used together, the value must be one of them.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.options
(List of constants: [tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.string函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.int
input.float
input.timeframe
input.source
input.color
input
Adding input to the Input Tag page of the script settings, which allows you to provide configuration options to the script user. This function adds a check mark to the script input.
input.bool(defval, title, tooltip, inline, group, confirm)
Examples
i_switch = input.bool(true, "On/Off")
plot(i_switch ? open : na)
Returns the valueEnter the value of the variable
Parameters
defval
(const bool) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the user can change it.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.bool函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.int
input.float
input.string
input.timeframe
input.source
input.color
input
Add input to the input label page of the script setting, which allows you to provide configuration options to the script user. This function adds an integer input field to the input of the script.
input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm)
input.int(defval, title, options, tooltip, inline, group, confirm)
Examples
i_len1 = input.int(10, "Length 1", minval=5, maxval=21, step=1)
plot(ta.sma(close, i_len1))
i_len2 = input.int(10, "Length 2", options=[5, 10, 21])
plot(ta.sma(close, i_len2))
Returns the valueEnter the value of the variable
Parameters
defval
(const int) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the script user can change it.options
When the arguments are used together, the value must be one of them.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.minval
(const int) Minimum possible value of the input variable. Optional.maxval
(const int) The maximum possible value of the input variable. Optional.step
(const int) is used to increase/decrease the input step length. Optional. Default is 1options
(tuple of const int values: [val1, val2,...]) A list of options selected from the drop-down menu, separated by commas and encapsulated in square brackets: [val1, val2,...];; cannot be used when using this parameterminval
、maxval
andstep
Parameters are.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.int函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.float
input.string
input.timeframe
input.source
input.color
input
Adding input to the input label page of the script setting, which allows you to provide configuration options to the script user. This function adds floating point input fields to the input of the script.
input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm)
input.float(defval, title, options, tooltip, inline, group, confirm)
Examples
i_angle1 = input.float(0.5, "Sin Angle", minval=-3.14, maxval=3.14, step=0.02)
plot(math.sin(i_angle1) > 0 ? close : open, "sin", color=color.green)
i_angle2 = input.float(0, "Cos Angle", options=[-3.14, -1.57, 0, 1.57, 3.14])
plot(math.cos(i_angle2) > 0 ? close : open, "cos", color=color.red)
Returns the valueEnter the value of the variable
Parameters
defval
(const int/float) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the script user can change it.options
When the arguments are used together, the value must be one of them.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.minval
(const int/float) Minimum possible value of the input variable. Optional.maxval
(const int/float) The maximum possible value of the input variable. Optional.step
(const int/float) is used to increase/decrease the input step length. Optional. Default is 1options
(tuple of const int/float values: [val1, val2,...]) A list of options selected from the drop-down menu, separated by commas and encapsulated in square brackets: [val1, val2,...];; cannot be used when using this parameterminval
、maxval
andstep
Parameters are.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.float函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.int
input.string
input.timeframe
input.source
input.color
input
Input is added to the input label page of the script settings, which allows you to provide configuration options to the script user. This function adds a color selector, allowing the user to select colors and transparency from the color palette or the hexadecimal.
input.color(defval, title, tooltip, inline, group, confirm)
Examples
i_col = input.color(color.red, "Plot Color")
plot(close, color=i_col)
Returns the valueEnter the value of the variable
Parameters
defval
(const color) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the user can change it.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.color函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.int
input.float
input.string
input.timeframe
input.source
input
Use the price input to add to the scripts of the tab setting/input tab tag page.confirm = true
Activate the interactive input mode and select the price by clicking on the chart.
input.price(defval, title, tooltip, inline, group, confirm)
Examples
price1 = input.price(title="Date", defval=42)
plot(price1)
price2 = input.price(54, title="Date")
plot(price2)
Returns the valueEnter the value of the variable
Parameters
defval
(const int/float) Determines the default value of the input variable suggested in the script's const settings/input const label page, from which the user can change it.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, enable interactive input mode and complete the selection by clicking on the chart when the indicator is added to the chart, or complete the selection by selecting the indicator and then moving the selection. Optional. Default is false.NotesWhen using the interaction mode, if two functions are called against each otherinline
The same parameters can be used to combine the time input with the price input.
See you later
input.bool
input.int
input.float
input.string
input.resolution
input.source
input.color
input
Adding input to the input label page of the script settings, which allows you to provide configuration options to the script user. This function adds a drop-down list that allows the user to select a specific time period via the time period selector and return it as a string. The selector includes custom time periods that the user may add to the drop-down menu using the time period of the chart.
input.timeframe(defval, title, options, tooltip, inline, group, confirm)
Examples
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
s = request.security(syminfo.tickerid, i_res, close)
plot(s)
Returns the valueEnter the value of the variable
Parameters
defval
(const string) Determines the default value of the input variable suggested in the script's const setting/input const label page, from which the user can change it.options
When the arguments are used together, the value must be one of them.title
(const string) Input title. If not specified, the variable name is used as the input title. If the title is specified, but the title is empty, the name is an empty string.options
(tuple of const string values: [val1, val2,...]) List of options that can be selected.tooltip
(const string) This string will be displayed to the user when the mouse hangs over the tooltip icon.inline
(const string) Combines all input calls using the same parameter in one line. It does not display the string used as the parameter. It is only used to identify inputs belonging to the same line.group
(const string) Create a header above all inputs using the same set parameter string. The string is also used as the text of the header.confirm
(const bool) If true, the user is asked to confirm the input value before adding the indicator to the chart. The default is false.Notes input.timeframe函数的结果总是应该分配给一个变量,见上面的例子。
See you later
input.bool
input.int
input.float
input.string
input.source
input.color
input
Not yet
Not yet
Arnaud Legoux Moving Average. It uses the Gaussian distribution as a weight for the moving average.
ta.alma(series, length, offset, sigma)
ta.alma(series, length, offset, sigma, floor)
Examples
plot(ta.alma(close, 9, 0.85, 6))
// same on pine, but much less efficient
pine_alma(series, windowsize, offset, sigma) =>
m = offset * (windowsize - 1)
//m = math.floor(offset * (windowsize - 1)) // Used as m when math.floor=true
s = windowsize / sigma
norm = 0.0
sum = 0.0
for i = 0 to windowsize - 1
weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2)))
norm := norm + weight
sum := sum + series[windowsize - i - 1] * weight
sum / norm
plot(pine_alma(close, 9, 0.85, 6))
Returns the valueArnaud Legoux moving average
Parameters
series
(series int/float) The series value to be executed.length
(series int) K number of lines (length).offset
(simple int/float) Controls the trade-off between smoothness (approximately 1) and responsiveness (approximately 0).sigma
(simple int/float) changes the smoothness of ALMA. The larger the Sigma, the smoother the ALMA.floor
(simple bool) Optional parameter. Specify whether the deflection is calculated as a lower bound before calculating ALMA. Default is false.See you later
ta.sma
ta.ema
ta.rma
ta.wma
ta.vwma
ta.swma
The sma function returns the moving average, the last y value of x, divided by y.
ta.sma(source, length)
Examples
plot(ta.sma(close, 15))
// same on pine, but much less efficient
pine_sma(x, y) =>
sum = 0.0
for i = 0 to y - 1
sum := sum + x[i] / y
sum
plot(pine_sma(close, 15))
Returns the value
length
The K line returnssource
The simple moving average of the mean of the mean of the mean of the mean of the mean of the mean of the mean of the mean of the mean of the mean.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).See you later
ta.ema
ta.rma
ta.wma
ta.vwma
ta.swma
ta.alma
The cog is an indicator based on statistics and the Fibonacci Golden Ratio.
ta.cog(source, length)
Examples
plot(ta.cog(close, 10))
// the same on pine
pine_cog(source, length) =>
sum = math.sum(source, length)
num = 0.0
for i = 0 to length - 1
price = source[i]
num := num + price * (i + 1)
-num / sum
plot(pine_cog(close, 10))
Returns the valueFocus
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).See you later
ta.stoch
衡量系列与其ta.sma之间的差异
ta.dev(source, length)
Examples
plot(ta.dev(close, 10))
// the same on pine
pine_dev(source, length) =>
mean = ta.sma(source, length)
sum = 0.0
for i = 0 to length - 1
val = source[i]
sum := sum + math.abs(val - mean)
dev = sum/length
plot(pine_dev(close, 10))
Returns the value
length
The K line returnssource
I'm not going to say anything.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).See you later
ta.variance
ta.stdev
ta.stdev(source, length, biased)
Examples
plot(ta.stdev(close, 5))
//the same on pine
isZero(val, eps) => math.abs(val) <= eps
SUM(fst, snd) =>
EPS = 1e-10
res = fst + snd
if isZero(res, EPS)
res := 0
else
if not isZero(res, 1e-4)
res := res
else
15
pine_stdev(src, length) =>
avg = ta.sma(src, length)
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
sum = SUM(src[i], -avg)
sumOfSquareDeviations := sumOfSquareDeviations + sum * sum
stdev = math.sqrt(sumOfSquareDeviations / length)
plot(pine_stdev(close, 5))
Returns the valueStandard deviation
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).biased
(series bool) Determines which estimate should be used. Optional. Default is true.NotesWhat ifbiased
If true, the function will calculate using biased estimates of the total, if false - biased estimates of the sample.
See you later
ta.dev
ta.variance
The ema function returns an index-weighted moving average. In ema, the weighting factor is exponentially decreasing. It is calculated using the following formula: EMA = alpha * source + (1 - alpha) * EMA,[1] where alpha = 2 / (length + 1) ;
ta.ema(source, length)
Examples
plot(ta.ema(close, 15))
//the same on pine
pine_ema(src, length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_ema(close,15))
Returns the value
source
The index of the moving average, alpha = 2 / (length + 1) ー
Parameters
source
(series int/float) The series value to be executed.length
(simple int) K number of lines (length).NotesPlease note that using this variable/function may result in a redrawing of the indicator.
See you later
ta.sma
ta.rma
ta.wma
ta.vwma
ta.swma
ta.alma
The wma function returnslength
K-linesource
In wma, the weighting factor is decreased by the arithmetic mean.
ta.wma(source, length)
Examples
plot(ta.wma(close, 15))
// same on pine, but much less efficient
pine_wma(x, y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
plot(pine_wma(close, 15))
Returns the value
length
The K line returnssource
The weighted moving average.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).See you later
ta.sma
ta.ema
ta.rma
ta.vwma
ta.swma
ta.alma
A symmetrical weighted moving average with a fixed length:4. Weight: [1/6,2 / 6,2 / 6,1 / 6].
ta.swma(source)
Examples
plot(ta.swma(close))
// same on pine, but less efficient
pine_swma(x) =>
x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
plot(pine_swma(close))
Returns the valueSymmetrical weighted moving averages.
Parameters
source
(series int/float) Source series.See you later
ta.sma
ta.ema
ta.rma
ta.wma
ta.vwma
ta.alma
The hma function returns the moving average HMA of the hull.
ta.hma(source, length)
Examples
src = input(defval=close, title="Source")
length = input(defval=9, title="Length")
hmaBuildIn = ta.hma(src, length)
plot(hmaBuildIn, title="Hull MA", color=#674EA7)
Returns the valueReturns the Hull Moving Average of the Hull length of the Hull column.
Parameters
source
(series int/float) The series value to be executed.length
(simple int) K number of linesSee you later
ta.ema
ta.rma
ta.wma
ta.vwma
ta.sma
The moving average used in the RSI. It is an index-weighted moving average, with alpha plus weight = 1/length.
ta.rma(source, length)
Examples
plot(ta.rma(close, 15))
//the same on pine
pine_rma(src, length) =>
alpha = 1/length
sum = 0.0
sum := na(sum[1]) ? ta.sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_rma(close, 15))
Returns the value
source
The index of the moving average, alpha = 1 /length
。
Parameters
source
(series int/float) The series value to be executed.length
(simple int) K number of lines (length).See you later
ta.sma
ta.ema
ta.wma
ta.vwma
ta.swma
ta.alma
ta.rsi
Relative intensity index. It is used in the lastlength
K-linesource
The upward and downward changesta.rma()
I'm not going to lie.
ta.rsi(source, length)
Examples
plot(ta.rsi(close, 7))
// same on pine, but less efficient
pine_rsi(x, y) =>
u = math.max(x - x[1], 0) // upward ta.change
d = math.max(x[1] - x, 0) // downward ta.change
rs = ta.rma(u, y) / ta.rma(d, y)
res = 100 - 100 / (1 + rs)
res
plot(pine_rsi(close, 7))
Returns the valueRelative strength and weakness (RSI)
Parameters
source
(series int/float) The series value to be executed.length
(simple int) K number of lines (length).See you later
ta.rma
The true strength and weakness index. It uses the moving average of the potential movements of financial instruments.
ta.tsi(source, short_length, long_length)
Returns the valueTrue strength and weakness index. Values in the range [-1,1].
Parameters
source
(series int/float) Source series.short_length
(simple int) Short length.long_length
(simple int) The length of the long string.The function roc ((rate of change)) showssource
The current value ofsource
A few days agolength
The difference between the values.
It is calculated by the following formula: 100 * change (src, length) / src (length).
ta.roc(source, length)
Returns the value
length
The K line returnssource
The rate of change in the number of people in the country is very high.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).Returns the difference between the minimum and maximum values in the sequence.
ta.range(source, length)
Returns the valueThe difference between the minimum and maximum values in the sequence.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).The MACD (smooth asymmetric averages) is supposed to reveal the strength, direction, momentum and duration of changes in stock price trends.
ta.macd(source, fastlen, slowlen, siglen)
Examples
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
plot(macdLine, color=color.blue)
plot(signalLine, color=color.orange)
plot(histLine, color=color.red, style=plot.style_histogram)
If you only need one value, use a placeholder symbol like this:
Examples
[_, signalLine, _] = ta.macd(close, 12, 26, 9)
plot(signalLine, color=color.orange)
Returns the valueThe three components of the MACD series are: MACD line, signal line, and rectangular line.
Parameters
source
(series int/float) The series value to be executed.fastlen
(simple int) The shortcut parameterslowlen
(simple int) Slow length parameter.siglen
(simple int) Signal length parameterSee you later
ta.sma
ta.ema
Returns the pattern of the sequence. Returns the minimum value if there are multiple values of the same frequency.
ta.mode(source, length)
Returns the valueThe pattern of the sequence.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).Returns the median of the sequence.
ta.median(source, length)
Returns the valueThe median of the sequence.
Parameters
source
(series int/float) The series value to be executed.length
(series int) K number of lines (length).A linear regression curve ─ a line that most closely matches the specified price within a user-defined time interval ─ is calculated using the least binary multiplication ─ the result of this function is calculated using the following formula: linreg = intercept + slope * (length - 1 - offset), where intercept and slope are used.source
The value of the smallest binary multiplication of the series.
ta.linreg(source, length, offset)
Returns the valueLinear regression curve
Parameters
source
(series int/float) Source series.length
(series int)offset
(simple int) shiftBrainstorming is a technical analysis tool defined by a set of lines that are spaced along two standard deviations (positive and negative) from the simple moving average (SMA) of a security's price, but can be adjusted according to user preference.
ta.bb(series, length, mult)
Examples
[middle, upper, lower] = ta.bb(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
// the same on pine
f_bb(src, length, mult) =>
float basis = ta.sma(src, length)
float dev = mult * ta.stdev(src, length)
[basis, basis + dev, basis - dev]
[pineMiddle, pineUpper, pineLower] = f_bb(close, 5, 4)
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
Returns the valueI'm not sure what to do.
Parameters
series
(series int/float) Sequence to runwuhuoyanHow 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.