ColorUtility for working with colors.
Get the luminosity of a color and determine the optimal (black or white) foreground color.
Indicators and strategies
ISODateTimeLibrary "ISODateTime"
getDateParts(dateStr)
Get year, month, day from date string.
Parameters:
dateStr : : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
Returns: array of int
getTimeParts(dateStr)
Get hour, minute, seconds from date string.
Parameters:
dateStr : : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
Returns: array of int
getUTCTimezone(dateStr)
Get UTC timezone.
Parameters:
dateStr : : ISO 8601 format, i.e. "2022-05-04T14:00:00.001000-04:00" or "2022-05-04T14:00:00Z"
Returns: string UTC timezone
Obj_XABCD_HarmonicLibrary "Obj_XABCD_Harmonic"
Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
init_params(pct_error, pct_asym, types, w_e, w_p, w_d)
Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
Parameters:
pct_error : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym : Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
types : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
w_e : Weight of ratio % error (used in score calculation, dft = 1)
w_p : Weight of PRZ confluence (used in score calculation, dft = 1)
w_d : Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
Returns: harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p)
Initialize an xabcd_harmonic object instance.
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
xX : Point X bar index
xY : Point X price/level
aX : Point A bar index
aY : Point A price/level
bX : Point B bar index
bY : Point B price/level
cX : Point C bar index
cY : Point C price/level
dX : Point D bar index
dY : Point D price/level
params : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp : Pattern type
p : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
get_name(p)
Get the pattern name
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern name (string)
get_symbol(p)
Get the pattern symbol
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern symbol (1 byte string)
get_pid(p)
Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern ID (string)
set_target(p, target, target_lvl, calc_target)
Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
Parameters:
p : Instance of xabcd_harmonic object
target : Target (1 or 2)
target_lvl : Target price/level (required if calc_target is not specified)
calc_target : Target to auto calculate (required if target is not specified)
Options:
Returns: Target price/level (float)
erase_pattern(p)
Erase the pattern
Parameters:
p : Instance of xabcd_harmonic object
Returns: p
draw_pattern(p)
Draw the pattern
Parameters:
p : Instance of xabcd_harmonic object
Returns: Pattern lines
erase_label(p)
Erase the pattern label
Parameters:
p : Instance of xabcd_harmonic object
Returns: p
draw_label(p, txt, tooltip, clr, txt_clr)
Draw the pattern label. Default text is the pattern name.
Parameters:
p : Instance of xabcd_harmonic object
txt : Label text
tooltip : Tooltip text
clr : Label color
txt_clr : Text color
Returns: Label
harmonic_params
Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
Fields:
pct_error : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym
types
w_e
w_p
w_d
xabcd_harmonic
Harmonic Pattern object
Fields:
bull : Bullish pattern flag
tp
xX
xY
aX
aY
bX
bY
cX
cY
dX
dY
r_xb
re_xb
r_ac
re_ac
r_bd
re_bd
r_xd
re_xd
score
score_eAvg
score_prz
score_eD
prz_bN
prz_bF
prz_xN
prz_xF
t1Hit : Target 1 flag
t1
t2Hit
t2
sHit : Stop flag
stop : Stop level
entry : Entry level
eHit
eX
eY
pLines
pLabel
pid
params
Signal AnalyzerThis library contains functions that try to analyze trading signals performance.
Like the % of average returns after a long or short signal is provided or the number of times that signal was correct, in the inmediate 2 candles after the signal.
jsonLibrary "json"
JSON Easy Object Create/stringiffy
Functions to add/write JSON
new (name , kind) -> object
set (_item , _obj , _key ) -> key index for parent object's array
add (_obj , _key , _item ) -> key index for parent object's array
write (object , kind ) -> stringified object // (enter kind to cut off key )
============================================
obj
obj Object storage container/item
Fields:
key : (string ) item name
kind : (string ) item's type(for writing)
item : (string ) item (converted to string)
keys : (string ) keys of all sub-items and objects
items : (obj ) nested obj off individual subitems (for later...)
============================================
new(_name, _kind)
create multitype object
Parameters:
_name : (string) Name off object
_kind : (string) Preset Type (_OBJECT if a container item)
Returns: object container/item 2-in-1
============================================
add(_item, _obj, _key)
Set item to object obj item (same as set, prep for future Pine methods)
Parameters:
_item : ( int / float / bool / string )
_obj : (obj multi-type-item object)
_key : ( string )
set(_item, _obj, _key)
Set item to object obj item (same as add, prep for future Pine methods)
Parameters:
_item : ( int / float / bool / string )
_obj : (obj multi-type-item object)
_key : ( string )
addstore(_parent, _child)
Add a object as a subobject to storage (Future upgrade to write/edit)
Parameters:
_parent : to insert obj into
_child : to be inserted
setstore(_child, _parent)
Add a object as a subobject to storage (Future upgrade to write/edit)
Parameters:
_child : to be inserted
_parent : to insert obj into
add(_parent, _child)
Add a object as a string rendered item
Parameters:
_parent : to insert obj into
_child : to be inserted
set(_child, _parent)
Add a object as a string rendered item
Parameters:
_child : to be inserted
_parent : to insert obj into
============================================
write(_object, _key, _itemname)
Write object to string Object
Parameters:
_object : (obj)
_key : (array<(string/int)> )/(string)
_itemname : (string)
Returns: stringified flattened object.
clean_output(_str)
Clean JSON final output
Parameters:
_str : string json item
Returns: cleaned string
WelcomeUDT█ OVERVIEW
This is a simplest example of user-defined types (UDT) or objects , which simplify as alternative to hello world.
█ CREDITS
Tradingview
█ USAGE
These are the types used during initializations, commonly variables.
export type Settings
int bar
float price
string phrase
...
Example of library function to print out label.
export printLabel(Settings setup) =>
if setup.variable
var label lab = na
label.delete(lab)
lab := label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
else
label.new(setup.bar, setup.price, setup.phrase, color = setup.bg)
Usage of types
Settings setup = Settings.new(bar_index , priceInput, phraseInput, colorInput, variableInput)
Alternative way to write types
Settings setup = Settings.new(
bar = bar_index ,
price = priceInput,
phrase = phraseInput,
variable = variableInput)
Usage of types into custom function / library function.
printLabel(setup)
printLabel(Settings)
Print out label
Parameters:
Settings : types
Returns: Label object
Settings
Initialize type values
Fields:
bar : X position for label
price : Y position for label
phrase : Text for label
bg : Color for label
variable : Boolean for enable new line and delete line
ZigZag█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing custom user-defined types and functions to calculate Zig Zag indicators within their scripts. It is not a stand-alone indicator.
Pine Script™ libraries are publications that contain reusable code for importing into Pine Script™ indicators, strategies, and other libraries. For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script™ User Manual .
█ CONCEPTS
Zig Zag
Zig Zag is a popular indicator that filters out minor price fluctuations to denoise data and emphasize trends. Traders commonly use Zig Zag for trend confirmation, identifying potential support and resistance, and pattern detection. It is formed by identifying significant local high and low points in alternating order and connecting them with straight lines, omitting all other data points from their output. There are several ways to calculate the Zig Zag's data points and the conditions by which its direction changes. This script uses pivots as the data points, which are the highest or lowest values over a defined number of bars before and after them. The direction only reverses when a newly formed pivot deviates from the last Zig Zag point in the opposite direction by an amount greater than or equal to a specified percentage.
To learn more about Zig Zag and how to calculate it, see this entry from the Help Center.
█ FOR Pine Script™ CODERS
Notes
This script's architecture utilizes user-defined types (UDTs) to create custom objects which are the equivalent of variables containing multiple parts, each able to hold independent values of different types . UDTs are the newest addition to Pine Script™ and the most advanced feature the language has seen to date. The feature's introduction creates a new runway for experienced coders to push the boundaries of Pine. We recommend that newcomers to the language explore the basics first before diving into UDTs and objects.
Demonstration Code
Our example code shows a simple use case by displaying a Zig Zag with user-defined settings. A new ZigZag object is instantiated on the first bar using a Settings object to control its attributes. The fields for the Settings object are declared using variables assigned to input.* functions, allowing control of the field values from the script's settings. The `update()` function is invoked on each bar to update the ZigZag object's fields and create new lines and labels when required.
Look first. Then leap.
█ TYPES
This library contains the following types:
Settings
Provides calculation and display attributes to ZigZag objects.
Fields:
devThreshold : The minimum percentage deviation from a point before the ZigZag will change direction.
depth : The number of bars required for pivot detection.
lineColor : Line color.
extendLast : Condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice : Condition to display the pivot price in the pivot label.
displayCumulativeVolume : Condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange : Condition to display the change in price or percent from the previous pivot in the pivot label.
differencePriceMode : Reversal change display mode. Options are "Absolute" or "Percent".
draw : Condition to display lines and labels.
Point
A coordinate containing time and price information.
Fields:
tm : A value in UNIX time.
price : A value on the Y axis (price).
Pivot
A level of significance used to determine directional movement or potential support and resistance.
Fields:
ln : A line object connecting the `start` and `end` Point objects.
lb : A label object to display pivot values.
isHigh : A condition to determine if the pivot is a pivot high.
vol : Volume for the pivot segment.
start : The coordinate of the previous Point.
end : The coordinate of the current Point.
ZigZag
An object to maintain Zig Zag settings, pivots, and volume.
Fields:
settings : Settings object to provide calculation and display attributes.
pivots : An array of Pivot objects.
sumVol : The volume sum for the pivot segment.
extend : Pivot object used to project a line from the last pivot to the last bar.
█ FUNCTIONS
This library contains the following functions:
lastPivot(this)
Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
Parameters:
this : (series ZigZag) A ZigZag object.
Returns: (Pivot) The last Pivot in the ZigZag.
update(this)
Updates `this` ZigZag object with new pivots, volume, lines, labels.
Parameters:
this : (series ZigZag) a ZigZag object.
Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
newInstance(settings)
Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
Parameters:
settings : (series Settings) A Settings object.
Returns: (ZigZag) A new ZigZag instance.
FrizBugLibrary "FrizBug"
Debug Tools | Pinescript Debugging Tool Kit
All in one Debugger - the benefit of wrapper functions to simply wrap variables or outputs and have the code still execute the same. Perfect for Debugging on Pine
str(inp)
Overloaded tostring like Function for all type+including Object Variables will also do arrays and matricies of all Types
Parameters:
inp : All types
Returns: string
print_label(str, x_offset, y, barstate, style, color, textcolor, text_align, size)
Label Helper Function - only needs the Str input to work
Parameters:
str :
x_offset : offset from last bar + or -
y : price of label
barstate : barstate built in variable
style : label style settin7
color : color setting
textcolor : textcolor
text_align : text align setting
size : text_sise
Returns: label
init()
initializes the database arrays
Returns: tuple | 2 matrix (1 matrix is varip(live) the other is reagular var (Bar))
update(log, live, live_console, log_console, live_lbl, log_lbl)
Put at the very end of your code / This updates all of the consoles
Parameters:
log : This matrix is the one used for Bar updates
live : This matrix is the one used for Real Time updates
live_console : on_offs for the consoles and lbls - call in the update function
log_console : on_offs for the consoles and lbls - call in the update function
live_lbl : on_offs for the consoles and lbls - call in the update function
log_lbl : on_offs for the consoles and lbls - call in the update function
Returns: void
log(log, inp, str_label, off, rows, index_cols, bars_back)
Function Will push to the Console offset to the right of Current bar, This is the main Console - it has 2 Feeds left and right (changeable)"
Parameters:
log : Matrix - Log or Live
inp : All types
str_label : (optional) This input will label it on the feed
off : Useful for when you don't want to remove the function"
rows : when printing or logging a matrix this will shorten the output will show last # of rows"
index_cols : When printing or logging a array or matrix this will shorten the array or the columns of a matrix by the #"
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)"
Returns: inp - all types (The log and print functions can be used as wrapper functions see usage below for examples)
Print(log, str_label, off, bars_back)
Function can be used to send information to a label style Console, Can be used as a wrapper function, Similar to str.format use with str()
Parameters:
log :
str_label : (optional) Can be used to label Data sent to the Console
off : Useful for when you don't want to remove the function
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)
Returns: string
print(inp, str_label, off, bars_back)
This Function can be used to send information to a label style Console, Can be used as a wrapper function, Overload print function
Parameters:
inp : All types
str_label : string (optional) Can be used to label Data sent to the Console
off : Useful for when you don't want to remove the function
bars_back : Adjustment for Bars Back - Default is 1 (0 for barstate.islast)
Returns: inp - all types (The log and print functions can be used as wrapper functions see usage below for examples)
Credits:
@kaigouthro - for the font library
@RicardoSantos - for the concept I used to make this
Thanks!
Use cases at the bottom
BinaryInsertionSortLibrary "BinaryInsertionSort"
Library containing functions which can help create sorted array based on binary insertion sort.
This sorting will be quicker than array.sort function if the sorting needs to be done on every bar and the size of the array is comparatively big.
This is created with the intention of using this to solve a bigger problem posted by @lejmer. Wish me luck!!
binary_insertion_sort(sortedArray, item, order)
binary insertion sort - inserts item into sorted array while maintaining sort order
Parameters:
sortedArray : array which is assumed to be sorted in the requested order
item : float|int item which needs to be inserted into sorted array
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns: int index at which the item is inserted into sorted array
update_sort_indices(sortIndices, newItemIndex)
adds the sort index of new item added to sorted array and also updates existing sort indices.
Parameters:
sortIndices : array containing sort indices of an array.
newItemIndex : sort index of new item added to sorted array
Returns: void
get_array_of_series(item, order)
Converts series into array and sorted array.
Parameters:
item : float|int series
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
get_sorted_arrays(item, order)
Converts series into array and sorted array. Also calculates the sort order of the value array
Parameters:
item : float|int series
order : Sort order - positive number means ascending order whereas negative number represents descending order
Returns:
POALibrary "POA"
This library is a client script for making a webhook signal formatted string to POABOT server.
entry_message(password, percent, leverage, kis_number)
Create a entry message for POABOT
Parameters:
password : (string) The password of your bot.
percent : (float) The percent for entry based on your wallet balance.
leverage : (int) The leverage of entry. If not set, your levereage doesn't change.
kis_number : (int) The number of koreainvestment account.
Returns: (string) A json formatted string for webhook message.
close_message(password, percent, kis_number)
Create a close message for POABOT
Parameters:
password : (string) The password of your bot.
percent : (float) The percent for close based on your wallet balance.
kis_number : (int) The number of koreainvestment account.
Returns: (string) A json formatted string for webhook message.
exit_message(password, percent)
Create a exit message for POABOT
Parameters:
password : (string) The password of your bot.
percent : (float) The percent for exit based on your wallet balance.
Returns: (string) A json formatted string for webhook message.
in_trade(start_time, end_time)
Create a trade start line
Parameters:
start_time : (int) The start of time.
end_time : (int) The end of time.
Returns: (bool) Get bool for trade based on time range.
PlurexSignalStrategyLibrary "PlurexSignalStrategy"
Provides functions that wrap the built in TradingView strategy functions so you can seemlessly integrate with Plurex Signal automation.
NOTE: Be sure to:
- set your strategy default_qty_value to the default entry percentage of your signal
- set your strategy default_qty_type to strategy.percent_of_equity
- set your strategy pyramiding to some value greater than 1 or something appropriate to your strategy in order to have multiple entries.
long(secret, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
longAndFixedStopLoss(secret, stop, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
Parameters:
secret : The secret for your Signal on plurex
stop : The trigger price for the stop loss. See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
longAndTrailingStopLoss(secret, trail_offset, trail_price, trail_points, budgetPercentage, priceLimit, marketOverride)
Open a new long entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
Parameters:
secret : The secret for your Signal on plurex
trail_offset : See strategy.exit documentation
trail_price : See strategy.exit documentation
trail_points : See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
short(secret, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
shortAndFixedStopLoss(secret, stop, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal stop loss for full open position
Parameters:
secret : The secret for your Signal on plurex
stop : The trigger price for the stop loss. See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
shortAndTrailingStopLoss(secret, trail_offset, trail_price, trail_points, budgetPercentage, priceLimit, marketOverride)
Open a new short entry. Wraps strategy function and sends plurex message as an alert. Also sets a gobal trailing stop loss for full open position. You must set one of trail_price or trail_points.
Parameters:
secret : The secret for your Signal on plurex
trail_offset : See strategy.exit documentation
trail_price : See strategy.exit documentation
trail_points : See strategy.exit documentation
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeAll(secret, marketOverride)
Close all positions. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLongs(secret, marketOverride)
close all longs. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeShorts(secret, marketOverride)
close all shorts. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastLong(secret, marketOverride)
Close last long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeLastShort(secret, marketOverride)
Close last short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstLong(secret, marketOverride)
Close first long entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
closeFirstShort(secret, marketOverride)
Close first short entry. Wraps strategy function and sends plurex message as an alert.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Dynamic Array Table (versatile display methods)Library "datTable"
Dynamic Array Table.... Configurable Shape/Size Table from Arrays
Allows for any data in any size combination of arrays to join together
with:
all possible orientations!
filling all cells contiguously and/or flipping at boundaries
vertical or horizontal rotation
x/y axis direction swapping
all types array inputs for data.
please notify of any bugs. thanks
init(_posit)
Get Table (otional gapping cells)
Parameters:
_posit : String or Int (1-9 3x3 grid L to R)
Returns: Table
coords()
Req'd coords Seperate for VARIP table, non-varip coords
add
Add arrays to display table. coords reset each calc
uses displaytable object, string titles, and color optional array, and second line optional data array.
PlurexSignalCoreLibrary "PlurexSignalCore"
General purpose functions and helpers for use in more specific Plurex Signal alerting scripts and libraries
plurexMarket()
Build a Plurex market string from a base and quote asset symbol.
Returns: A market string that can be used in Plurex Signal messages.
tickerToPlurexMarket()
Builds Plurex market string from the syminfo
Returns: A market string that can be used in Plurex Signal messages.
simpleMessage(secret, action, marketOverride)
Builds Plurex Signal Message json to be sent to a Signal webhook
Parameters:
secret : The secret for your Signal on plurex
action : The action of the message. One of .
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
entryMessage(secret, isLong, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal Entry Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
isLong : The action of the message. true for LONG, false for SHORT.
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
long(secret, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal LONG Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
short(secret, budgetPercentage, priceLimit, marketOverride)
Builds Plurex Signal SHORT Message json to be sent to a Signal webhook with optional parameters for budget and price limits.
Parameters:
secret : The secret for your Signal on plurex
budgetPercentage : Optional, The percentage of budget to use in the entry.
priceLimit : Optional, The worst price to accept for the entry.
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeAll(secret, marketOverride)
Builds Plurex Signal CLOSE_ALL Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeShorts(secret, marketOverride)
Builds Plurex Signal CLOSE_SHORTS Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLongs(secret, marketOverride)
Builds Plurex Signal CLOSE_LONGS Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeFirstLong(secret, marketOverride)
Builds Plurex Signal CLOSE_FIRST_LONG Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLastLong(secret, marketOverride)
Builds Plurex Signal CLOSE_LAST_LONG Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeFirstShort(secret, marketOverride)
Builds Plurex Signal CLOSE_FIRST_SHORT Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
closeLastShort(secret, marketOverride)
Builds Plurex Signal CLOSE_LAST_SHORT Message json to be sent to a Signal webhook.
Parameters:
secret : The secret for your Signal on plurex
marketOverride : Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own.
Returns: A json string message that can be used in alerts to send messages to Plurex.
Expansion Contraction LibraryLibrary "ExpansionContraction"
Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator created by Brian Latta based on Jake Bernstein’s principles of Moving Average Channel system.
calc(shortLookback, longLookback)
Calculates Expansion Contraction values.
Parameters:
shortLookback : Integer for the short lookback calculation, defaults to 8
longLookback : Integer for the long lookback calculation, defaults to 32
@return Returns array of Expansion Contraction values
stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong, stdevLookback)
Calculates standard deviation lines based on Expansion Contraction Long and Short values.
Parameters:
positiveShort : Float for the positive short XC value from calculation
negativeShort : Float for the negative short XC value from calculation
positiveLong : Float for the positive long XC value from calculation
negativeLong : Float for the negative long XC value from calculation
stdevLookback : Integer for the standard deviation lookback, defaults to 500
@return Returns array of standard deviation values
trend(positiveShort, negativeShort, positiveLong, negativeLong)
Determines if trend is strong or weak based on Expansion Contraction values.
Parameters:
positiveShort : Float for the positive short XC value from calculation
negativeShort : Float for the negative short XC value from calculation
positiveLong : Float for the positive long XC value from calculation
negativeLong : Float for the negative long XC value from calculation
@return Returns array of boolean values indicating strength or weakness of trend
Stringify - Timeframe Enumeration --> StringLibrary "Stringify"
Cast variable types and enumerations to human-readable Strings
timeframe(string)
Cast a timeframe enumeration to readable string.
Parameters:
string : `T` is a timeframe enumeration ('3D', '120', '15', '5s' ...)
Returns: A string representation of the timeframe or 'NA' if `x` is `na`
EMAFlowLibrary "EMAFlow"
Functions that manipulate a set of 5 MAs created within user-supplied maximum and minimum lengths. The MAs are spaced out (within the range) in a way that approximates how Fibonnaci numbers are spaced.
Using MA flow, as opposed to simple crosses of the minimum and maximum lengths, gives more detail, and can result in faster changes and more resistance to chop, depending how you use it.
f_emaFlowBias()
@function f_emaFlowBias: Gives a bullish or bearish bias reading based on the EMA flow from the user-supplied range.
@param int _min: The minimum length of the EMA set.
@param int _max: The maximum length of the EMA set.
@param: string _source: The source for the EMA set. Must be in standard format (open, close, ohlc4, etc.)
@returns: An integer, representing the bias: 1 is bearish, 2 is slightly bearish, 3 is neutral, 4 is slightly bullish, 5 is bullish.
taLibrary "ta"
Collection of all custom and enhanced TA indicators. Same as enhanced_ta. But, removed all the displays to make it faster.
ma(source, maType, length)
returns custom moving averages
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: moving average for the given type and length
atr(maType, length)
returns ATR with custom moving average
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR for the given moving average type and length
atrpercent(maType, length)
returns ATR as percentage of close price
Parameters:
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
Returns: ATR as percentage of close price for the given moving average type and length
bb(source, maType, length, multiplier, sticky)
returns Bollinger band for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger band with custom moving average for given source, length and multiplier
bbw(source, maType, length, multiplier, sticky)
returns Bollinger bandwidth for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Bandwidth for custom moving average for given source, length and multiplier
bpercentb(source, maType, length, multiplier, sticky)
returns Bollinger Percent B for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Bollinger Percent B for custom moving average for given source, length and multiplier
kc(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel for custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel for custom moving average for given souce, length and multiplier
kcw(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Channel Width for custom moving average
kpercentk(source, maType, length, multiplier, useTrueRange, sticky)
returns Keltner Channel Percent K Width with custom moving average
Parameters:
source : Moving Average Source
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : Moving Average Length
multiplier : Standard Deviation multiplier
useTrueRange : - if set to false, uses high-low.
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Keltner Percent K for given moving average, source, length and multiplier
dc(length, useAlternateSource, alternateSource, sticky)
returns Custom Donchian Channel
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel
dcw(length, useAlternateSource, alternateSource, sticky)
returns Donchian Channel Width
Parameters:
length : - donchian channel length
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel width
dpercentd(useAlternateSource, alternateSource, length, sticky)
returns Donchian Channel Percent of price
Parameters:
useAlternateSource : - Custom source is used only if useAlternateSource is set to true
alternateSource : - Custom source
length : - donchian channel length
sticky : - sticky boundaries which will only change when value is outside boundary.
Returns: Donchian channel Percent D
oscillatorRange(source, method, highlowLength, rangeLength, sticky)
oscillatorRange - returns Custom overbought/oversold areas for an oscillator input
Parameters:
source : - Osillator source such as RSI, COG etc.
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
rangeLength : - length used for calculating oversold/overbought range - usually same as oscillator length
sticky : - overbought, oversold levels won't change unless crossed
Returns: Dynamic overbought and oversold range for oscillator input
oscillator(type, length, shortLength, longLength, source, highSource, lowSource, method, highlowLength, sticky)
oscillator - returns Choice of oscillator with custom overbought/oversold range
Parameters:
type : - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr
length : - Oscillator length - not used for TSI
shortLength : - shortLength only used for TSI
longLength : - longLength only used for TSI
source : - custom source if required
highSource : - custom high source for stochastic oscillator
lowSource : - custom low source for stochastic oscillator
method : - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
highlowLength : - length on which highlow of the oscillator is calculated
sticky : - overbought, oversold levels won't change unless crossed
Returns: Oscillator value along with dynamic overbought and oversold range for oscillator input
multibands(bandType, source, maType, length, useTrueRange, sticky, numberOfBands, multiplierStart, multiplierStep)
multibands - returns Choice of oscillator with custom overbought/oversold range
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
sticky : - for sticky borders which only change upon source crossover/crossunder
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: array of band values sorted in ascending order
mbandoscillator(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep)
mbandoscillator - Multiband oscillator created on the basis of bands
Parameters:
bandType : - Band type - can be either bb or kc
source : - custom source if required
maType : Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median
length : - Oscillator length - not used for TSI
useTrueRange : - if set to false, uses high-low.
stickyBands : - for sticky borders which only change upon source crossover/crossunder for band detection
numberOfBands : - Number of bands to generate
multiplierStart : - Starting ATR or Standard deviation multiplier for first band
multiplierStep : - Incremental value for multiplier for each band
Returns: oscillator currentStates - Array containing states for last n bars
CSMlibraryLibrary "CSMlibrary"
TODO: Contains functions to simplify my scripts. Using code snippets in reference manual and elsewhere .....
CSMplot()
Slope_TKLibrary "Slope_TK"
This library calculate the slope of a serie between two points
The serie can be ta.ema(close,200) for example
The size is the number of bars between the two points for the slope calculation, for example it can be 10
slope_of_ema200 = slope(t a.eam(close, 200) , 10 )
slope( float serie, int size )
libcompressLibrary "libcompress"
numbers compressor for large output data compression
compress_fp24()
converts float to base64 (4 chars) | 24 bits: 1 sign + 5 exponent + 18 mantissa
Returns: 4-character base64_1/5/18 representation of x
compress_ufp18()
converts unsigned float to base64 (3 chars) | 18 bits: 5 exponent + 13 mantissa
Returns: 3-character base64_0/5/13 representation of x
compress_int()
converts int to base64
racille_arrayutilsLibrary "racille_arrayutils"
The most used array utility functions
func_sin()
returns sin function as a parameter to calculate the function_array()
func_cos()
returns cos function as a parameter to calculate the function_array()
func_tan()
returns tan function as a parameter to calculate the function_array()
func_cot()
returns cot function as a parameter to calculate the function_array()
func_asin()
returns asin function as a parameter to calculate the function_array()
func_acos()
returns acos function as a parameter to calculate the function_array()
func_atan()
returns atan function as a parameter to calculate the function_array()
func_acot()
returns acot function as a parameter to calculate the function_array()
func_sqrt()
returns sqrt function as a parameter to calculate the function_array()
func_pow(x)
returns pow function as a parameter to calculate the function_array()
Parameters:
x : - power
func_exp(x)
returns exp function as a parameter to calculate the function_array()
Parameters:
x : - base
func_log(x)
returns log function as a parameter to calculate the function_array()
Parameters:
x : - base
func_replace_array(arr, func)
replace each element of array with func(element) and returns a new array
Parameters:
arr : - array
func : - function to replace. Must be one of func_*()
Returns: new array, where each element is func(element)
multiply_array(arr, x)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
x : - multiplier
Returns: new array, where each element is multiplied on x
multiply_array(arr, n)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
n : - multiplier
Returns: new array, where each element is multiplied on n
multiply_array(arr, n)
multiplies each element of array by multiplier and returns a new array
Parameters:
arr : - array
n : - multiplier
Returns: new array, where each element is multiplied on n
divide_array(arr, x)
divides each element of array by divider and returns a new array
Parameters:
arr : - array
x : - divider
Returns: new array, where each element is multiplied on x
divide_array(arr, n)
divides each element of array by divider and returns a new array
Parameters:
arr : - array
n : - divider
Returns: new array, where each element is multiplied on n
increase_array(arr, x)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
x : - increment
Returns: new array, where each element is multiplied on x
increase_array(arr, n)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
n : - increment
Returns: new array, where each element is multiplied on n
increase_array(arr, n)
adds increment to each element of array and returns a new array
Parameters:
arr : - array
n : - increment
Returns: new array, where each element is multiplied on x
decrease_array(arr, x)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
x : - decrement
Returns: new array, where each element is multiplied on x
decrease_array(arr, n)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
n : - decrement
Returns: new array, where each element is multiplied on n
decrease_array(arr, n)
substracts decrement to each element of array and returns a new array
Parameters:
arr : - array
n : - decrement
Returns: new array, where each element is multiplied on x
negate_array(arr)
changes each elements sign of array and returns a new array
Parameters:
arr : - array
Returns: new array, where each element is of different sign
array_sum()
calculates elementwise sum of two arrays
array_diff()
calculates elementwise difference of two arrays
array_product()
calculates elementwise product of two arrays
array_division()
calculates elementwise division of two arrays
StringStringHashmapLibrary "StringStringHashmap"
A simple implementation of a key string-to-string value dictionary in pine script
create_ss_dict()
Create an empty string-string dictionary
Returns: the indices and elements of the dict
add_key_value(key, value, i, e)
Add new key-value pair in the dictionary
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
get_value(key, i, e)
Get the value of the given key
Parameters:
key : string
i : string the indices of the dictionary
e : string the element of the dictionary
Returns: return the value of the given key
change_value(key, value, i, e)
Change the value of the given key
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
Hurst Exponent (Dubuc's variation method)Library "Hurst"
hurst(length, samples, hi, lo)
Estimate the Hurst Exponent using Dubuc's variation method
Parameters:
length : The length of the history window to use. Large values do not cause lag.
samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
hi : The high value of the series to analyze.
lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5. A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation. Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price). Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com