PINE LIBRARY

Strategy

Updated
█  OVERVIEW

This library is a Pine Script™ programmer’s tool containing a variety of strategy-related functions to assist in calculations like profit and loss, stop losses and limits. It also includes several useful functions one can use to convert between units in ticks, price, currency or a percentage of the position's size.



█ CONCEPTS


The library contains three types of functions:
1 — Functions beginning with `percent` take either a portion of a price, or the current position's entry price and convert it to the value outlined in the function's documentation.
  Example: Converting a percent of the current position entry price to ticks, or calculating a percent profit at a given level for the position.
2 — Functions beginning with `tick` convert a tick value to another form.
  These are useful for calculating a price or currency value from a specified number of ticks.
3 — Functions containing `Level` are used to calculate a stop or take profit level using an offset in ticks from the current entry price.
  These functions can be used to plot stop or take profit levels on the chart, or as arguments to the `limit` and `stop` parameters in strategy.exit() function calls.
  Note that these calculated levels flip automatically with the position's bias.
  For example, using `ticksToStopLevel()` will calculate a stop level under the entry price for a long position, and above the entry price for a short position.

There are also two functions to assist in calculating a position size using the entry's stop and a fixed risk expressed as a percentage of the current account's equity. By varying the position size this way, you ensure that entries with different stop levels risk the same proportion of equity.



█ NOTES


Example code using some of the library's functions is included at the end of the library. To see it in action, copy the library's code to a new script in the Pine Editor, and “Add to chart”.
For each trade, the code displays:
 • The entry level in orange.
 • The stop level in fuchsia.
 • The take profit level in green.

The stop and take profit levels automatically flip sides based on whether the current position is long or short.
Labels near the last trade's levels display the percentages used to calculate them, which can be changed in the script's inputs.
We plot markers for entries and exits because strategy code in libraries does not display the usual markers for them.

snapshot



Look first. Then leap.



█ FUNCTIONS


percentToTicks(percent) Converts a percentage of the average entry price to ticks.
  Parameters:
    percent: (series int/float) The percentage of `strategy.position_avg_price` to convert to ticks. 50 is 50% of the entry price.
  Returns: (float) A value in ticks.

percentToPrice(percent) Converts a percentage of the average entry price to a price.
  Parameters:
    percent: (series int/float) The percentage of `strategy.position_avg_price` to convert to price. 50 is 50% of the entry price.
  Returns: (float) A value in the symbol's quote currency (USD for BTCUSD).

percentToCurrency(price, percent) Converts the percentage of a price to money.
  Parameters:
    price: (series int/float) The symbol's price.
    percent: (series int/float) The percentage of `price` to calculate.
  Returns: (float) A value in the symbol's currency.

percentProfit(exitPrice) Calculates the profit (as a percentage of the position's `strategy.position_avg_price` entry price) if the trade is closed at `exitPrice`.
  Parameters:
    exitPrice: (series int/float) The potential price to close the position.
  Returns: (float) Percentage profit for the current position if closed at the `exitPrice`.

priceToTicks(price) Converts a price to ticks.
  Parameters:
    price: (series int/float) Price to convert to ticks.
  Returns: (float) A quantity of ticks.

ticksToPrice(price) Converts ticks to a price offset from the average entry price.
  Parameters:
    price: (series int/float) Ticks to convert to a price.
  Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.

ticksToCurrency(ticks) Converts ticks to money.
  Parameters:
    ticks: (series int/float) Number of ticks.
  Returns: (float) Money amount in the symbol's currency.

ticksToStopLevel(ticks) Calculates a stop loss level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `stop` parameter of a `strategy.exit()` call. NOTE: The stop level automatically flips based on whether the position is long or short.
  Parameters:
    ticks: (series int/float) The distance in ticks from the entry price to the stop loss level.
  Returns: (float) A stop loss level for the current position.

ticksToTpLevel(ticks) Calculates a take profit level using a distance in ticks from the current `strategy.position_avg_price` entry price. This value can be plotted on the chart, or used as an argument to the `limit` parameter of a `strategy.exit()` call. NOTE: The take profit level automatically flips based on whether the position is long or short.
  Parameters:
    ticks: (series int/float) The distance in ticks from the entry price to the take profit level.
  Returns: (float) A take profit level for the current position.

calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent) Calculates the position size needed to implement a given stop loss (in ticks) corresponding to `riskPercent` of equity.
  Parameters:
    stopLossTicks: (series int) The stop loss (in ticks) that will be used to protect the position.
    riskPercent: (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
  Returns: (int) A quantity of contracts.

calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice) Calculates the position size needed to implement a given stop loss (%) corresponding to `riskPercent` of equity.
  Parameters:
    stopLossPercent: (series int/float) The stop loss in percent that will be used to protect the position.
    riskPercent: (series int/float) The maximum risk level as a percent of current equity (`strategy.equity`).
    entryPrice: (series int/float) The entry price of the position.
  Returns: (int) A quantity of contracts.

exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, when, alertMessage) A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit in as a value in percent. NOTE: this function may work incorrectly with pyramiding turned on due to the use of `strategy.position_avg_price` in its calculations of stop loss and take profit offsets.
  Parameters:
    id: (series string) The order identifier of the `strategy.exit()` call.
    lossPercent: (series int/float) Stop loss as a percent of the entry price.
    profitPercent: (series int/float) Take profit as a percent of the entry price.
    qty: (series int/float) Number of contracts/shares/lots/units to exit a trade with. The default value is `na`.
    qtyPercent: (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
    comment: (series string) Optional. Additional notes on the order.
    when: (series bool) Condition of the order. The order is placed if it is true.
    alertMessage: (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
Release Notes
v2

█  NEW FUNCTIONS


An additional strategy.exit() wrapper has been added to allow for profit and loss to be expressed in ticks rather than a percentage, as is the case with its sister function from v1.

Also new with this update are functions to calculate the Sharpe and Sortino ratios. They are not exact functional equivalents to the metrics displayed in the Strategy Tester's "Performance Summary" tab because of differences in how monthly periods are calculated, but their results are pretty close.

The new functions are:

exitTicks(id, lossTicks, profitTicks, qty, qtyPercent, comment, when, alertMessage)
  A wrapper of the `strategy.exit()` built-in which adds the possibility to specify loss & profit as a value in ticks.
  Parameters:
    id: (series string) The order identifier of the `strategy.exit()` call.
    lossTicks: (series int/float) Loss in ticks.
    profitTicks: (series int/float) Profit in ticks.
    qty: (series int/float) Number of contracts/shares/lots/units to exit a trade with. Optional. The default value is `na`.
    qtyPercent: (series int/float) The percent of the position's size to exit a trade with. If `qty` is `na`, the default value of `qty_percent` is 100.
    comment: (series string) Optional. Additional notes on the order.
    when: (series bool) Condition of the order. The order is placed if it is true.
    alertMessage: (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
  Returns: (void)

sortinoRatio(interestRate, forceCalc)
  Calculates the Sortino Ratio for the trading period.
  Parameters:
    interestRate: (simple int/float) The benchmark "risk-free" rate of return to compare strategy risk against in the ratio.
    forceCalc: (series bool) When `true`, forces a recalculation on each bar. Optional. The default is `false`, whereby calculations are performed only on the last bar, for efficiency.
  Returns: (float) The Sortino Ratio. Useful for measuring the risk-adjusted return of a strategy, taking into account only drawdowns.

sharpeRatio(interestRate, forceCalc)
   Calculates the Sharpe Ratio for the trading period.
  Parameters:
    interestRate: (simple int/float) The benchmark "risk-free" rate of return to compare strategy risk against in the ratio.
    forceCalc: (series bool) When `true`, forces a recalculation on each bar. Optional. The default is `false`, whereby calculations are performed only on the last bar, for efficiency.
  Returns: (float) The Sharpe Ratio. Useful for measuring the risk-adjusted return of a strategy, taking into account both run-ups and drawdowns.



█  UPDATED FUNCTIONS


Added a new `from` parameter
A `from` parameter was added to the following three functions. If a price is supplied as an argument to the new `from` parameter when calling one of these functions, it will use that price as a reference instead of the default strategy.position_avg_price which was used in v1 of the library.

percentToTicks(percent, from)
  Converts a percentage of the supplied price or the average entry price to ticks.
  Parameters:
    percent: (series int/float) The percentage of supplied price to convert to ticks. 50 is 50% of the entry price.
    from: (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
  Returns: (float) A value in ticks.

percentToPrice(percent, from)
  Converts a percentage of the supplied price or the average entry price to a price.
  Parameters:
    percent: (series int/float) The percentage of the supplied price to convert to price. 50 is 50% of the supplied price.
    from: (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
  Returns: (float) A value in the symbol's quote currency (USD for ​BTCUSD).

ticksToPrice(ticks, from)
  Converts ticks to a price offset from the supplied price or the average entry price.
  Parameters:
    ticks: (series int/float) Ticks to convert to a price.
    from: (series int/float) A price that can be used to calculate from. Optional. The default value is `strategy.position_avg_price`.
  Returns: (float) A price level that has a distance from the entry price equal to the specified number of ticks.
Release Notes
v3


█  NEW FUNCTIONS


Two new wrappers have been added for strategy.close() and strategy.close_all(), which allow position's closing calculations to occur on the close of the last bar of the trading session, rather than the next session's first bar open. These functions use the new `immediately` parameter added to both strategy-closing function built-ins.

The new functions are:

closeAllAtEndOfSession(comment, alertMessage)
  A wrapper of the `strategy.close_all()` built-in which closes all positions on the close of the last bar of the trading session.
  Parameters:
    comment: (series string) Optional. Additional notes on the order.
    alertMessage: (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
  Returns: (void) Closes all positions on the `close` of the last bar of the trading session, instead of the `open` of the next session.

closeAtEndOfSession(entryId, comment, alertMessage)
  A wrapper of the `strategy.close()` built-in which closes the position matching the `entryId` on the close of the last bar of the trading session.
  Parameters:
    entryId: (series string) A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
    comment: (series string) Optional. Additional notes on the order.
    alertMessage: (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
  Returns: (void) Closes `entryId` on the `close` of the last bar of the trading session, instead of the `open` of the next session.
Release Notes
v4

This version's release comes with the following changes:

• The `sortinoRatio()` and `sharpeRatio()` functions have updated calculations. Previously, the functions compared strategy returns over monthly periods if the trading range was three or more months, and daily periods if the range was three or more days but less than three months. These functions now use monthly strategy returns exclusively in their ratio calculations, which helps provide a more uniform assessment of risk-adjusted performance across different trading intervals. This change keeps the library's calculations aligned with the updated Strategy Tester, which also exclusively uses monthly returns to calculate Sharpe and Sortino ratios.
• We've refined and expanded all exported function descriptions to provide more detailed information for library users.
• The `exitTicks()` function has been removed. To set an exit order based on ticks, use the `strategy.exit()` function and specify the profit and loss parameters.


strategies

Pine library

In true TradingView spirit, the author has published this Pine code as an open-source library so that other Pine programmers from our community can reuse it. Cheers to the author! You may use this library privately or in other open-source publications, but reuse of this code in a publication is governed by House rules.


Share TradingView with a friend:
tradingview.com/share-your-love/

Read more about the new tools and features we're building for you: tradingview.com/blog/en/
Also on:

Disclaimer