Risk ManagementLibrary "RiskManagement"
This library keeps your money in check, and is used for testing and later on webhook-applications too. It has four volatility functions and two of them can be used to calculate a Stop-Loss, like Average True Range. It also can calculate Position Size, and the Risk Reward Ratio. But those calculations don't take leverage into account.
position_size(portfolio, risk, entry, stop_loss, use_leverage, qty_as_integer)
This function calculates the definite amount of contracts/shares/units you should use to buy or sell. This value can used by `strategy.entry(qty)` for example.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. Possible values are between 0.1 and 100%. Same usecase with strategy(default_qty_type=strategy.percent_of_equity,default_qty_value=100), except its calculation the risk only.
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
use_leverage (bool) : This value is optional. When not used or when set to false then this function will let you invest your portfolio at max.
qty_as_integer (bool) : This value is optional. When set to true this function will return a value used with integers. The largest integer less than or equal to the given number. Because some Broker/Exchanges let you trade hole contracts/shares/units only.
Returns: float
position_size_currency(portfolio, risk, entry, stop_loss)
This function calculates the definite amount of currency you should use when going long or short.
Parameters:
portfolio (float) : This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
risk (float) : This is the percentage of your Portfolio you willing to loose on a single trade. For example: 1 is 100% and 0,01 is 1%. Default amount is 0.02 (2%).
entry (float) : This is the limit-/market-price for the current investment. In other words: The price per contract/share/units you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
Returns: float
rrr(entry, stop_loss, take_profit)
This function calculates the Risk Reward Ratio. Common values are between 1.5 and 2.0 and you should not go lower except for very few special cases.
Parameters:
entry (float) : This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
stop_loss (float) : This is the limit-/market-price when to exit the trade, to minimize your losses.
take_profit (float) : This is the limit-/market-price when to take profits.
Returns: float
change_in_price(length)
This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
maximum_price_fluctuation(length)
This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
absolute_price_changes(length)
This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
annualized_volatility(length)
This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
Parameters:
length (int) : The length is needed to determine how many candles/bars back should take into account.
Returns: float
Strategies
LYGLibraryLibrary "LYGLibrary"
A collection of custom tools & utility functions commonly used with my scripts
getDecimals()
Calculates how many decimals are on the quote price of the current market
Returns: The current decimal places on the market quote price
truncate(number, decimalPlaces)
Truncates (cuts) excess decimal places
Parameters:
number (float)
decimalPlaces (simple float)
Returns: The given number truncated to the given decimalPlaces
toWhole(number)
Converts pips into whole numbers
Parameters:
number (float)
Returns: The converted number
toPips(number)
Converts whole numbers back into pips
Parameters:
number (float)
Returns: The converted number
getPctChange(value1, value2, lookback)
Gets the percentage change between 2 float values over a given lookback period
Parameters:
value1 (float)
value2 (float)
lookback (int)
av_getPositionSize(balance, risk, stopPoints, conversionRate)
Calculates OANDA forex position size for AutoView based on the given parameters
Parameters:
balance (float)
risk (float)
stopPoints (float)
conversionRate (float)
Returns: The calculated position size (in units - only compatible with OANDA)
bullFib(priceLow, priceHigh, fibRatio)
Calculates a bullish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
bearFib(priceLow, priceHigh, fibRatio)
Calculates a bearish fibonacci value
Parameters:
priceLow (float) : The lowest price point
priceHigh (float) : The highest price point
fibRatio (float) : The fibonacci % ratio to calculate
Returns: The fibonacci value of the given ratio between the two price points
getMA(length, maType)
Gets a Moving Average based on type (MUST BE CALLED ON EVERY CALCULATION)
Parameters:
length (simple int)
maType (string)
Returns: A moving average with the given parameters
getEAP(atr)
Performs EAP stop loss size calculation (eg. ATR >= 20.0 and ATR < 30, returns 20)
Parameters:
atr (float)
Returns: The EAP SL converted ATR size
getEAP2(atr)
Performs secondary EAP stop loss size calculation (eg. ATR < 40, add 5 pips, ATR between 40-50, add 10 pips etc)
Parameters:
atr (float)
Returns: The EAP SL converted ATR size
barsAboveMA(lookback, ma)
Counts how many candles are above the MA
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are above the MA
barsBelowMA(lookback, ma)
Counts how many candles are below the MA
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many recent bars are below the EMA
barsCrossedMA(lookback, ma)
Counts how many times the EMA was crossed recently
Parameters:
lookback (int)
ma (float)
Returns: The bar count of how many times price recently crossed the EMA
getPullbackBarCount(lookback, direction)
Counts how many green & red bars have printed recently (ie. pullback count)
Parameters:
lookback (int)
direction (int)
Returns: The bar count of how many candles have retraced over the given lookback & direction
getBodySize()
Gets the current candle's body size (in POINTS, divide by 10 to get pips)
Returns: The current candle's body size in POINTS
getTopWickSize()
Gets the current candle's top wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's top wick size in POINTS
getBottomWickSize()
Gets the current candle's bottom wick size (in POINTS, divide by 10 to get pips)
Returns: The current candle's bottom wick size in POINTS
getBodyPercent()
Gets the current candle's body size as a percentage of its entire size including its wicks
Returns: The current candle's body size percentage
isHammer(fib, colorMatch)
Checks if the current bar is a hammer candle based on the given parameters
Parameters:
fib (float)
colorMatch (bool)
Returns: A boolean - true if the current bar matches the requirements of a hammer candle
isStar(fib, colorMatch)
Checks if the current bar is a shooting star candle based on the given parameters
Parameters:
fib (float)
colorMatch (bool)
Returns: A boolean - true if the current bar matches the requirements of a shooting star candle
isDoji(wickSize, bodySize)
Checks if the current bar is a doji candle based on the given parameters
Parameters:
wickSize (float)
bodySize (float)
Returns: A boolean - true if the current bar matches the requirements of a doji candle
isBullishEC(allowance, rejectionWickSize, engulfWick)
Checks if the current bar is a bullish engulfing candle
Parameters:
allowance (float)
rejectionWickSize (float)
engulfWick (bool)
Returns: A boolean - true if the current bar matches the requirements of a bullish engulfing candle
isBearishEC(allowance, rejectionWickSize, engulfWick)
Checks if the current bar is a bearish engulfing candle
Parameters:
allowance (float)
rejectionWickSize (float)
engulfWick (bool)
Returns: A boolean - true if the current bar matches the requirements of a bearish engulfing candle
isInsideBar()
Detects inside bars
Returns: Returns true if the current bar is an inside bar
isOutsideBar()
Detects outside bars
Returns: Returns true if the current bar is an outside bar
barInSession(sess, useFilter)
Determines if the current price bar falls inside the specified session
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls within the given time session
barOutSession(sess, useFilter)
Determines if the current price bar falls outside the specified session
Parameters:
sess (simple string)
useFilter (bool)
Returns: A boolean - true if the current bar falls outside the given time session
dateFilter(startTime, endTime)
Determines if this bar's time falls within date filter range
Parameters:
startTime (int)
endTime (int)
Returns: A boolean - true if the current bar falls within the given dates
dayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
Checks if the current bar's day is in the list of given days to analyze
Parameters:
monday (bool)
tuesday (bool)
wednesday (bool)
thursday (bool)
friday (bool)
saturday (bool)
sunday (bool)
Returns: A boolean - true if the current bar's day is one of the given days
atrFilter(atrValue, maxSize)
Parameters:
atrValue (float)
maxSize (float)
fillCell(tableID, column, row, title, value, bgcolor, txtcolor)
This updates the given table's cell with the given values
Parameters:
tableID (table)
column (int)
row (int)
title (string)
value (string)
bgcolor (color)
txtcolor (color)
Returns: A boolean - true if the current bar falls within the given dates
Mizar_LibraryThe "Mizar_Library" is a powerful tool designed for Pine Script™ programmer’s, providing a collection of general functions that facilitate the usage of Mizar’s DCA (Dollar-Cost-Averaging) bot system.
To begin using the Mizar Library, you first need to import it into your indicator script. Insert the following line below your indicator initiation line: import Mizar_Trading/Mizar_Library/1 as mizar (mizar is the chosen alias).
In the import statement, Mizar_Trading.Mizar_Library_v1 refers to the specific version of the Mizar Library you wish to use. Feel free to modify mizar to your preferred alias name.
Once the library is imported, you can leverage its functions by prefixing them with mizar. . This will prompt auto-completion suggestions displaying all the available user-defined functions provided by the Mizar Library.
Now, let's delve into some of the key functions available in the Mizar Library:
DCA_bot_msg(_cmd)
The DCA_bot_msg function accepts an user-defined type (UDT) _cmd as a parameter and returns a string with the complete JSON command for a Mizar DCA bot.
Parameters:
_cmd (bot_params) : ::: User-defined type (UDT) that holds all the necessary information for the bot command.
Returns: A string with the complete JSON command for a Mizar DCA bot.
rounding_to_ticks(value, ticks, rounding_type)
The rounding_to_ticks function rounds a calculated price to the nearest actual price based on the specified tick size.
Parameters:
value (float) : ::: The calculated price as float type, to be rounded to the nearest real price.
ticks (float) : ::: The smallest possible price obtained through a request in your script.
rounding_type (int) : ::: The rounding type for the price: 0 = closest real price, 1 = closest real price above, 2 = closest real price below.
Returns: A float value representing the rounded price to the next tick.
bot_params
Bot_params is an user-defined type (UDT) that represents the parameters required for a Mizar DCA bot.
Fields:
bot_id (series string) : The ID number of your Mizar DCA bot.
api_key (series string) : Your private API key from your Mizar account (keep it confidential!).
action (series string) : The command to perform: "open" (standard) or "close" optional .
tp_perc (series string) : The take profit percentage in decimal form (1% = "0.01") optional .
base_asset (series string) : The cryptocurrency you want to buy (e.g., "BTC").
quote_asset (series string) : The coin or fiat currency used for payment (e.g., "USDT" is standard if not specified) optional .
direction (series string) : The direction of the position: "long" or "short" (only applicable for two-way hedge bots) optional .
To obtain the JSON command string for the alert_function call, you can use the DCA_bot_msg function provided by the library. Simply pass the cmd_msg UDT as an argument and assign the returned string value to a variable.
Here's an example to illustrate the process:
// Import of the Mizar Library to use the included functions
import/Mizar_Trading/Mizar_Library/1 as mizar
// Example to set a variable called “cmd_msg” and all of its parameters
cmd_msg = mizar.bot_params. new()
cmd_msg.action := "open"
cmd_msg.api_key := "top secret"
cmd_msg.bot_id := "9999"
cmd_msg.base_asset := "BTC"
cmd_msg.quote_asset := "USDT"
cmd_msg.direction := "long"
cmd_msg.tp_perc := "0.015"
// Calling the Mizar conversion function named “DCA_bot_msg()” with the cmd_msg as argument to receive the JSON command and save it in a string variable called “alert_msg”
alert_msg = mizar.DCA_bot_msg(cmd_msg)
Feel free to utilize (series) string variables instead of constant strings. By incorporating the Mizar Library into your Pine Script, you gain access to a powerful set of functions and can leverage them according to your specific requirements.
For additional help or support, you can join the Mizar Discord channel. There, you'll find a dedicated Pine Script channel where you can ask any questions related to Pine Script.
GeneratorBetaLib:Generator
This library generate levels that could be used inside SNG scripts and strategies. Also uses beta version of SNG Types library
biased_price_targetLibrary "biased_price_target"
Collection of functions that can be used for the calculation of biased price targets like stop loss and
take profit from a reference price using several methods that are already provided by the "distance_ratio" library plus
the 'HHLL'. Methods supported are percentagewise (PERC), atr-based (ATR), fixed profit (PROF), tick-based (TICKS),
risk reward ratio (RR), and highest high/lowest low (HHLL)
Strategy UtilitiesThis library comprises valuable functions for implementing strategies on TradingView, articulated in a professional writing style.
The initial version features a monthly Profit & Loss table with percentage variations, utilizing a modified version of the script by @QuantNomad.
Library "strategy_utilities"
monthly_table(results_prec, results_dark)
monthly_table prints the Monthly Returns table, modified from QuantNomad. Please put calc_on_every_tick = true to plot it.
Parameters:
results_prec (int) : for the precision for decimals
results_dark (bool) : true or false to print the table in dark mode
Returns: nothing (void), but prints the monthly equity table
Sample Usage
import TheSocialCryptoClub/strategy_utilities/1 as su
results_prec = input(2, title = "Precision", group="Results Table")
results_dark = input.bool(defval=true, title="Dark Mode", group="Results Table")
su.monthly_table(results_prec, results_dark)
SAT_BACKTEST @description TODO: Regroupement of useful functionsLibrary "SAT_BACKTEST"
ex_timezone(tz)
switch case return exact @timezone for timezone input
Parameters:
tz (simple string)
Returns: syminfo.timezone or tz
if_in_date_range(usefromDate, fromDate, usetoDate, toDate, src_timezone, dst_timezone)
if_in_date_range : check if @time_close is range
Parameters:
usefromDate (simple bool)
fromDate (simple int)
usetoDate (simple bool)
toDate (simple int)
src_timezone (simple string)
dst_timezone (simple string)
Returns: true if @time_close is range
if_in_session(useSessionStart, sessionStartHour, sessionStartMinute, useSessionEnd, sessionEndHour, sessionEndMinute, useSessionDay, mon, tue, wed, thu, fri, sat, sun, src_timezone, dst_timezone)
if_in_session : check if @time_close is range
Parameters:
useSessionStart (simple bool)
sessionStartHour (simple int)
sessionStartMinute (simple int)
useSessionEnd (simple bool)
sessionEndHour (simple int)
sessionEndMinute (simple int)
useSessionDay (simple bool)
mon (simple bool)
tue (simple bool)
wed (simple bool)
thu (simple bool)
fri (simple bool)
sat (simple bool)
sun (simple bool)
src_timezone (simple string)
dst_timezone (simple string)
Returns: true if @time_close is range
OrderLibLibrary "OrderLib"
TODO: add library description here
removeOrderView(view)
Parameters:
view (orderView)
createOrderView(model, length, profit_color, loss_color, enter_color)
Parameters:
model (orderModel)
length (simple int)
profit_color (simple color)
loss_color (simple color)
enter_color (simple color)
createOrder(enter, tp, sl)
Parameters:
enter (float)
tp (float)
sl (float)
createOrderByRR(enter, sl, rr)
Parameters:
enter (float)
sl (float)
rr (float)
createOrderByRR(enter, sl, rr, commision_percent)
Parameters:
enter (float)
sl (float)
rr (simple float)
commision_percent (simple float)
orderModel
Fields:
enter (series__float)
sl (series__float)
tp (series__float)
orderView
Fields:
enter (series__line)
sl (series__line)
tp (series__line)
LibreLibrary "Libre"
TODO: add library description here
MMMM(toe)
Parameters:
toe (string)
OOOO(toe, toe1, toe2, toe3, toe4, toe5, init)
Parameters:
toe (string)
toe1 (string)
toe2 (string)
toe3 (string)
toe4 (string)
toe5 (string)
init (int)
XXXX(toe)
Parameters:
toe (string)
WWWW(toe)
Parameters:
toe (string)
Scaled Order Sizing and Take Profit Target ArraysWOAH Order Scaling!
This Provides a user with methods to create a list of profit targets and order sizes which grow or shrink. For size, the will add up to specific sum. for Targets they will include the first and last, and can lean towards either, to scale the order grid.
And thanks to @Hoanghetti for the markdown, i've included a basic usage example within the hover , o you don't need to search for the usage example, simply import, and when writing, the code hint contains a full example.
scaled_sizes(total_size, count, weight, min_size, as_percent)
create an array of sizes which grow or shrink from first to last
which add up to 1.0 if set the as_percent flag , or a total value / sum.
Parameters:
total_size : (float) total size to divide ito split
count : (int ) desired number of splits to create
weight : (float) a weight to apply to grow or shrink the split either towards the last being most, or the first being most, or 1.0 being each is equally sized as 1/n count
min_size : (float) a minimum size for the smallest value (in value of ttotal_size units)
as_percent : (float) a minimum size for the smallest value (in value of total_size units)
Returns: Array of Sizes for each split
scaled_targets(count, weight, minimum, maximum)
create a list of take profitt targets from the smallest to larget distance
Parameters:
count : (int ) number of targets
weight : (float) weight to apply to growing or shrinking
minimum : (float) first value of the output
maximum : (float) last value of the output
Returns: Array of percentage targets
libKageMiscLibrary "libKageMisc"
Kage's Miscelaneous library
print(_value)
Print a numerical value in a label at last historical bar.
Parameters:
_value : (float) The value to be printed.
Returns: Nothing.
barsBackToDate(_year, _month, _day)
Get the number of bars we have to go back to get data from a specific date.
Parameters:
_year : (int) Year of the specific date.
_month : (int) Month of the specific date. Optional. Default = 1.
_day : (int) Day of the specific date. Optional. Default = 1.
Returns: (int) Number of bars to go back until reach the specific date.
bodySize(_index)
Calculates the size of the bar's body.
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.
Returns: (float) The size of the bar's body in price units.
shadowSize(_direction)
Size of the current bar shadow. Either "top" or "bottom".
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) The size of the chosen bar's shadow in price units.
shadowBodyRatio(_direction)
Proportion of current bar shadow to the bar size
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) Ratio of the shadow size per body size.
bodyCloseRatio(_index)
Proportion of chosen bar body size to the close price
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.()
Returns: (float) Ratio of the body size per close price.
lastDayOfMonth(_month)
Returns the last day of a month.
Parameters:
_month : (int) Month number.
Returns: (int) The number (28, 30 or 31) of the last day of a given month.
nameOfMonth(_month)
Return the short name of a month.
Parameters:
_month : (int) Month number.
Returns: (string) The short name ("Jan", "Feb"...) of a given month.
pl(_initialValue, _finalValue)
Calculate Profit/Loss between two values.
Parameters:
_initialValue : (float) Initial value.
_finalValue : (float) Final value = Initial value + delta.
Returns: (float) Profit/Loss as a percentual change.
gma(_Type, _Source, _Length)
Generalist Moving Average (GMA).
Parameters:
_Type : (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA".
_Source : (series float) Series of values to process.
_Length : (simple int) Number of bars (length).
Returns: (float) The value of the chosen moving average.
xFormat(_percentValue, _minXFactor)
Transform a percentual value in a X Factor value.
Parameters:
_percentValue : (float) Percentual value to be transformed.
_minXFactor : (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10.
Returns: (string) A formated string.
isLong()
Check if the open trade direction is long.
Returns: (bool) True if the open position is long.
isShort()
Check if the open trade direction is short.
Returns: (bool) True if the open position is short.
lastPrice()
Returns the entry price of the last openned trade.
Returns: (float) The last entry price.
barsSinceLastEntry()
Returns the number of bars since last trade was oppened.
Returns: (series int)
getBotNameFrosty()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getBotNameZig()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getTicksValue(_currencyValue)
Converts currency value to ticks
Parameters:
_currencyValue : (float) Value to be converted.
Returns: (float) Value converted to minticks.
getSymbol(_botName, _botCustomSymbol)
Formats the symbol string to be used with a bot
Parameters:
_botName : (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string.
_botCustomSymbol : (string) Custom string. Optional. Default is empy string.
Returns: (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format.
showProfitLossBoard()
Calculates and shows a board of Profit/Loss through the years.
Returns: Nothing.
libKageBotLibrary "libKageBot"
Library of function to generate command strings for bots FrostyBot and Zignally. This version ONLY WORKS WITH FROSTYBOT.
strSize(_sizePercent, _sizeCurrency)
Converts a float to a formated string suitable to position size in percentage or currency. At leaste one parameter must be given
Parameters:
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A formated string containing the position size
entry(_bot, _direction, _sizePercent, _sizeCurrency)
Generates a simple entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_direction : (string) Flag to opena long or a short position. Must be either DIRECTION_LONG or DIRECTION_SHORT constant
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a simple open position command
exit(_bot, _sizePercent, _sizeCurrency, _reduce)
Generates a simple exit command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
_reduce : (bool) Flag to use Ruce Only option on Binance positions. Optional. Default = true
Returns: (string) A string of a simple close position command
cancelAll(_bot)
Generates a command string for a bot that cancels all open orders
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
Returns: (string) A string of a command to cancel all open orders
leverage(_bot, _leverage, _type)
Generates a command string for a bot to set leverage
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_type : (string) Type of leverage. Must be either LEVERAGE_CROSS or LEVERAGE_ISOLATED. Optional. Default is LEVERAGE_CROSS.
Returns: (string) A string of a simple leverage command
entryLong(_bot, _leverage, _leverageType, _sizePercent, _sizeCurrency)
Generates a complete long entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_leverageType : (string) Type of leverage. Must be either LEVERAGE_CROSS or LEVERAGE_ISOLATED. Optional. Default is LEVERAGE_CROSS.
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a complete open long position command
entryShort(_bot, _leverage, _leverageType, _sizePercent, _sizeCurrency)
Generates a complete short entry command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_leverage : (int) The amount of leverage to be used when opening a position. Optional. If does not given, the bot's default will be used
_leverageType
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
Returns: (string) A string of a complete open short position command
exitPosition(_bot, _sizePercent, _sizeCurrency, _reduce)
Generates a complete close position command string for a bot
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_sizePercent : (float) Position size in percent value. Optional. Default = na. Mandatory if _sizeCurrency is not given.
_sizeCurrency : (float) Position size in currency value. Optional. Default = na. Mandatory if _sizePercent is not given.
_reduce : (bool) Flag to use Ruce Only option on Binance positions. Optional. Default = true
Returns: (string) A string of a comlete close position command
printBot(_bot, _command)
Print bot's information for debug purposes
Parameters:
_bot : (TradeBot) Previously instancied bot type variable
_command : (string) A command string to be debugged
Returns: Nothing.
Constants
Constants to be used in both in internal and external code
Fields:
SERVER_FROSTBOT : (string) Identifier to FrostyBot
SERVER_ZIGNALY : (string) Identifier to Zignaly
DIRECTION_LONG : (string) Flag to open a long position
DIRECTION_SHORT
LEVERAGE_CROSS : (string) Flag to set leverage to cross
LEVERAGE_ISOLATED : (string) Flag to set leverage to isolated
TradeBot
Bot type to handle its essential information
Fields:
server : (string) Type o server. Must me one of the SERVER_* constant values
id : (string) Id of the account in the server (Stub for FrostyBot or Key to Zignally)
symbol : (string) Symbol of the pair to be negotiated (example: ETH/USDT)
leverage : (int) Leverage coeficient. Default is 1
PositionLibrary "Position"
Allows for simulating trades within an indicator.
newTrade(size, price, timestamp)
Creates a new trade object.
Parameters:
size : The size of the trade (number of shares or contracts).
price : The price at which the trade took place.
timestamp : The timestamp of the trade. Defaults to the current time.
Returns: A new trade object.
start(size, price, timestamp)
Starts a new position.
Parameters:
size : The size of the position (number of shares or contracts).
price : The price at which the position was started.
timestamp : The timestamp of the start of the position. Defaults to the current time.
Returns: A new position object.
trade(pos, size, price, timestamp)
Modifies an existing position.
Parameters:
pos : The position to be modified.
size : The size of the trade (number of shares or contracts).
price : The price at which the trade took place.
timestamp : The timestamp of the trade. Defaults to the current time.
Returns: The modified position object.
exit(pos, price, timestamp)
Closes a position by trading the entire position size at a given price and timestamp.
Parameters:
pos : The position being closed.
price : The price at which the position is being closed.
timestamp : The timestamp of the trade, defaults to the current time.
Returns: The updated position after the trade.
unrealized(pos, price)
Calculates the unrealized gain or loss for a given position and price.
Parameters:
pos : The position for which to calculate unrealized gain/loss.
price : The current market price.
Returns: The calculated unrealized gain or loss.
Trade
Represents a single trade.
Fields:
size : Size of the trade in units.
price : Price of the trade in currency.
value : Total value of the trade in currency units.
time : Timestamp of the trade.
Position
Represents a single position.
Fields:
size : Size of the position in units.
price : Average price of the position in currency.
value : Total value of the position in currency units.
start : Timestamp of the first trade that opened the position.
net : Realized gains and losses of the position in currency units.
history : Array of trades that make up the position.
HiveLibraryLibrary "HiveLibrary"
: Custom library
RoundDown(number, decimals)
RoundDown() rounds the specified number down to the given number
of decimal places.
Parameters:
number : is the argument for rounding down & decimals is the number of digits after dot
decimals
Returns: return is the rounded down value of the number
Replica of TradingView's Backtesting Engine with ArraysHello everyone,
Here is a perfectly replicated TradingView backtesting engine condensed into a single library function calculated with arrays. It includes TradingView's calculations for Net profit, Total Trades, Percent of Trades Profitable, Profit Factor, Max Drawdown (absolute and percent), and Average Trade (absolute and percent). Here's how TradingView defines each aspect of its backtesting system:
Net Profit: The overall profit or loss achieved.
Total Trades: The total number of closed trades, winning and losing.
Percent Profitable: The percentage of winning trades, the number of winning trades divided by the total number of closed trades.
Profit Factor: The amount of money the strategy made for every unit of money it lost, gross profits divided by gross losses.
Max Drawdown: The greatest loss drawdown, i.e., the greatest possible loss the strategy had compared to its highest profits.
Average Trade: The sum of money gained or lost by the average trade, Net Profit divided by the overall number of closed trades.
Here's how each variable is defined in the library function:
_backtest(bool _enter, bool _exit, float _startQty, float _tradeQty)
bool _enter: When the strategy should enter a trade (entry condition)
bool _exit: When the strategy should exit a trade (exit condition)
float _startQty: The starting capital in the account (for BTCUSD, it is the amount of USD the account starts with)
float _tradeQty: The amount of capital traded (if set to 1000 on BTCUSD, it will trade 1000 USD on each trade)
Currently, this library only works with long strategies, and I've included a commented out section under DEMO STRATEGY where you can replicate my results with TradingView's backtesting engine. There's tons I could do with this beyond what is shown, but this was a project I worked on back in June of 2022 before getting burned out. Feel free to comment with any suggestions or bugs, and I'll try to add or fix them all soon. Here's my list of thing to add to the library currently (may not all be added):
Add commission calculations.
Add support for shorting
Add a graph that resembles TradingView's overview graph.
Clean and optimize code.
Clean up in a way that makes it easy to add other TradingView calculations (such as Sharpe and Sortino ratio).
Separate all variables, so they become accessible outside of calculations (such as gross profit, gross loss, number of winning trades, number of losing trades, etc.).
Thanks for reading,
OztheWoz
Profit EstimateLibrary "profitestimate"
Simple profit Estimatr. Engages when Position != 0
and holds until posittion is na/0...
if position changes sizes, it will update automatically and adjust.
it has an input for comission to estmate exit fees
update_avgprice(_sizewas, _delta, _pricewas, _newprice)
Get a new Average position Price
Parameters:
_sizewas : (float) the position prior
_delta : (float) the order amount
_pricewas : (float) the prior price
_newprice : (float) the price of order
Returns: New Avg Price
amount(_position, _close, _commission, _leverage, _fullqty)
Position Net Profit Net Commission, automatic on/off if position != 0
Parameters:
_position : (float) position size (total or margin size)
_close
_commission : (float) % where (0.1 = 0.1%)
_leverage : (float) optional if leveraged, default 1x
_fullqty : (bool) if position entered is tottal trade size default is margin qty (1/lev)
Returns: quote value of profit
percent(_position, _close, _commission, _leverage, _fullqty)
Position Net Profit, automatic on/off if position != 0
Parameters:
_position : (float) position size (total or margin size)
_close
_commission : (float) % where (0.1 = 0.1%)
_leverage : (float) optional if leveraged, default 1x
_fullqty : (bool) if position entered is tottal trade size, default is margin qty (1/lev)
Returns: percentage profit (1% = 1)
PlurexSignalStrategyLibrary "PlurexSignalStrategy"
Provides functions that wrap the built in TradingView strategy functions so you can seemlessly integrate with Plurex Signal automation.
NOTE: Be sure to:
- set your strategy default_qty_value to the default entry percentage of your signal
- set your strategy default_qty_type to strategy.percent_of_equity
- set your strategy pyramiding to some value greater than 1 or something appropriate to your strategy in order to have multiple entries.
long(secret, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
longAndFixedStopLoss(secret, stop, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
Parameters:
secret : The secret for your Signal on plurex
stop : The trigger price for the stop loss. See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
longAndTrailingStopLoss(secret, trail_offset, trail_price, trail_points, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
Parameters:
secret : The secret for your Signal on plurex
trail_offset : See strategy.exit documentation
trail_price : See strategy.exit documentation
trail_points : See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
short(secret, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
shortAndFixedStopLoss(secret, stop, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
Parameters:
secret : The secret for your Signal on plurex
stop : The trigger price for the stop loss. See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
shortAndTrailingStopLoss(secret, trail_offset, trail_price, trail_points, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
Parameters:
secret : The secret for your Signal on plurex
trail_offset : See strategy.exit documentation
trail_price : See strategy.exit documentation
trail_points : See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeAll(secret, marketOverride)
Close all positions. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLongs(secret, marketOverride)
close all longs. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeShorts(secret, marketOverride)
close all shorts. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastLong(secret, marketOverride)
Close last long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastShort(secret, marketOverride)
Close last short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstLong(secret, marketOverride)
Close first long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstShort(secret, marketOverride)
Close first short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
strategyLibrary "strategy"
Library containing few key calculations for strategy involving leveraged limit and stop orders
getQty(entry, stop, riskPercentage)
calculate qty and leverage based on entry and stop price for given risk percentage.
Parameters:
entry : Entry Price
stop : Stop Price
riskPercentage : risk percentage per trade
Returns: - Quantity based on the risk and calculated leverage on position including existing positions
bracketOrder(entry, stop, target, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates bracket orders for given entry/stop/target
Parameters:
entry : Entry Price
stop : Stop Price
target : Target Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
order(entry, stop, maxLeverage, isLimitOrder, riskPercentage)
Calculates position size based on risk and creates order for given entry/stop
Parameters:
entry : Entry Price
stop : Stop Price
maxLeverage : Maximum leverage allowed
isLimitOrder : if true, places limit order for entry, else places stop order.
riskPercentage : risk percentage per trade
Returns: orderPlaced - true if orders successfully placed, false otherwise.
TradingWolfLibaryLibrary "TradingWolfLibary"
getMA(int, string)
Gets a Moving Average based on type
Parameters:
int : length The MA period
string : maType The type of MA
Returns: A moving average with the given parameters
minStop(float, simple, float, string)
Calculates and returns Minimum stop loss
Parameters:
float : entry price (Close if calculating on the entry candle)
simple : int Calculate how many bars back to look at swings
float : Minimum Stop Loss allowed (Should be x 0.01) if input
string : Direciton of trade either "Long" or "Short"
Returns: Stop Loss Value
Strategy PnL LibraryLibrary "Strategy_PnL_Library"
TODO: This is a library that helps you learn current pnl of open position and use it to create your own dynamic take profit or stop loss rules based on current level of your profit. It should only be used with strategies.
inTrade()
inTrade: Checks if a position is currently open.
Returns: bool: true for yes, false for no.
notInTrade()
inTrade: Checks if a position is currently open. Interchangeable with inTrade but just here for simple semantics.
Returns: bool: true for yes, false for no.
pnl()
pnl: Calculates current profit or loss of position after the commission. If the strategy is not in trade it will always return na.
Returns: float: Current Profit or Loss of position, positive values for profit, negative values for loss.
entryBars()
entryBars: Checks how many bars it's been since the entry of the position.
Returns: int: Returns a int of strategy entry bars back. Minimum value is always corrected to 1 to avoid lookback errors.
pnlvelocity()
pnlvelocity: Calculates the velocity of pnl by following the change in open profit compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl velocity.
pnlacc()
pnlacc: Calculates the acceleration of pnl by following the change in profit velocity compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl acceleration.
pnljerk()
pnljerk: Calculates the jerk of pnl by following the change in profit acceleration compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl jerk.
pnlhigh()
pnlhigh: Calculates the highest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float highest value the pnl has reached.
pnllow()
pnllow: Calculates the lowest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float lowest value the pnl has reached.
pnldev()
pnldev: Calculates the deviance of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float deviance value of the pnl.
pnlvar()
pnlvar: Calculates the variance value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float variance value of the pnl.
pnlstdev()
pnlstdev: Calculates the stdev value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float stdev value of the pnl.
pnlmedian()
pnlmedian: Calculates the median value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float median value of the pnl.
AkselitoLibraryLibrary "AkselitoLibrary"
TODO: add library description here
fun(x)
TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
hi()
FrostyBotLibrary "FrostyBot"
JSON Alert Builder for FrostyBot.js Binance Futures and FTX orders
github.com
More Complete Version Soon.
TODO: Comment Functions and annotations from command reference ^^
TODO: Add additional whitelist and symbol mappings.
leverage()
buy()
sell()
cancelall()
closelong()
closeshort()
traillong()
trailshort()
long()
short()
takeprofit()
stoploss()
PineHelperLibrary "PineHelper"
This library provides various functions to reduce your time.
recent_opentrade_entry_bar_index()
get a recent opentrade entry bar_index
Returns: (int) bar_index
recent_closedtrade_entry_bar_index()
get a recent closedtrade entry bar_index
Returns: (int) bar_index
recent_closedtrade_exit_bar_index()
get a recent closedtrade exit bar_index
Returns: (int) bar_index
all_opnetrades_roi()
get all aopentrades roi
Returns: (float) roi
bars_since_recent_opentrade_entry()
get bars since recent opentrade entry
Returns: (int) number of bars
bars_since_recent_closedtrade_entry()
get bars since recent closedtrade entry
Returns: (int) number of bars
bars_since_recent_closedtrade_exit()
get bars since recent closedtrade exit
Returns: (int) number of bars
recent_opentrade_entry_id()
get recent opentrade entry ID
Returns: (string) entry ID
recent_closedtrade_entry_id()
get recent closedtrade entry ID
Returns: (string) entry ID
recent_closedtrade_exit_id()
get recent closedtrade exit ID
Returns: (string) exit ID
recent_opentrade_entry_price()
get recent opentrade entry price
Returns: (float) price
recent_closedtrade_entry_price()
get recent closedtrade entry price
Returns: (float) price
recent_closedtrade_exit_price()
get recent closedtrade exit price
Returns: (float) price
recent_opentrade_entry_time()
get recent opentrade entry time
Returns: (int) time
recent_closedtrade_entry_time()
get recent closedtrade entry time
Returns: (int) time
recent_closedtrade_exit_time()
get recent closedtrade exit time
Returns: (int) time
time_since_recent_opentrade_entry()
get time since recent opentrade entry
Returns: (int) time
time_since_recent_closedtrade_entry()
get time since recent closedtrade entry
Returns: (int) time
time_since_recent_closedtrade_exit()
get time since recent closedtrade exit
Returns: (int) time
recent_opentrade_size()
get recent opentrade size
Returns: (float) size
recent_closedtrade_size()
get recent closedtrade size
Returns: (float) size
all_opentrades_size()
get all opentrades size
Returns: (float) size
recent_opentrade_profit()
get recent opentrade profit
Returns: (float) profit
all_opentrades_profit()
get all opentrades profit
Returns: (float) profit
recent_closedtrade_profit()
get recent closedtrade profit
Returns: (float) profit
recent_opentrade_max_runup()
get recent opentrade max runup
Returns: (float) runup
recent_closedtrade_max_runup()
get recent closedtrade max runup
Returns: (float) runup
recent_opentrade_max_drawdown()
get recent opentrade maxdrawdown
Returns: (float) mdd
recent_closedtrade_max_drawdown()
get recent closedtrade maxdrawdown
Returns: (float) mdd
max_open_trades_drawdown()
get max open trades drawdown
Returns: (float) mdd
recent_opentrade_commission()
get recent opentrade commission
Returns: (float) commission
recent_closedtrade_commission()
get recent closedtrade commission
Returns: (float) commission
qty_by_percent_of_equity(percent)
get qty by percent of equtiy
Parameters:
percent : (series float) percent that you want to set
Returns: (float) quantity
qty_by_percent_of_position_size(percent)
get size by percent of position size
Parameters:
percent : (series float) percent that you want to set
Returns: (float) size
is_day_change()
get bool change of day
Returns: (bool) day is change or not
is_in_trade()
get bool using number of bars
Returns: (bool) allowedToTrade
discord_message(name, message)
get json format discord message
Parameters:
name : (string) name of bot
message : (string) message that you want to send
Returns: (string) json format string
telegram_message(chat_id, message)
get json format telegram message
Parameters:
chat_id : (string) chatId of bot
message : (string) message that you want to send
Returns: (string) json format string