garbage_collection_and_utilitiesGarbage Collection and Utilities is a library that offers a set of functions designed for efficient management of various types of arrays. This library provides garbage collection utilities to remove and delete excess elements, and also includes utilities for checking the size of arrays. It's particularly useful for developers who want to manage labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings efficiently within their scripts.
Both dump and trim act on the array backwards . This means that for trim , the elements that will be left start from 0. If you want the most recent element to be left after trim, you must use unshift().
Garbage Collection:
Functions to remove and delete excess elements from various types of arrays.
Useful for freeing up memory and keeping the arrays within desired size limits.
Size Checking:
Functions to check if arrays are larger than a specified size.
Helps in ensuring that arrays have enough elements before performing operations.
Supported Types:
Compatible with a wide range of array types, including labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
Usage:
The dump methods are ideal for clearing out unwanted elements from arrays, while the trim methods allow for more refined control over the size of arrays.
The ready methods enable you to verify if arrays have the required number of elements before proceeding with further operations.
Library "garbage_collection_and_utilities"
Provides garbage collection utilities for managing and trimming various types of arrays, and utilities to check if an array is of a specific size. Included types are: labels, lines, polylines, boxes, linefills, chart points, floats, integers, booleans, and strings.
method ready(self, size)
Checks if an array of labels is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of lines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of polylines is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of boxes is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of linefills is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of chart points is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of floats is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of integers is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of booleans is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method ready(self, size)
Checks if an array of strings is larger than a specified size
Namespace types: array
Parameters:
self (array)
size (int) : The minimum size of the array
Returns: A boolean indicating whether the array is ready
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method dump(self, max_size, trigger)
Removes and deletes excess elements from an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
trigger (bool) : A condition to trigger the dumping process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of labels
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of lines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of polylines
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of boxes
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of linefills
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of chart points
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of floats
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of integers
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of booleans
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
method trim(self, max_size, min_size, trigger)
Removes excess elements and trims an array of strings
Namespace types: array
Parameters:
self (array)
max_size (int) : The maximum size of the array
min_size (int) : The minimum size of the array
trigger (bool) : A condition to trigger the trimming process
Returns: void
Indicators and strategies
AminioLibraryLibrary "AminioLibrary"
: this is my personal library that is being used in different indicators and strategies
calculateMA(source, len, maType)
This fuction returns a moving average value based on the type
Parameters:
source (float) : Is the time series source to calculate average from
len (simple int) : The length of the moving average, this should be integer
maType (string) : The type of moving average, acceptable types are : SMA, HMA, EMA, RMA, WMA, VWMA
Returns: value of moving average
atr(source, len)
This fuction returns atr value for a given source
Parameters:
source (float) : Is the time series source to calculate atr from
len (simple int) : The length of the atr, this should be integer
Returns: value of atr from source
superTrend(source, factor, len)
This fuction returns value of super trend indicator and the trend direction as a tupple
Parameters:
source (float) : Is the time series source to calculate super trend from
factor (simple float) : The multiplication factor for upper and lower band calcualtion, this can be a float
len (simple int) : The length of the super trend, this should be integer
Returns: value of atr from source
halfTrend(am, chdev)
This fuction returns a hTrend type carrying different values for half trend indicator
Parameters:
am (int) : This is the amplitude used for calcucating the half trend, use integers
chdev (float) : This is the Channel Deviation value used for calculating upper and lower atr channel boundaries, you can use floats
Returns: hTrend data type
hTrend
Fields:
halfTrend (series__float)
trend (series__integer)
atrHigh (series__float)
atrLow (series__float)
arrowUp (series__float)
arrowDown (series__float)
Order Block Refiner [TradingFinder]🔵 Introduction
The "Refinement" feature allows you to adjust the width of the order block according to your strategy. There are two modes, "Aggressive" and "Defensive," in the "Order Block Refine". The difference between "Aggressive" and "Defensive" lies in the width of the order block.
For risk-averse traders, the "Defensive" mode is suitable as it provides a lower loss limit and a greater reward-to-risk ratio. For risk-taking traders, the "Aggressive" mode is more appropriate. These traders prefer to enter trades at higher prices, and this mode, which has a wider order block width, is more suitable for this group of individuals.
Important :
One of the advantages of using this library is increased code accuracy. Not only does it have the capability to create order blocks, but you can also simply define the condition for order block creation (true/false) and "bar_index," and you'll find the primary range without applying any filters.
🟣 Order Block Refinement Algorithm
The order block ranges are filtered in two stages. In the first stage, the "Open," "High," "Low," and "Close" of the current order block candle, its two or three previous candles, and one subsequent candle (if available) are examined. In this stage, minimum and maximum distances are calculated, and logical range filters are applied.
In the second stage, two modes, "Aggressive" and "Defensive," are calculated.
For the "Defensive" mode, the width of these ranges is compared with the "ATR" (Average True Range) of period 55, and if they are smaller than "ATR" or 1 to more than 4 times "ATR," the width of the range is reduced from 0 to 80 percent.
For the "Aggressive" mode, you get the same output as the first filter, which usually has a wider width than the "Defensive" mode.
• Order Block Refiner : Off
• Order Block Refiner : On / "Aggressive Mode"
• Order Block Refiner : On / "Defensive Mode"
🔵 How to Use
OBRefiner(string OBType, string OBRefine, string RefineMethod, bool TriggerCondition, int Index) =>
Parameters:
• OBType (string)
• OBRefine (string)
• RefineMethod (string)
• TriggerCondition (bool)
• Index (int)
To add "Order Block Refiner Library", you must first add the following code to your script.
import TFlab/OrderBlockRefiner_TradingFinder/1
OBType : This parameter receives 2 inputs. If the order block you want to "Refine" is of type demand, you should enter "Demand," and if it's of type supply, you should enter "Supply."
OBRefine : Set to "On" if you want the "Refine" operation to be performed. Otherwise, set to "Off."
RefineMethod : This input receives 2 modes, "Aggressive" and "Defensive." You can switch between these modes according to your needs.
TriggerCondition : Enter the condition with which the order block is formed in this parameter.
Index : Enter the "bar_index" of the candle where the order block is formed in this parameter.
🟣 Function Outputs
This function has 6 outputs: "bar_index" at the beginning of the "Distal" line, "bar_index+1" at the end of the "Distal" line, "Price" at the "Distal" line, "bar_index" at the beginning of the "Proximal" line, "bar_index+1" at the end of the "Proximal" line, and "Price" at the "Proximal" line, which can be used to draw order blocks.
Sample :
= Refiner.OBRefiner('Demand', 'Off', 'Aggressive',BuMChMain_Trigger, BuMChMain_Index)
if BuMChMain_Trigger
BuMChHlineMain := line.new(BuMChMain_Xp1 , BuMChMain_Yp12 , bar_index , BuMChMain_Yp12, color = color.black , style = line.style_dotted)
BuMChLlineMain := line.new(BuMChMain_Xd1 , BuMChMain_Yd12 , bar_index , BuMChMain_Yd12, color = color.black , style = line.style_dotted)
BuMChFilineMain := linefill.new(BuMChHlineMain ,BuMChLlineMain , color = color.rgb(76, 175, 80 , 75 ) )
Monty3192_LibraryLibrary "Monty3192_Library"
Libreria Monty3192 - MontyTrader
calc_func(inversion1, inversion2, inversion3, inversion4, inversion5, inversion6, inversion7, inversion8, inversion9, inversion10, precio1, precio2, precio3, precio4, precio5, precio6, precio7, precio8, precio9, precio10, act_1, act_2, act_3, act_4, act_5, act_6, act_7, act_8, act_9, act_10)
Parameters:
inversion1 (float)
inversion2 (float)
inversion3 (float)
inversion4 (float)
inversion5 (float)
inversion6 (float)
inversion7 (float)
inversion8 (float)
inversion9 (float)
inversion10 (float)
precio1 (float)
precio2 (float)
precio3 (float)
precio4 (float)
precio5 (float)
precio6 (float)
precio7 (float)
precio8 (float)
precio9 (float)
precio10 (float)
act_1 (bool)
act_2 (bool)
act_3 (bool)
act_4 (bool)
act_5 (bool)
act_6 (bool)
act_7 (bool)
act_8 (bool)
act_9 (bool)
act_10 (bool)
rend_func(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, po)
Parameters:
p1 (float)
p2 (float)
p3 (float)
p4 (float)
p5 (float)
p6 (float)
p7 (float)
p8 (float)
p9 (float)
p10 (float)
po (float)
f_drawLine(cond, x1, y1, x2, y2, colorr, txt, act, offset, txtc, txts)
Parameters:
cond (bool)
x1 (int)
y1 (float)
x2 (int)
y2 (float)
colorr (color)
txt (string)
act (bool)
offset (int)
txtc (color)
txts (string)
f_Vline(cond, x1, y1, x2, y2, colorr, txt, sel, txts, txtc)
Parameters:
cond (bool)
x1 (int)
y1 (float)
x2 (int)
y2 (float)
colorr (color)
txt (string)
sel (bool)
txts (string)
txtc (color)
get_all_time_high()
TRADINGLibrary "TRADING"
This library is a client script for making a webhook signal formatted string to PoABOT server.
entry_message(password, percent, leverage, margin_mode, kis_number)
Create a entry message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for entry based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
order_message(password, percent, leverage, margin_mode, kis_number)
Create a order message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for entry based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
close_message(password, percent, margin_mode, kis_number)
Create a close message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for close based on your wallet balance.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
exit_message(password, percent, margin_mode, kis_number)
Create a exit message for POABOT
Parameters:
password (string) : (string) The password of your bot.
percent (float) : (float) The percent for exit based on your wallet balance.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account. Default 1
Returns: (string) A json formatted string for webhook message.
manual_message(password, exchange, base, quote, side, qty, price, percent, leverage, margin_mode, kis_number, order_name)
Create a manual message for POABOT
Parameters:
password (string) : (string) The password of your bot.
exchange (string) : (string) The exchange
base (string) : (string) The base
quote (string) : (string) The quote of order message
side (string) : (string) The side of order messsage
qty (float) : (float) The qty of order message
price (float) : (float) The price of order message
percent (float) : (float) The percent for order based on your wallet balance.
leverage (int) : (int) The leverage of entry. If not set, your levereage doesn't change.
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
kis_number (int) : (int) The number of koreainvestment account.
order_name (string) : (string) The name of order message
Returns: (string) A json formatted string for webhook message.
in_trade(start_time, end_time, hide_trade_line)
Create a trade start line
Parameters:
start_time (int) : (int) The start of time.
end_time (int) : (int) The end of time.
hide_trade_line (bool) : (bool) if true, hide trade line. Default false.
Returns: (bool) Get bool for trade based on time range.
real_qty(qty, precision, leverage, contract_size, default_qty_type, default_qty_value)
Get exchange specific real qty
Parameters:
qty (float) : (float) qty
precision (float) : (float) precision
leverage (int) : (int) leverage
contract_size (float) : (float) contract_size
default_qty_type (string)
default_qty_value (float)
Returns: (float) exchange specific qty.
method set(this, password, start_time, end_time, leverage, initial_capital, default_qty_type, default_qty_value, margin_mode, contract_size, kis_number, entry_percent, close_percent, exit_percent, fixed_qty, fixed_cash, real, auto_alert_message, hide_trade_line)
Set bot object.
Namespace types: bot
Parameters:
this (bot)
password (string) : (string) password for poabot.
start_time (int) : (int) start_time timestamp.
end_time (int) : (int) end_time timestamp.
leverage (int) : (int) leverage.
initial_capital (float)
default_qty_type (string)
default_qty_value (float)
margin_mode (string) : (string) The margin mode for trade(only for OKX). "cross" or "isolated"
contract_size (float)
kis_number (int) : (int) kis_number for poabot.
entry_percent (float) : (float) entry_percent for poabot.
close_percent (float) : (float) close_percent for poabot.
exit_percent (float) : (float) exit_percent for poabot.
fixed_qty (float) : (float) fixed qty.
fixed_cash (float) : (float) fixed cash.
real (bool) : (bool) convert qty for exchange specific.
auto_alert_message (bool) : (bool) convert alert_message for exchange specific.
hide_trade_line (bool) : (bool) if true, Hide trade line. Default false.
Returns: (void)
method print(this, message)
Print message using log table.
Namespace types: bot
Parameters:
this (bot)
message (string)
Returns: (void)
method start_trade(this)
start trade using start_time and end_time
Namespace types: bot
Parameters:
this (bot)
Returns: (void)
method entry(this, id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, when)
It is a command to enter market position. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate an entry order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.order, the function strategy.entry is affected by pyramiding and it can reverse market position correctly. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
direction (string) : (string) A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop (float) : (float) An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name (string) : (string) An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
oca_type (string) : (string) An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (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.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method order(this, id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, when)
It is a command to place order. If an order with the same ID is already pending, it is possible to modify the order. If there is no order with the specified ID, a new order is placed. To deactivate order, the command strategy.cancel or strategy.cancel_all should be used. In comparison to the function strategy.entry, the function strategy.order is not affected by pyramiding. If both 'limit' and 'stop' parameters are 'NaN', the order type is market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
direction (string) : (string) A required parameter. Market position direction: 'strategy.long' is for long, 'strategy.short' is for short.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to trade. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Limit price of the order. If it is specified, the order type is either 'limit', or 'stop-limit'. 'NaN' should be specified for any other order type.
stop (float) : (float) An optional parameter. Stop price of the order. If it is specified, the order type is either 'stop', or 'stop-limit'. 'NaN' should be specified for any other order type.
oca_name (string) : (string) An optional parameter. Name of the OCA group the order belongs to. If the order should not belong to any particular OCA group, there should be an empty string.
oca_type (string) : (string) An optional parameter. Type of the OCA group. The allowed values are: "strategy.oca.none" - the order should not belong to any particular OCA group; "strategy.oca.cancel" - the order should belong to an OCA group, where as soon as an order is filled, all other orders of the same group are cancelled; "strategy.oca.reduce" - the order should belong to an OCA group, where if X number of contracts of an order is filled, number of contracts for each other order of the same OCA group is decreased by X.
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (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.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method close_all(this, comment, alert_message, immediately, when)
Exits the current market position, making it flat.
Namespace types: bot
Parameters:
this (bot)
comment (string) : (string) An optional parameter. Additional notes on the order.
alert_message (string) : (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.
immediately (bool) : (bool) An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method cancel(this, id, when)
It is a command to cancel/deactivate pending orders by referencing their names, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel an order by referencing its identifier.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method cancel_all(this, when)
It is a command to cancel/deactivate all pending orders, which were generated by the functions: strategy.order, strategy.entry and strategy.exit.
Namespace types: bot
Parameters:
this (bot)
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
method close(this, id, comment, qty, qty_percent, alert_message, immediately, when)
It is a command to exit from the entry with the specified ID. If there were multiple entry orders with the same ID, all of them are exited at once. If there are no open entries with the specified ID by the moment the command is triggered, the command will not come into effect. The command uses market order. Every entry is closed by a separate market order.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
comment (string) : (string) An optional parameter. Additional notes on the order.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
qty_percent (float) : (float) Defines the percentage (0-100) of the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
alert_message (string) : (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.
immediately (bool) : (bool) An optional parameter. If true, the closing order will be executed on the tick where it has been placed, ignoring the strategy parameters that restrict the order execution to the open of the next bar. The default is false.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
ticks_to_price(ticks, from)
Converts ticks to a price offset from the supplied price or the average entry price.
Parameters:
ticks (float) : (float) Ticks to convert to a price.
from (float) : (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.
method exit(this, id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, comment_profit, comment_loss, comment_trailing, alert_message, alert_profit, alert_loss, alert_trailing, when)
It is a command to exit either a specific entry, or whole market position. If an order with the same ID is already pending, it is possible to modify the order. If an entry order was not filled, but an exit order is generated, the exit order will wait till entry order is filled and then the exit order is placed. To deactivate an exit order, the command strategy.cancel or strategy.cancel_all should be used. If the function strategy.exit is called once, it exits a position only once. If you want to exit multiple times, the command strategy.exit should be called multiple times. If you use a stop loss and a trailing stop, their order type is 'stop', so only one of them is placed (the one that is supposed to be filled first). If all the following parameters 'profit', 'limit', 'loss', 'stop', 'trail_points', 'trail_offset' are 'NaN', the command will fail. To use market order to exit, the command strategy.close or strategy.close_all should be used.
Namespace types: bot
Parameters:
this (bot)
id (string) : (string) A required parameter. The order identifier. It is possible to cancel or modify an order by referencing its identifier.
from_entry (string) : (string) An optional parameter. The identifier of a specific entry order to exit from it. To exit all entries an empty string should be used. The default values is empty string.
qty (float) : (float) An optional parameter. Number of contracts/shares/lots/units to exit a trade with. The default value is 'NaN'.
qty_percent (float) : (float) Defines the percentage of (0-100) the position to close. Its priority is lower than that of the 'qty' parameter. Optional. The default is 100.
profit (float) : (float) An optional parameter. Profit target (specified in ticks). If it is specified, a limit order is placed to exit market position when the specified amount of profit (in ticks) is reached. The default value is 'NaN'.
limit (float) : (float) An optional parameter. Profit target (requires a specific price). If it is specified, a limit order is placed to exit market position at the specified price (or better). Priority of the parameter 'limit' is higher than priority of the parameter 'profit' ('limit' is used instead of 'profit', if its value is not 'NaN'). The default value is 'NaN'.
loss (float) : (float) An optional parameter. Stop loss (specified in ticks). If it is specified, a stop order is placed to exit market position when the specified amount of loss (in ticks) is reached. The default value is 'NaN'.
stop (float) : (float) An optional parameter. Stop loss (requires a specific price). If it is specified, a stop order is placed to exit market position at the specified price (or worse). Priority of the parameter 'stop' is higher than priority of the parameter 'loss' ('stop' is used instead of 'loss', if its value is not 'NaN'). The default value is 'NaN'.
trail_price (float) : (float) An optional parameter. Trailing stop activation level (requires a specific price). If it is specified, a trailing stop order will be placed when the specified price level is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
trail_points (float) : (float) An optional parameter. Trailing stop activation level (profit specified in ticks). If it is specified, a trailing stop order will be placed when the calculated price level (specified amount of profit) is reached. The offset (in ticks) to determine initial price of the trailing stop order is specified in the 'trail_offset' parameter: X ticks lower than activation level to exit long position; X ticks higher than activation level to exit short position. The default value is 'NaN'.
trail_offset (float) : (float) An optional parameter. Trailing stop price (specified in ticks). The offset in ticks to determine initial price of the trailing stop order: X ticks lower than 'trail_price' or 'trail_points' to exit long position; X ticks higher than 'trail_price' or 'trail_points' to exit short position. The default value is 'NaN'.
oca_name (string) : (string) An optional parameter. Name of the OCA group (oca_type = strategy.oca.reduce) the profit target, the stop loss / the trailing stop orders belong to. If the name is not specified, it will be generated automatically.
comment (string) : (string) Additional notes on the order. If specified, displays near the order marker on the chart. Optional. The default is na.
comment_profit (string) : (string) Additional notes on the order if the exit was triggered by crossing `profit` or `limit` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
comment_loss (string) : (string) Additional notes on the order if the exit was triggered by crossing `stop` or `loss` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
comment_trailing (string) : (string) Additional notes on the order if the exit was triggered by crossing `trail_offset` specifically. If specified, supercedes the `comment` parameter and displays near the order marker on the chart. Optional. The default is na.
alert_message (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Optional. The default is na.
alert_profit (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `profit` or `limit` specifically. Optional. The default is na.
alert_loss (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `stop` or `loss` specifically. Optional. The default is na.
alert_trailing (string) : (string) Text that will replace the '{{strategy.order.alert_message}}' placeholder when one is used in the "Message" field of the "Create Alert" dialog. Only replaces the text if the exit was triggered by crossing `trail_offset` specifically. Optional. The default is na.
when (bool) : (bool) An optional parmeter. Condition, deprecated.
Returns: (void)
percent_to_ticks(percent, from)
Converts a percentage of the supplied price or the average entry price to ticks.
Parameters:
percent (float) : (float) The percentage of supplied price to convert to ticks. 50 is 50% of the entry price.
from (float) : (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.
percent_to_price(percent, from)
Converts a percentage of the supplied price or the average entry price to a price.
Parameters:
percent (float) : (float) The percentage of the supplied price to convert to price. 50 is 50% of the supplied price.
from (float) : (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).
bot
Fields:
password (series__string)
start_time (series__integer)
end_time (series__integer)
leverage (series__integer)
initial_capital (series__float)
default_qty_type (series__string)
default_qty_value (series__float)
margin_mode (series__string)
contract_size (series__float)
kis_number (series__integer)
entry_percent (series__float)
close_percent (series__float)
exit_percent (series__float)
log_table (series__table)
fixed_qty (series__float)
fixed_cash (series__float)
real (series__bool)
auto_alert_message (series__bool)
hide_trade_line (series__bool)
LoggerLibLibrary "LoggerLib"
Function Description:
This library aims to extend the logging functionality by overloading various logging methods.
The objective is to enable appending ".log" at the end of different types to make logging outputs easier.
Key features of this function include:
Multi Debug Levels: The readout will encompass error, warning, and info messages.
Controlled Output: Logging can be set for every bar or only the last X bars.
Automatic Logging: Essential variables such as bar_index, time, price, and # of times log has been called can be extracted.
Methods Included:
Logs variables.
Logs floats.
Logs integers.
Logs strings.
Logs booleans.
Logs arrays.
Logs matrices.
Logs maps.
This comprehensive logging function enhances logging capabilities,
providing versatility and ease of use in capturing and debugging data across different contexts.
method log(this, debugLevel, showLast, verbose, showLabels)
Logs any variable type, excluding custom UDTs, and displays to the logs or as a label on bars.
```
// Example
variable = close
variable.log()
variable.log(2, 0,true,true)
// Example Arrays
ArrayVariable = array.from()
ArrayVariable.log()
// Examples Maps
MapVariable = map.new()
MapVariable.log( )
// Example Funky stuff
close.log(debugLevel = 1, showLast = 1, verbose = true, showLabels = true)
```
Namespace types: series float, simple float, input float, const float
Parameters:
this (float) : Variable to be formatted into a logger message
debugLevel (int) : Log Level `1 = log.info | 2 = log.warning 3 = log.error`
showLast (int) : Shows last x Logs, 0 shows all.
verbose (bool) : Include additional Debug logger Data.
showLabels (bool) : Create Labels of the logs on that main chart.
Returns: void
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series int, simple int, input int, const int
Parameters:
this (int)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series string, simple string, input string, const string
Parameters:
this (string)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
this (bool)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: series color, simple color, input color, const color
Parameters:
this (color)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: array
Parameters:
this (array)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: map
Parameters:
this (map)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
method log(this, debugLevel, showLast, verbose, showLabels)
Namespace types: matrix
Parameters:
this (matrix)
debugLevel (int)
showLast (int)
verbose (bool)
showLabels (bool)
divergingchartpatternLibrary "divergingchartpattern"
Library having implementation of converging chart patterns
getPatternNameByType(patternType)
Returns pattern name based on type
Parameters:
patternType (int) : integer value representing pattern type
Returns: string name of the pattern
method find(this, sProperties, dProperties, patterns, ohlcArray)
find converging patterns for given zigzag
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Current zigzag Object
sProperties (ScanProperties) : ScanProperties Object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/5) : DrawingProperties Object
patterns (array type from Trendoscope/abstractchartpatterns/5) : array of existing patterns to check for duplicates
ohlcArray (array type from Trendoscope/ohlc/1) : array of OHLC values for historical reference
Returns: string name of the pattern
ScanProperties
Object containing properties for pattern scanning
Fields:
baseProperties (ScanProperties type from Trendoscope/abstractchartpatterns/5) : Object of Base Scan Properties
convergingDistanceMultiplier (series float)
booksLibrary "books"
this library contains excerpts from great books to help with trading.
enhiridion()
Fills the map with admonitions from Epictetus' "Enchiridion".
Returns: map with admonitions
CandleInsightsLibrary "CandleInsights"
CandleInsights provides a set of utility functions to facilitate identifying certain types of individual candles and candle patterns.
isBullish()
Returns true if candle is bullish.
Returns: bool
isBearish()
Returns true if candle is bearish.
Returns: bool
isHammer()
Returns true if candle is a hammer. TODO: Allow params
Returns: bool
isShootingStar()
Returns true if candle is a shooting star. TODO: Allow params
Returns: bool
isBearishToppingTail()
Returns true if candle is bearish with a top wick over half the range of the candle. TODO: Allow params
Returns: bool
isHanging()
Returns true if candle is considering a hanging candle (aka hanging man). TODO: Allow params
Returns: bool
isLongBullish(pctChg)
Parameters:
pctChg (float)
isBullishEngulfing()
utilsLibrary "utils"
Provides a set of utility functions for use in strategies or indicators.
colorGreen(opacity)
Parameters:
opacity (int)
colorRed(opacity)
Parameters:
opacity (int)
colorTeal(opacity)
Parameters:
opacity (int)
colorBlue(opacity)
Parameters:
opacity (int)
colorOrange(opacity)
Parameters:
opacity (int)
colorPurple(opacity)
Parameters:
opacity (int)
colorPink(opacity)
Parameters:
opacity (int)
colorYellow(opacity)
Parameters:
opacity (int)
colorWhite(opacity)
Parameters:
opacity (int)
colorBlack(opacity)
Parameters:
opacity (int)
trendChangingUp(emaShort, emaLong)
Signals when the trend is starting to change in a positive direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
trendChangingDown(emaShort, emaLong)
Signals when the trend is starting to change in a negative direction.
Parameters:
emaShort (float)
emaLong (float)
Returns: bool
percentChange(start, end)
Returns the percent change between a start number and end number. A positive change returns a positive value and vice versa.
Parameters:
start (float)
end (float)
Returns: float
percentOf(percent, n)
Returns the number that's the percentage of the provided value.
Parameters:
percent (float) : Use 0.2 for 20 percent, 0.35 for 35 percent, etc.
n (float) : The number to calculate the percentage of.
Returns: float
targetPriceByPercent(percent, n)
Parameters:
percent (float)
n (float)
hasNegativeSlope(start, end)
Parameters:
start (float)
end (float)
timeinrange(resolution, session, timezone)
Returns true when the current time is within a given session window. Note, the time is calculated in the "America/New_York" timezone.
Parameters:
resolution (simple string) : The time interval to use to start/end the background color. Use "1" for the coloring the background up to the minute.
session (simple string) : The session string to use to identify the time window. Example: "0930-1600:23456" means normal market hours on weekdays.
timezone (simple string)
Returns: series bool
barsSinceLastEntry()
Returns the number of bars since the last entry order.
Returns: series int
barsSinceLastExit()
Returns the number of bars since the last exit order.
Returns: series int
calcSlope(ln, lookback)
Calculates the slope of the provided line based on its x,y coordinates in the previous bar to the current bar.
Parameters:
ln (float)
lookback (int)
Returns: series float
openPL()
Returns slope of the line given the start and end x,y coordinates.
Returns: series float
hasConsecutiveNegativeCandles(lookbackInput)
Returns true if the number of consecutive red candles matches the provided count.
Parameters:
lookbackInput (int) : The amount of bars to look back to check for consecutive negative bars. Default = 1.
Returns: series bool
stdevPercent(stdev, price)
Returns the standard deviation as a percentage of price.
Parameters:
stdev (float) : The standard deviation value
price (float) : The current price of the target ticker.
Returns: series float
XXPivotsBreakoutsLibrary "XXPivotsBreakouts"
Utilizes k-NN machine learning to predict breakout zones from pivot points, aiding traders in identifying potential bullish and bearish market movements. Ideal for trend-following and breakout strategies.
breakouts(pivotBars, numNeighbors, maxData, predictionSmoothing)
Detects and predicts breakout points from pivot data.
Parameters:
pivotBars (int) : int: Number of bars for pivot point detection.
numNeighbors (int) : int: Neighbors count for k-NN prediction.
maxData (int) : int: Maximum pivot data points for analysis.
predictionSmoothing (int) : int: Smoothing period for predictions.
Returns: : Lower and higher prediction bands plus pivot signal, 1 for ph and -1 for pl.
regressionsLibrary "regressions"
This library computes least square regression models for polynomials of any form for a given data set of x and y values.
fit(X, y, reg_type, degrees)
Takes a list of X and y values and the degrees of the polynomial and returns a least square regression for the given polynomial on the dataset.
Parameters:
X (array) : (float ) X inputs for regression fit.
y (array) : (float ) y outputs for regression fit.
reg_type (string) : (string) The type of regression. If passing value for degrees use reg.type_custom
degrees (array) : (int ) The degrees of the polynomial which will be fit to the data. ex: passing array.from(0, 3) would be a polynomial of form c1x^0 + c2x^3 where c2 and c1 will be coefficients of the best fitting polynomial.
Returns: (regression) returns a regression with the best fitting coefficients for the selecected polynomial
regress(reg, x)
Regress one x input.
Parameters:
reg (regression) : (regression) The fitted regression which the y_pred will be calulated with.
x (float) : (float) The input value cooresponding to the y_pred.
Returns: (float) The best fit y value for the given x input and regression.
predict(reg, X)
Predict a new set of X values with a fitted regression. -1 is one bar ahead of the realtime
Parameters:
reg (regression) : (regression) The fitted regression which the y_pred will be calulated with.
X (array)
Returns: (float ) The best fit y values for the given x input and regression.
generate_points(reg, x, y, left_index, right_index)
Takes a regression object and creates chart points which can be used for plotting visuals like lines and labels.
Parameters:
reg (regression) : (regression) Regression which has been fitted to a data set.
x (array) : (float ) x values which coorispond to passed y values
y (array) : (float ) y values which coorispond to passed x values
left_index (int) : (int) The offset of the bar farthest to the realtime bar should be larger than left_index value.
right_index (int) : (int) The offset of the bar closest to the realtime bar should be less than right_index value.
Returns: (chart.point ) Returns an array of chart points
plot_reg(reg, x, y, left_index, right_index, curved, close, line_color, line_width)
Simple plotting function for regression for more custom plotting use generate_points() to create points then create your own plotting function.
Parameters:
reg (regression) : (regression) Regression which has been fitted to a data set.
x (array)
y (array)
left_index (int) : (int) The offset of the bar farthest to the realtime bar should be larger than left_index value.
right_index (int) : (int) The offset of the bar closest to the realtime bar should be less than right_index value.
curved (bool) : (bool) If the polyline is curved or not.
close (bool) : (bool) If true the polyline will be closed.
line_color (color) : (color) The color of the line.
line_width (int) : (int) The width of the line.
Returns: (polyline) The polyline for the regression.
series_to_list(src, left_index, right_index)
Convert a series to a list. Creates a list of all the cooresponding source values
from left_index to right_index. This should be called at the highest scope for consistency.
Parameters:
src (float) : (float ) The source the list will be comprised of.
left_index (int) : (float ) The left most bar (farthest back historical bar) which the cooresponding source value will be taken for.
right_index (int) : (float ) The right most bar closest to the realtime bar which the cooresponding source value will be taken for.
Returns: (float ) An array of size left_index-right_index
range_list(start, stop, step)
Creates an from the start value to the stop value.
Parameters:
start (int) : (float ) The true y values.
stop (int) : (float ) The predicted y values.
step (int) : (int) Positive integer. The spacing between the values. ex: start=1, stop=6, step=2:
Returns: (float ) An array of size stop-start
regression
Fields:
coeffs (array__float)
degrees (array__float)
type_linear (series__string)
type_quadratic (series__string)
type_cubic (series__string)
type_custom (series__string)
_squared_error (series__float)
X (array__float)
swinglibraryLibrary "swinglibrary"
This library is for calculating non-repainting swings for further calculation on them.
These swings can later be drawn, but drawing is not part of this library, only the calculation.
What do I need to use the library?
You better include the following constants into your script using this library:
int SWING_NO_ACTION = 0
int SWING_FLIP = 1
int SWING_FLIP_NEW_SWING = 2
int SWING_FLIP_UPDATED = 3
int RELATION_HIGHER = 1
int RELATION_EQUAL = 0
int RELATION_LOWER = -1
Choosing the function, that fits your needs
This library contains 4 functions for calculating swings, the difference between them are the data you get for every swing point and additional average values for length and duration:
swings()
swingsR()
swingsL()
swingsLDR()
The naming scheme of these functions is the following:
The base version swings() is only for the swings containing the following swingPoint type:
swingPoint
Fields:
x (integer) : bar index
y (float) : price
hilo (integer) 1 -> high, -1 -> low
and the return type:
swingReturn
Fields:
swings (array) : array of the last x swing points
newSwingHigh (integer) : flag to detect changes for swing highs see constants (SWING_NO_ACTION, SWING_FLIP_NEW_SWING, SWING_FLIP_UPDATED)
newSwingLow (integer) : flag to detect changes for swing lows see constants (SWING_NO_ACTION, SWING_FLIP_NEW_SWING, SWING_FLIP_UPDATED)
The R in swingsR() stands for relation where the previously shown types do also contain the relation between the swings of the same swing type (highs and lows respectively).
The same goes for L in swingsL() for length containing the price difference between the current and previous swing point in ticks.
And in the following version swingsLDR() there is also the duration between the current and previous point included.
The parameters for the other functions and type definitions include only the ones, that are needed, the "full" version of the function is described here:
swingsLDR(swingSize, dtbStrength, init, SWING_HISTORY_NUM)
Parameters:
swingSize (int) This parameter defines the size of the swings to look after, meaning higher values will lead to bigger swings
dtbStrength (int) Value between 0 and 100 is a factor (%) to the ATR that is used to calculate equal highs/lows (double tops / bottoms).
Higher values will result in a higher tolerance of price difference between the swings.
init (bool) This value is usually set to false on default.
It has a special use case, where we need to reduce memory usage and calculation time on the script using this library by start calculating at x bars back instead of the beginning of the chart.
In this case, we set init = true on the first bar we start calculating the swings on to perform the correct initialization.
SWING_HISTORY_NUM (int) This is the max number of swings that are stored in the array, so only the last SWING_HISTORY_NUM swings are stored in the array to reduce the memory usage.
New ones remove the oldest ones like in a ring buffer.
This is also influencing the average duration and average swing length.
swingPointLDR
Fields:
x (integer) : bar index
y (float) : price
hilo (integer) : 1 -> high, -1 -> low
length (float) : price difference to the previous swing point in ticks
duration (integer) : duration difference to the previous swing point in number of bars
relation (integer) : see constants RELATION_HIGHER, RELATION_EQUAL, RELATION_LOWER: reelation to the previous swing points of the same type (previous high or previous low respectively)
swingReturnLDR
Fields:
swings (array) : array of the last x swing points
newSwingHigh (integer) : flag to detect changes for swing highs see constants (SWING_NO_ACTION, SWING_FLIP_NEW_SWING, SWING_FLIP_UPDATED)
newSwingLow (integer) : flag to detect changes for swing lows see constants (SWING_NO_ACTION, SWING_FLIP_NEW_SWING, SWING_FLIP_UPDATED)
avSwLength (float) : average swing length for the last x swings (depending on the max number of swings)
avSwingDuration (float) : average swing duration for the last x swings (depending on the max number of swings)
MarkdownUtilsLibrary "MarkdownUtils"
This library shows all of CommonMark's formatting elements that are currently (2024-03-30)
available in Pine Script® and gives some hints on how to use them.
The documentation will be in the tooltip of each of the following functions. It is also
logged into Pine Logs by default if it is called. We can disable the logging by setting `pLog = false`.
mediumMathematicalSpace()
Medium mathematical space that can be used in e.g. the library names like `Markdown Utils`.
Returns: The medium mathematical space character U+205F between those double quotes " ".
zeroWidthSpace()
Zero-width space.
Returns: The zero-width character U+200B between those double quotes "".
stableSpace(pCount)
Consecutive space characters in Pine Script® are replaced by a single space character on output.
Therefore we require a "stable" space to properly indent text e.g. in Pine Logs. To use it in code blocks
of a description like this one, we have to copy the 2(!) characters between the following reverse brackets instead:
# > <
Those are the zero-width character U+200B and a space.
Of course, this can also be used within a text to add some extra spaces.
Parameters:
pCount (simple int)
Returns: A zero-width space combined with a space character.
headers(pLog)
Headers
```
# H1
## H2
### H3
#### H4
##### H5
###### H6
```
*results in*
# H1
## H2
### H3
#### H4
##### H5
###### H6
*Best practices*: Add blank line before and after each header.
Parameters:
pLog (bool)
paragrahps(pLog)
Paragraphs
```
First paragraph
Second paragraph
```
*results in*
First paragraph
Second paragraph
Parameters:
pLog (bool)
lineBreaks(pLog)
Line breaks
```
First row
Second row
```
*results in*
First row\
Second row
Parameters:
pLog (bool)
emphasis(pLog)
Emphasis
With surrounding `*` and `~` we can emphasize text as follows. All emphasis can be arbitrarily combined.
```
*Italics*, **Bold**, ***Bold italics***, ~~Scratch~~
```
*results in*
*Italics*, **Bold**, ***Bold italics***, ~~Scratch~~
Parameters:
pLog (bool)
blockquotes(pLog)
Blockquotes
Lines starting with at least one `>` followed by a space and text build block quotes.
```
Text before blockquotes.
> 1st main blockquote
>
> 1st main blockquote
>
>> 1st 1-nested blockquote
>
>>> 1st 2-nested blockquote
>
>>>> 1st 3-nested blockquote
>
>>>>> 1st 4-nested blockquote
>
>>>>>> 1st 5-nested blockquote
>
>>>>>>> 1st 6-nested blockquote
>
>>>>>>>> 1st 7-nested blockquote
>
> 2nd main blockquote, 1st paragraph, 1st row\
> 2nd main blockquote, 1st paragraph, 2nd row
>
> 2nd main blockquote, 2nd paragraph, 1st row\
> 2nd main blockquote, 2nd paragraph, 2nd row
>
>> 2nd nested blockquote, 1st paragraph, 1st row\
>> 2nd nested blockquote, 1st paragraph, 2nd row
>
>> 2nd nested blockquote, 2nd paragraph, 1st row\
>> 2nd nested blockquote, 2nd paragraph, 2nd row
Text after blockquotes.
```
*results in*
Text before blockquotes.
> 1st main blockquote
>
>> 1st 1-nested blockquote
>
>>> 1st 2-nested blockquote
>
>>>> 1st 3-nested blockquote
>
>>>>> 1st 4-nested blockquote
>
>>>>>> 1st 5-nested blockquote
>
>>>>>>> 1st 6-nested blockquote
>
>>>>>>>> 1st 7-nested blockquote
>
> 2nd main blockquote, 1st paragraph, 1st row\
> 2nd main blockquote, 1st paragraph, 2nd row
>
> 2nd main blockquote, 2nd paragraph, 1st row\
> 2nd main blockquote, 2nd paragraph, 2nd row
>
>> 2nd nested blockquote, 1st paragraph, 1st row\
>> 2nd nested blockquote, 1st paragraph, 2nd row
>
>> 2nd nested blockquote, 2nd paragraph, 1st row\
>> 2nd nested blockquote, 2nd paragraph, 2nd row
Text after blockquotes.
*Best practices*: Add blank line before and after each (nested) blockquote.
Parameters:
pLog (bool)
lists(pLog)
Paragraphs
#### Ordered lists
The first line starting with a number combined with a delimiter `.` or `)` starts an ordered
list. The list's numbering starts with the given number. All following lines that also start
with whatever number and the same delimiter add items to the list.
#### Unordered lists
A line starting with a `-`, `*` or `+` becomes an unordered list item. All consecutive items with
the same start symbol build a separate list. Therefore every list can only have a single symbol.
#### General information
To start a new list either use the other delimiter or add some non-list text between.
List items in Pine Script® allow line breaks but cannot have paragraphs or blockquotes.
Lists Pine Script® cannot be nested.
```
1) 1st list, 1st item, 1st row\
1st list, 1st item, 2nd row
1) 1st list, 2nd item, 1st row\
1st list, 2nd item, 2nd row
1) 1st list, 2nd item, 1st row\
1st list, 2nd item, 2nd row
1. 2nd list, 1st item, 1st row\
2nd list, 1st item, 2nd row
Intermediary text.
1. 3rd list
Intermediary text (sorry, unfortunately without proper spacing).
8. 4th list, 8th item
8. 4th list, 9th item
Intermediary text.
- 1st list, 1st item
- 1st list, 2nd item
* 2nd list, 1st item
* 2nd list, 2nd item
Intermediary text.
+ 3rd list, 1st item
+ 3rd list, 2nd item
```
*results in*
1) 1st list, 1st item, 1st row\
1st list, 1st item, 2nd row
1) 1st list, 2nd item, 1st row\
1st list, 2nd item, 2nd row
1) 1st list, 2nd item, 1st row\
1st list, 2nd item, 2nd row
1. 2nd list, 1st item, 1st row\
2nd list, 1st item, 2nd row
Intermediary text.
1. 3rd list
Intermediary text (sorry, unfortunately without proper spacing).
8. 4th list, 8th item
8. 4th list, 9th item
Intermediary text.
- 1st list, 1st item
- 1st list, 2nd item
* 2nd list, 1st item
* 2nd list, 2nd item
Intermediary text.
+ 3rd list, 1st item
+ 3rd list, 2nd item
Parameters:
pLog (bool)
code(pLog)
### Code
`` `Inline code` `` is formatted like this.
To write above line we wrote `` `` `Inline code` `` ``.
And to write that line we added another pair of `` `` `` around that code and
a zero-width space of function between the inner `` `` ``.
### Code blocks
can be formatted like that:
~~~
```
export method codeBlock() =>
"code block"
```
~~~
Or like that:
```
~~~
export method codeBlock() =>
"code block"
~~~
```
To write ````` within a code block we can either surround it with `~~~`.
Or we "escape" those ````` by only the zero-width space of function (stableSpace) in between.
To escape \` within a text we use `` \` ``.
Parameters:
pLog (bool)
horizontalRules(pLog)
Horizontal rules
At least three connected `*`, `-` or `_` in a separate line build a horizontal rule.
```
Intermediary text.
---
Intermediary text.
***
Intermediary text.
___
Intermediary text.
```
*results in*
Intermediary text.
---
Intermediary text.
***
Intermediary text.
___
Intermediary text.
*Best practices*: Add blank line before and after each horizontal rule.
Parameters:
pLog (bool)
tables(pLog)
Tables
A table consists of a single header line with columns separated by `|`
and followed by a row of alignment indicators for either left (`---`, `:---`), centered (`:---:`) and right (`---:`)
A table can contain several rows of data.
The table can be written as follows but hasn't to be formatte like that. By adding (stableSpace)
on the correct side of the header we could even adjust the spacing if we don't like it as it is. Only around
the column separator we should only use a usual space on each side.
```
Header 1 | Header 1 | Header 2 | Header 3
--- | :--- | :----: | ---:
Left (Default) | Left | Centered | Right
Left (Default) | Left | Centered | Right
```
*results in*
Header 1 | Header 1 | Header 2 | Header 3
--- | :--- | :----: | ---:
Left (Default) | Left | Centered | Right
Left (Default) | Left | Centered | Right
Parameters:
pLog (bool)
links(pLog)
## Links.
### Inline-style
` (Here should be the link to the TradingView homepage)`\
results in (Here should be the link to the TradingView homepage)
` (Here should be the link to the TradingView homepage "Trading View tooltip")`\
results in (Here should be the link to the TradingView homepage "Trading View tooltip")
### Reference-style
One can also collect all links e.g. at the end of a description and use a reference to that as follows.
` `\
results in .
` `\
results in .
` `\
results in .
` (../tradingview/scripts/readme)`\
results in (../tradingview/scripts/readme).
### URLs and email
URLs are also identified by the protocol identifier, email addresses by `@`. They can also be surrounded by `<` and `>`.
Input | Result
--- | ---
`Here should be the link to the TradingView homepage` | Here should be the link to the TradingView homepage
`` |
`support@tradingview.com` | support@tradingview.com
`` |
## Images
We can display gif, jp(e)g and png files in our documentation, if we add `!` before a link.
### Inline-style:
`! (Here should be the link to the favicon of the TradingView homepage "Trading View icon")`
results in
! (Here should be the link to the favicon of the TradingView homepage "Trading View icon")\
### Reference-style:
`! `
results in
!
## References for reference-style links
Even though only the formatted references are visible here in the output, this text is also followed
by the following references with links in the style
` : Referenced link`
```
: Here should be the link to the TradingView homepage "Trading view text-reference tooltip"
: Here should be the link to the TradingView homepage "Trading view number-reference tooltip"
: Here should be the link to the TradingView homepage "Trading view self-reference tooltip"
: Here should be the link to the favicon of the TradingView homepage "Trading View icon (reference)"
```
: Here should be the link to the TradingView homepage "Trading view text-reference tooltip"
: Here should be the link to the TradingView homepage "Trading view number-reference tooltip"
: Here should be the link to the TradingView homepage "Trading view self-reference tooltip"
: Here should be the link to the favicon of the TradingView homepage "Trading View icon (reference)"
Parameters:
pLog (bool)
taskLists(pLog)
Task lists.
Other Markdown implementations can also display task lists for list items like `- ` respective `- `.
This can only be simulated by inline code `` ´ ` ``.
Make sure to either add a line-break `\` at the end of the line or a new paragraph by a blank line.
### Task lists
` ` Finish library
` ` Finish library
Parameters:
pLog (bool)
escapeMd(pLog)
Escaping Markdown syntax
To write and display Markdown syntax in regular text, we have to escape it. This can be done
by adding `\` before the Markdown syntax. If the Markdown syntax consists of more than one character
in some cases also the character of function can be helpful if a command consists of
more than one character if it is placed between the separate characters of the command.
Parameters:
pLog (bool)
test()
Calls all functions of above script.
DeleteArrayType█ OVERVIEW
Here are common functions usually delete drawing once array of drawing is recall.
Method is used as in pine script version 5 instead of custom function.
It is an upgrade from DeleteArrayObject , which may not support overload parameter in future.
Library "DeleteArrayType"
TODO: Delete array type especially for drawings
method deleteLabel(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: label.delete()
method deleteLine(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: line.delete()
method deleteLineFill(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: linefill.delete()
method deletePolyLine(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: polyline.delete()
method deleteBox(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: box.delete()
method deleteTable(id)
TODO: Delete array
Namespace types: array
Parameters:
id (array)
Returns: TODO: table.delete()
YPLibrary "YP"
TODO: add library description here
breakUp(previousHigh)
breakUp: Determines if the low of the first bar of the current day
is above a given previous high.
Parameters:
previousHigh (float)
Returns: : Boolean value indicating whether the condition is met (true) or not (false).
Alert Sender Library [TradingFinder]Library "AlertSenderLibrary_TradingFinder"
🔵 Introduction
The "Alert Sender Library" is a management and production program for "Alert Messages" that enables the creation of unique messages for any type of signal generated by indicators or strategies.
These messages include the direction of the signal, symbol, time frame, the date and time the condition was triggered, prices related to the signal, and a personal message from you. To make better and more optimal use of this "library", you should carefully study " Key Features" and "How to Use".
🔵 Key Features
Automatic Detection of Appropriate Type :
Using two parameters, "AlertType" and "DetectionType", which you must enter at the beginning into the "AlertSender" function, the type of the alert message is determined.
For example, if you select one of the "DetectionType"s such as "Order Block Signal", "Signal", and "Setup", your alert type will be chosen based on "Long" and "Short". Whether it's "Long" or "Short" depends on the "AlertType" you have set to either "Bullish" or "Bearish".
Automatic Symbol Detection :
Whenever you add an alert for a specific symbol, if you want the name of that symbol to be in your message text, you must manually write the name of the symbol in your message. One of the capabilities of the "Alert Sender" is the automatic detection of the symbol and adding it to the message text.
Automatic Time Frame Detection :
When adding your alert, the "Alert Sender" detects the time frame of the symbol you intend to add the alert for and adds it to the text. This feature is very practical and can prevent traders from making mistakes.
For example, a trader might add alerts for a specific symbol using a specific indicator in different time frames, taking the main signal in the 1-hour time frame and only a confirmation signal in the 15-minute time frame. This feature helps to identify in which time frame the signal is set.
Detection of Date and Time When the Signal is Triggered :
You can have the date and time at the moment the message is sent. This feature has various uses. For example, if you use the Webhook URL feature to send messages to a Telegram channel, there might be issues with alert delivery on your server, causing delays, and you might receive the message when it has lost its validity.
With this feature, you can match the sending time of the message from TradingView with the receipt time in your messenger and detect if there is a delay in message delivery.
Important :
You can also set the Time Zone you wish to receive the date and time based on.
Display of "Key Prices" :
Key prices can vary based on the type of signals. For example, when the "DetectionType" is in "Order Block Signal" mode, the key prices are the "Distal" and "Proximal" prices. Or if the "DetectionType" is in "Setup" mode, the key prices are "Entry", "Stop Loss", and "Take Profit".
Receipt of Personal "Messages" :
You can enter your personal message using "input.string" or "input.text_area" in addition to the messages that are automatically created.
Beautiful and Functional Display of Messages :
The titles of messages sent by "AlertSender" are displayed using related emojis to prevent mistakes due to visual errors, enhancing beauty.
🔵 How to Use
🟣 Familiarity with Function and Parameters
AlertSender(Condition, Alert, AlertName, AlertType, DetectionType, SetupData, Frequency, UTC, MoreInfo, Message, o, h, l, c, Entry, TP, SL, Distal, Proximal)
Parameters:
- Condition (bool)
- Alert (string)
- AlertName (string)
- AlertType (string)
- DetectionType (string)
- SetupData (string)
- Frequency (string)
- UTC (string)
- MoreInfo (string)
- Message (string)
- o (float)
- h (float)
- l (float)
- c (float)
- Entry (float)
- TP (float)
- SL (float)
- Distal (float)
- Proximal (float)
To add "Alert Sender Library", you must first add the following code to your script.
import TFlab/AlertSenderLibrary_TradingFinder/1
🟣 Parameters
"Condition" : This parameter is a Boolean. You need to set it based on the condition that, when met (or fired), you want to receive an alert. The output should be either "true" or "false".
"Alert" : This parameter accepts one of two inputs, "On" or "Off". If set to "On", the alarm is active; if "Off", the alarm is deactivated. This input is useful when you have numerous alerts in an indicator or strategy and need to activate only a few of them. "Alert" is a string parameter.
Alert = input.string('On', 'Alert', , 'If you turn on the Alert, you can receive alerts and notifications after setting the "Alert".', group = 'Alert')
"AlertName" : This is a string parameter where you can enter the name you choose for your alert.
AlertName = input.string('Order Blocks Finder ', 'Alert Name', group = 'Alert')
"AlertType" : The inputs for this parameter are "Bullish" or "Bearish". If the condition selected in the "Condition" parameter is of a bullish bias, you should set this parameter to "Bullish", and if the condition is of a bearish bias, it should be set to "Bearish". "AlertType" is a string parameter.
"DetectionType" : This parameter's predefined inputs include "Order Block Signal", "Signal", "Setup", and "Analysis". You may provide other inputs, but some functionalities, like "Key Price", might be lost. "DetectionType" is a string parameter.
"SetupData" :
If "DetectionType" is set to "Setup", you must specify "SetupData" as either "Basic" or "Full". In "Basic" mode, only the "Entry" price needs to be defined in the function, and "TP" (Take Profit) and "SL" (Stop Loss) can be any number or NA. In "Full" mode, you need to define "Entry", "SL", and "TP". "Setup" is a string parameter.
"Frequency" : This string parameter defines the announcement frequency. Choices include: "All" (activates the alert every time the function is called), "Once Per Bar" (activates the alert only on the first call within the bar), and "Once Per Bar Close" (the alert is activated only by a call at the last script execution of the real-time bar upon closing). The default setting is "Once per Bar".
Frequency = input.string('Once Per Bar', 'Message Frequency', , 'The triggering frequency. Possible values are: All (all function calls trigger the alert), Once Per Bar (the first function call during the bar triggers the alert), Per Bar Close (the function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it closes). The default is alert.freq_once_per_bar.', group = 'Alert')
"UTC" : With this parameter, you can set the Time Zone for the date and time of the alert's dispatch. "UTC" is a string parameter and can be set as "UTC-4", "UTC+1", "UTC+9", or any other Time Zone.
UTC = input.string('UTC', 'Show Alert time by Time Zone', group = 'Alert')
"MoreInfo" : This parameter can take one of two inputs, "On" or "Off", which are strings. Additional information, including "Time" and "Key Price", is included. If set to "On", this information is received; if "Off", it is not displayed in the sent message.
MoreInfo = input.string('On', 'Display More Info', , group = 'Alert')
"Message" : This parameter captures the user's personal message through an input and displays it at the end of the sent message. It is a string input.
MessageBull = input.text_area('Long Position', 'Long Signal Message', group = 'Alert') MessageBear = input.text_area('Short Position', 'Short Signal Message', group = 'Alert')
"o" (Open Price): A floating-point number representing the opening price of the candle. This input is necessary when the "DetectionType" is set to "Signal". Otherwise, it can be any number or "na".
"h" (High Price): A float variable for the highest price of the candle. Required when "DetectionType" is "Signal"; in other cases, any number or "na" is acceptable.
"l" (Low Price): A float representing the lowest price of the candle. This field must be filled if "DetectionType" is "Signal". If not, it can be any number or "na".
"c" (Close Price): A floating-point variable indicating the closing price of the candle. Needed for "Signal" type detections; otherwise, it can take any value or "na".
"Entry" : A float variable indicating the entry price into a trading setup. This is relevant when "DetectionType" is in "Setup" mode. In other scenarios, it can be any number or "na". It denotes the price at which the trade setup is entered.
"TP" (Take Profit): A float that is necessary when "DetectionType" is "Setup" and "SetupData" is "Full". Otherwise, it can be any number or "na". It signifies the price target for taking profits in a trading setup.
"SL" (Stop Loss): A float required when "DetectionType" is "Setup" and "SetupData" is "Full". It can be any number or "na" in other cases. This value represents the price at which a stop loss is set to limit losses.
"Distal" : A float important for "Order Block Signal" detection. It can be any number or "na" if not in use. This variable indicates the price reaching the distal line of an order block.
"Proximal" : A float needed for "Order Block Signal" detection mode. It can take any value or "na" otherwise. It marks the price reaching the proximal line of an order block.
AdaptivePNLLibrary "Adaptive Profit And Loss"
Provide Take profit and Stop loss values depending on source.
TakeProfitPriceTypes()
Provides supported Take profit sources
Returns: Supported Take profit sources
StopLossPriceTypes()
Provides supported Take profit sources
Returns: Supported Take profit sources
Price(type)
Get price value by selected price type
Parameters:
type (string) : price type from @TakeProfitPriceTypes() or @StopLossPriceTypes()
Returns: Required price value.
LinearProfit(initPerc, stepPerc)
Lineary changed profit
Parameters:
initPerc (float) : Initial profit value in percent unit
stepPerc (float) : Amount of change per every bar since last entry. Posiitive value will decrease profit in time.
Returns: Profit value lineary increased/decreased since last entry. If there is no opened trade, value is NaN
AdaptedProfit(initPerc, stepPerc, source)
Profit adapted to lowest/highest value of given source and lineary changes after it
Parameters:
initPerc (float) : Initial profit value in percent unit
stepPerc (float) : Amount of change per every bar since last entry. Posiitive value will decrease profit in time.
source (float) : Source according to is profit adapted. If it reach high, profit is increased for long positions, same for low and short positions.
Returns: Profit value lineary increased/decreased and adjusted since last entry. If there is no active trade, value is NaN
LinearStopLoss(initPerc, stepPerc)
Lineary changed stop loss
Parameters:
initPerc (float) : Initial stop loss value in percent unit
stepPerc (float) : Amount of change per every bar since last entry. Posiitive value will increase stop loss in time.
Returns: Stop loss value lineary increased/decreased since last entry. If there is no opened trade, value is NaN
AdaptedStopLoss(initPerc, stepPerc, source)
Stop loss adapted to highest/lowest value of given source and lineary changes after it
Parameters:
initPerc (float) : Initial stop loss value in percent unit
stepPerc (float) : Amount of change per every bar since last entry. Posiitive value will increase stop loss in time.
source (float) : Source according to is stop loss adapted. If it reach high, stop loss is increased for long positions, same for low and short positions.
Returns: Stop loss value lineary increased/decreased and adjusted since last entry. If there is no active trade, value is NaN
LibraryCOT_NZLibrary "LibraryCOT_NZ"
This library provides tools to help Pine programmers fetch Commitment of Traders (COT) data for futures.
rootToCFTCCode(root)
Accepts a futures root and returns the relevant CFTC code.
Parameters:
root (simple string) : Root prefix of the future's symbol, e.g. "ZC" for "ZC1!"" or "ZCU2021".
Returns: The part of a COT ticker corresponding to `root`, or "" if no CFTC code exists for the `root`.
currencyToCFTCCode(currency)
Converts a currency string to its corresponding CFTC code.
Parameters:
currency (simple string)
Returns: The corresponding to the currency, if one exists.
optionsToTicker(includeOptions)
Returns the part of a COT ticker using the `includeOptions` value supplied, which determines whether options data is to be included.
Parameters:
includeOptions (simple bool) : A "bool" value: 'true' if the symbol should include options and 'false' otherwise.
Returns: The part of a COT ticker: "FO" for data that includes options and "F" for data that doesn't.
metricNameAndDirectionToTicker(metricName, metricDirection)
Returns a string corresponding to a metric name and direction, which is one component required to build a valid COT ticker ID.
Parameters:
metricName (simple string) : One of the metric names listed in this library's chart. Invalid values will cause a runtime error.
metricDirection (simple string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Valid values vary with metrics. Invalid values will cause a runtime error.
Returns: The part of a COT ticker ID string, e.g., "OI_OLD" for "Open Interest" and "No direction", or "TC_L" for "Traders Commercial" and "Long".
typeToTicker(metricType)
Converts a metric type into one component required to build a valid COT ticker ID. See the "Old and Other Futures" section of the CFTC's Explanatory Notes for details on types.
Parameters:
metricType (simple string) : Metric type. Accepted values are: "All", "Old", "Other".
Returns: The part of a COT ticker.
convertRootToCOTCode(mode, convertToCOT)
Depending on the `mode`, returns a CFTC code using the chart's symbol or its currency information when `convertToCOT = true`. Otherwise, returns the symbol's root or currency information. If no COT data exists, a runtime error is generated.
Parameters:
mode (simple string) : A string determining how the function will work. Valid values are:
"Root": the function extracts the futures symbol root (e.g. "ES" in "ESH2020") and looks for its CFTC code.
"Base currency": the function extracts the first currency in a pair (e.g. "EUR" in "EURUSD") and looks for its CFTC code.
"Currency": the function extracts the quote currency ("JPY" for "TSE:9984" or "USDJPY") and looks for its CFTC code.
"Auto": the function tries the first three modes (Root -> Base Currency -> Currency) until a match is found.
convertToCOT (simple bool) : "bool" value that, when `true`, causes the function to return a CFTC code. Otherwise, the root or currency information is returned. Optional. The default is `true`.
Returns: If `convertToCOT` is `true`, the part of a COT ticker ID string. If `convertToCOT` is `false`, the root or currency extracted from the current symbol.
COTTickerid(COTType, CFTCCode, includeOptions, metricName, metricDirection, metricType)
Returns a valid TradingView ticker for the COT symbol with specified parameters.
Parameters:
COTType (simple string) : A string with the type of the report requested with the ticker, one of the following: "Legacy", "Disaggregated", "Financial".
CFTCCode (simple string)
includeOptions (simple bool) : A boolean value. 'true' if the symbol should include options and 'false' otherwise.
metricName (simple string) : One of the metric names listed in this library's chart.
metricDirection (simple string) : Direction of the metric, one of the following: "Long", "Short", "Spreading", "No direction".
metricType (simple string) : Type of the metric. Possible values: "All", "Old", and "Other".
Returns: A ticker ID string usable with `request.security()` to fetch the specified Commitment of Traders data.
EagleEyeEmbedsLibrary "EagleEyeEmbeds"
Pine Script library to build out a webhook that is catered to Discord Embed
formatTimeframe()
discordWebhookJSON(contentText, username, avatar_url, embeds)
Constructs a JSON string for a Discord webhook message. This string includes optional fields for content, username, avatar URL, and embeds.
Parameters:
contentText (string) : (string, optional): The main text content of the webhook message. Default is 'na'.
username (string) : (string, optional): Overrides the default username of the webhook. Default is 'na'.
avatar_url (string) : (string, optional): Overrides the default avatar URL of the webhook. Default is 'na'.
embeds (string) : (string, optional): A string containing one or more embed JSON objects. This should be formatted correctly as a JSON array. Default is 'na'.
createEmbedJSON(title, description, url, thumbImgUrl, color, authorName, authorUrl, authorIconUrl, fields, imageUrl, timeStamp, footerText, footerIconUrl)
Creates a JSON string for a single embed object for a Discord webhook.
Parameters:
title (string) : (string, optional): The title of the embed. Default is 'na' (not applicable).
description (string) : (string, optional): The description text of the embed. Supports basic formatting. Default is 'na'.
url (string)
thumbImgUrl (string)
color (int) : (int, optional): The color code of the embed, typically in decimal format. Default is 'na'.
authorName (string) : (string, optional): The name of the author to display in the embed. Default is 'na'.
authorUrl (string) : (string, optional): The URL linked to the author's name. Default is 'na'.
authorIconUrl (string) : (string, optional): The URL of the icon to display next to the author's name. Default is 'na'.
fields (string) : (string, optional): A string containing one or more field JSON objects. This should be formatted correctly as a JSON array. Default is 'na'. Note: Use the 'createEmbedFieldJSON' function to generate these JSON field strings before adding them to the array.
imageUrl (string)
timeStamp (string)
footerText (string) : (string, optional): The footer text to display in the embed.
footerIconUrl (string) : (string, optional): The URL of the icon to display next to the footer text.
createEmbedFieldJSON(name, value, inline)
Creates a JSON string representing a single field object within an embed for a Discord webhook message.
Parameters:
name (string) : (string): The name of the field, acting as a title for the field content.
value (string) : (string): The value of the field, containing the actual text or information you want to display within the field.
inline (bool) : (bool, optional): A boolean flag indicating whether the field should be displayed inline with other fields. If set to true, the field will be displayed on the same line as the next field
Multi conditions matricesLibrary "multi_conditions_matrices"
: facilitate including multiple AND / OR conditions to a script such as two entry / exit inputs groups.
method addConditions(conditions, conditionPair)
Helper to append conditions to a matrix condition array
Namespace types: matrix
Parameters:
conditions (matrix)
conditionPair (array) : array A condition pair , an input can be passed directly to enable
method check(conditions, operatorAnd)
check several condition within given operator
Namespace types: matrix
Parameters:
conditions (matrix)
operatorAnd (bool) : bool true if the operator between condition is AND (default OR)
Returns: bool Evaluates conditions
isWeekend()
isNightSignal(nightHour, morningHour, timezone)
Parameters:
nightHour (int)
morningHour (int)
timezone (string)
Moving point of controlLibrary "moving_poc"
method getMovingPoc(averagePriceByVolumeHistory, ltfVolumeSerie, ltfPriceSerie, nbBarsToLookback)
Volume point of control (PoC) extracted from lower time frame data and previous time period
Namespace types: array
Parameters:
averagePriceByVolumeHistory (array) : An array of float to record previous PoC average
ltfVolumeSerie (array) : Source of volume for the lower timeframe (ltf)
ltfPriceSerie (array) : Source of price for the lower timeframe
nbBarsToLookback (int) : A number of bars determining the lookback period of this PoC
Returns: Serie of PoC
FunctionDiscreteCosineTransformLibrary "FunctionDiscreteCosineTransform"
Discrete Cosine Transform (DCT)
The Discrete Cosine Transform (DCT) is a mathematical algorithm that converts a series of samples of a signal, typically in the time domain, into another domain called the frequency or spectral domain. It's commonly used for data compression and image/video coding applications such as JPEG and MPEG standards.
The DCT works by multiplying the input sequence with specific cosine functions that are pre-defined and then summing up these products to obtain a new series of values, which represent the frequency components of the original signal. The main advantage of the DCT over other transforms like Fourier Transform is its ability to handle non-stationary signals (i.e., signals with varying statistical properties) more effectively due to its localized basis functions.
In simple terms, the DCT can be thought of as a way to break down an image or video into different frequency components and then compress them without losing too much information. This compression technique is essential for efficient transmission and storage of digital media files over the internet or on devices with limited memory capacity.
~Mixtral4x7b
___
Reference:
lcamtuf.substack.com
dct(data, len)
Discrete Cosine Transform.
Parameters:
data (array) : Data source.
len (int) : Length of the sampling window.
Returns: List with frequency domain transformed information.
dct(data, len)
Discrete Cosine Transform.
Parameters:
data (float) : Data source.
len (int) : Length of the sampling window.
Returns: List with frequency domain transformed information.
idct(data, len)
Inverse Discrete Cosine Transform.
Parameters:
data (array) : Data source.
len (int) : Length of the sampling window.
Returns: List with time domain transformed information.
idct(data, len)
Inverse Discrete Cosine Transform.
Parameters:
data (float) : Data source.
len (int) : Length of the sampling window.
Returns: List with time domain transformed information.