PINE LIBRARY
Cập nhật Apicode

Library "Apicode"
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float): (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float): (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float): (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float): (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float): (series int/float) The price from which to calculate the percentage.
percent (float): (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float): (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float): (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float): (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float): (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float): (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float): (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float): (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float): (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float): (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float): (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float): (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float): (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string): (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float): (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float): (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float): (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float): (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float): (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool): (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float): (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool): (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float): (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float): (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float): (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float): (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float): (series int/float) The price from which to calculate the percentage.
percent (float): (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float): (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float): (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float): (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float): (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float): (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float): (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float): (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float): (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float): (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float): (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float): (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float): (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string): (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float): (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float): (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float): (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float): (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string): (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string): (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float): (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool): (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float): (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool): (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
Phát hành các Ghi chú
v2Thư viện Pine
Theo tinh thần TradingView thực sự, tác giả đã xuất bản mã Pine này dưới dạng thư viện nguồn mở để các lập trình viên Pine khác trong cộng đồng của chúng tôi có thể sử dụng lại. Xin tri ân tác giả! Bạn có thể sử dụng thư viện này riêng tư hoặc trong các bài đăng nguồn mở khác. Tuy nhiên, bạn cần sử dụng lại mã này theo Nội quy chung.
Thông báo miễn trừ trách nhiệm
Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.
Thư viện Pine
Theo tinh thần TradingView thực sự, tác giả đã xuất bản mã Pine này dưới dạng thư viện nguồn mở để các lập trình viên Pine khác trong cộng đồng của chúng tôi có thể sử dụng lại. Xin tri ân tác giả! Bạn có thể sử dụng thư viện này riêng tư hoặc trong các bài đăng nguồn mở khác. Tuy nhiên, bạn cần sử dụng lại mã này theo Nội quy chung.
Thông báo miễn trừ trách nhiệm
Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.