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 (float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (float) : 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) : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher)
w_e (float) : Weight of ratio % error (used in score calculation, dft = 1)
w_p (float) : Weight of PRZ confluence (used in score calculation, dft = 1)
w_d (float) : 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(x, a, b, c, d, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of points
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:
x (point type from dlmysolutions/Pattern/1) : Point X
a (point type from dlmysolutions/Pattern/1) : Point A
b (point type from dlmysolutions/Pattern/1) : Point B
c (point type from dlmysolutions/Pattern/1) : Point C
d (point type from dlmysolutions/Pattern/1) : Point D
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of x and y coordinate values.
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 (int) : Point X bar index (required)
xY (float) : Point X price/level (required)
aX (int) : Point A bar index (required)
aY (float) : Point A price/level (required)
bX (int) : Point B bar index (required)
bY (float) : Point B price/level (required)
cX (int) : Point C bar index (required)
cY (float) : Point C price/level (required)
dX (int) : Point D bar index
dY (float) : Point D price/level
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(pattern, params, tp, p)
Initialize an xabcd_harmonic object instance from a given pattern
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:
pattern (pattern type from dlmysolutions/Pattern/1) : Pattern
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
method get_name(p)
Get the pattern name
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern name (string)
method get_symbol(p)
Get the pattern symbol
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern symbol (1 byte string)
method get_pid(p)
Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern ID (string)
method 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.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
target (int) : Target (1 or 2)
target_lvl (float) : Target price/level (required if calc_target is not specified)
calc_target (string) : Target to auto calculate (required if target is not specified)
Options:
Returns: Target price/level (float)
method erase_pattern(p)
Erase the pattern
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: p
method draw_pattern(p, clr)
Draw the pattern
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color)
Returns: Pattern lines
method erase_label(p)
Erase the pattern label
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: p
method draw_label(p, clr, txt_clr, txt, tooltip)
Draw the pattern label. Default text is the pattern name.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color) : Label color
txt_clr (color) : Text color
txt (string) : Label text
tooltip (string) : Tooltip text
Returns: Label
harmonic_params
Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
Fields:
pct_error (series float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (series float)
types (array)
w_e (series float)
w_p (series float)
w_d (series float)
xabcd_harmonic
Harmonic Pattern object
Fields:
bull (series bool) : Bullish pattern flag
tp (series int)
x (point type from dlmysolutions/Pattern/1)
a (point type from dlmysolutions/Pattern/1)
b (point type from dlmysolutions/Pattern/1)
c (point type from dlmysolutions/Pattern/1)
d (point type from dlmysolutions/Pattern/1)
r_xb (series float)
re_xb (series float)
r_ac (series float)
re_ac (series float)
r_bd (series float)
re_bd (series float)
r_xd (series float)
re_xd (series float)
score (series float)
score_eAvg (series float)
score_prz (series float)
score_eD (series float)
prz_bN (series float)
prz_bF (series float)
prz_xN (series float)
prz_xF (series float)
t1Hit (series bool) : Target 1 flag
t1 (series float)
t2Hit (series bool)
t2 (series float)
sHit (series bool) : Stop flag
stop (series float) : Stop level
entry (series float) : Entry level
eHit (series bool)
e (point type from dlmysolutions/Pattern/1)
invalid_d (series bool)
pLines (array)
pLabel (series label)
pid (series string)
params (harmonic_params)
指標和策略
PatternLibrary "Pattern"
Pattern object definitions and functions. Easily draw and keep track of patterns, legs, and points.
Supported pattern types:
Type Leg validation # legs
"xabcd" Direction 3 or 4 (point D not required)
"zigzag" Direction >= 2
"free" None >= 2
Summary of exported types and associated methods/functions:
type point A point on the chart (x,y)
draw_label() Draw a point label
erase_label() Erase a point label
type leg A pattern leg (i.e. point A to point B)
leg_init() Initialize/instantiate a leg
draw() Draw a leg
erase() Erase a leg
leg_getLineTerms() Get the slope and y-intercept of a leg
leg_getPrice() Get price (Y) at a given bar index (X) within a leg
type pattern A pattern (set of at least 2 connected legs)
pattern_init() Initialize/instantiate a pattern
draw() Draw a pattern
erase() Erase a pattern
*See bottom of the script for example usage*
erase_label(this)
Delete the point label
Parameters:
this (point) : Point
Returns: Void
draw_label(this, position, clr, transp, txt_clr, txt, tooltip, size)
Draw the point label
Parameters:
this (point) : Point
position (string)
clr (color)
transp (float)
txt_clr (color)
txt (string)
tooltip (string)
size (string)
Returns: line
leg_init(a, b, prev, next, line)
Initialize a pattern leg
Parameters:
a (point) : Point A (required)
b (point) : Point B (required)
prev (leg) : Previous leg
next (leg) : Next leg
line (line) : Line
Returns: New instance of leg object
erase(this)
Delete the pattern leg
Parameters:
this (leg) : Leg
Returns: Void
erase(this)
Delete the pattern lines
Parameters:
this (pattern) : Pattern
Returns: Void
draw(this, clr, style, transp, width)
Draw the pattern leg
Parameters:
this (leg) : Leg
clr (color) : Color
style (string) : Style ("solid", "dotted", "dashed", "arrowleft", "arrowright")
transp (float) : Transparency
width (int) : Width
Returns: line
draw(this, clr, style, transp, width)
Draw the pattern
Parameters:
this (pattern) : Pattern
clr (color) : Color
style (string) : Style ("solid", "dotted", "dashed", "arrowleft", "arrowright")
transp (float) : Transparency
width (int) : Width
Returns: line
leg_getLineTerms(this)
Get the slope and y-intercept of a leg
Parameters:
this (leg) : Leg
Returns:
leg_getPrice(this, index)
Get the price (Y) at a given bar index (X) within the leg
Parameters:
this (leg) : Leg
index (int) : Bar index
Returns: Price (float)
pattern_init(legs, tp, name, subType, pid)
Initialize a pattern object from a given set of legs
Parameters:
legs (array) : Array of pattern legs (required)
tp (string) : Pattern type ("zigzag", "xabcd", or "free". dft = "free")
name (string) : Pattern name
subType (string) : Pattern subtype
pid (string) : Pattern Identifier string
Returns: New instance of pattern object, if one was successfully created
pattern_init(points, tp, name, subType, pid)
Initialize a pattern object from a given set of points
Parameters:
points (array)
tp (string) : Pattern type ("zigzag", "xabcd", or "free". dft = "free")
name (string) : Pattern name
subType (string) : Pattern subtype
pid (string) : Pattern Identifier string
Returns: New instance of pattern object, if one was successfully created
point
A point on the chart (x,y)
Fields:
x (series int) : Bar index (x coordinate)
y (series float)
label (series label)
leg
A pattern leg (point A to point B)
Fields:
a (point) : Point A
b (point)
deltaX (series int)
deltaY (series float)
prev (leg)
next (leg)
retrace (series float)
line (series line)
pattern
A pattern (set of at least 2 connected legs)
Fields:
legs (array)
type (series string)
subType (series string)
name (series string)
pid (series string)
DrawLibrary "Draw"
Draw patterns, lines, labels, shapes etc.
pat_colors(bull, buLn, beLn, ltxt)
Parameters:
bull (bool)
buLn (color)
beLn (color)
ltxt (color)
size(size)
Parameters:
size (string)
label_style(style)
Parameters:
style (string)
line_style(style)
Parameters:
style (string)
font_size(size)
Parameters:
size (string)
xabcd(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, iE, bull, bu, be)
Draw XABCD pattern
Parameters:
xX (int)
xY (float)
aX (int)
aY (float)
bX (int)
bY (float)
cX (int)
cY (float)
dX (int)
dY (float)
iE (float)
bull (bool)
bu (color)
be (color)
xabcd_inProgress(bull, type, tLimit, entry, stop, t1, t2, bcNt, bcFt, xaNt, xaFt, xX, xY, aY, bX, bY, cY, dX, dY, cBu, cBe, lTxt)
draw PRZ, entry, stop, targets, and projected reversal paths for XABCD pattern
Parameters:
bull (bool)
type (int)
tLimit (int)
entry (float)
stop (float)
t1 (float)
t2 (float)
bcNt (float)
bcFt (float)
xaNt (float)
xaFt (float)
xX (int)
xY (float)
aY (float)
bX (int)
bY (float)
cY (float)
dX (int)
dY (float)
cBu (color)
cBe (color)
lTxt (color)
xabcd_incInProgress(bull, type, tLimit, entry, xX, xY, aY, bX, bY, cX, cY, dY, cBu, cBe, lTxt)
Parameters:
bull (bool)
type (int)
tLimit (int)
entry (float)
xX (int)
xY (float)
aY (float)
bX (int)
bY (float)
cX (int)
cY (float)
dY (float)
cBu (color)
cBe (color)
lTxt (color)
xabcd_inProgress2(bull, tLimit, entry, stop, t1, t2, xadl, bcdl, xcdl, xX, xY, bX, bY, dX, dY, cBu, cBe, lTxt)
draw PRZ, entry, stop, targets, and projected reversal paths for XABCD pattern
Parameters:
bull (bool)
tLimit (int)
entry (float)
stop (float)
t1 (float)
t2 (float)
xadl (float)
bcdl (float)
xcdl (float)
xX (int)
xY (float)
bX (int)
bY (float)
dX (int)
dY (float)
cBu (color)
cBe (color)
lTxt (color)
eHitLbl(x, e, dX, dY, bull, lOnly)
Draw entry hit label
Parameters:
x (int)
e (float)
dX (int)
dY (float)
bull (bool)
lOnly (bool)
tHitLbl(x, tgt, eX, eY, bull)
Draw target hit label
Parameters:
x (int)
tgt (float)
eX (int)
eY (float)
bull (bool)
sHitLbl(x, s, eX, eY, bull)
Draw stop hit label
Parameters:
x (int)
s (float)
eX (int)
eY (float)
bull (bool)
level(y, x, type, length, extend, padding, b_style, colr, txt_color, txt, txt_loc, txt_size)
Draw a level (box)
Parameters:
y (float)
x (int)
type (int)
length (int)
extend (string)
padding (float)
b_style (string)
colr (color)
txt_color (color)
txt (string)
txt_loc (string)
txt_size (string)
incTtTxt(tp, name, xbr, xbre, acr, acre, bcN, bcF, xaN, xaF, score, e)
Parameters:
tp (int)
name (string)
xbr (float)
xbre (float)
acr (float)
acre (float)
bcN (float)
bcF (float)
xaN (float)
xaF (float)
score (float)
e (float)
TALibrary "TA"
General technical analysis functions
div_bull(pS, iS, cp_length_after, cp_length_before, pivot_length, lookback, lookback_pivs, no_broken, pW, iW, hidW, regW)
Test for bullish divergence
Parameters:
pS (float) : Price series (float)
iS (float) : Indicator series (float)
cp_length_after (simple int) : Bars after current (divergent) pivot low to be considered a valid pivot (optional int)
cp_length_before (simple int) : Bars before current (divergent) pivot low to be considered a valid pivot (optional int)
pivot_length (simple int) : Bars before and after prior pivot low to be considered valid pivot (optional int)
lookback (simple int) : Bars back to search for prior pivot low (optional int)
lookback_pivs (simple int) : Pivots back to search for prior pivot low (optional int)
no_broken (simple bool) : Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
pW (simple float) : Weight of change in price, used in degree of divergence calculation (optional float)
iW (simple float) : Weight of change in indicator, used in degree of divergence calculation (optional float)
hidW (simple float) : Weight of hidden divergence, used in degree of divergence calculation (optional float)
regW (simple float) : Weight of regular divergence, used in degree of divergence calculation (optional float)
Returns:
flag = true if divergence exists (bool)
degree = degree (strength) of divergence (float)
type = 1 = regular, 2 = hidden (int)
lx1 = x coordinate 1 (int)
ly1 = y coordinate 1 (float)
lx2 = x coordinate 2 (int)
ly2 = y coordinate 2 (float)
div_bear(pS, iS, cp_length_after, cp_length_before, pivot_length, lookback, lookback_pivs, no_broken, pW, iW, hidW, regW)
Test for bearish divergence
Parameters:
pS (float) : Price series (float)
iS (float) : Indicator series (float)
cp_length_after (simple int) : Bars after current (divergent) pivot high to be considered a valid pivot (optional int)
cp_length_before (simple int) : Bars before current (divergent) pivot highto be considered a valid pivot (optional int)
pivot_length (simple int) : Bars before and after prior pivot high to be considered valid pivot (optional int)
lookback (simple int) : Bars back to search for prior pivot high (optional int)
lookback_pivs (simple int) : Pivots back to search for prior pivot high (optional int)
no_broken (simple bool) : Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
pW (simple float) : Weight of change in price, used in degree of divergence calculation (optional float)
iW (simple float) : Weight of change in indicator, used in degree of divergence calculation (optional float)
hidW (simple float) : Weight of hidden divergence, used in degree of divergence calculation (optional float)
regW (simple float) : Weight of regular divergence, used in degree of divergence calculation (optional float)
Returns:
flag = true if divergence exists (bool)
degree = degree (strength) of divergence (float)
type = 1 = regular, 2 = hidden (int)
lx1 = x coordinate 1 (int)
ly1 = y coordinate 1 (float)
lx2 = x coordinate 2 (int)
ly2 = y coordinate 2 (float)
test_cd(cd, bc, xa, xc, ad, pErr, p_types)
Validate CD leg of XABCD
Parameters:
cd (float)
bc (float)
xa (float)
xc (float)
ad (float)
pErr (float)
p_types (array)
pat_xabcd_testSym(xax, abx, bcx, cdx, pAsym)
Validate ΔX symmetry of XABCD pattern
Parameters:
xax (int)
abx (int)
bcx (int)
cdx (int)
pAsym (float)
harmonic_xabcd_validate(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, pErr, pAsym, gart, bat, bfly, crab, shark, cyph)
Validate harmonic XABCD pattern
Parameters:
xX (int) : X coordinate of point X (int)
xY (float) : Y coordinate of point X (float)
aX (int) : X coordinate of point A (int)
aY (float) : Y coordinate of point A (float)
bX (int) : X coordinate of point B (int)
bY (float) : Y coordinate of point B (float)
cX (int) : X coordinate of point C (int)
cY (float) : Y coordinate of point C (float)
dX (int) : X coordinate of point D (int)
dY (float) : Y coordinate of point D (float)
pErr (float) : Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
pAsym (float) : Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
gart (bool) : Flag to validate Gartley pattern (bool)
bat (bool) : Flag to validate Bat pattern (bool)
bfly (bool) : Flag to validate Butterfly pattern (bool)
crab (bool) : Flag to validate Crab pattern (bool)
shark (bool) : Flag to validate Shark pattern (bool)
cyph (bool) : Flag to validate Cypher pattern (bool)
Returns:
flag = true if valid harmonic
t1 = true if valid gartley
t2 = true if valid bat
t3 = true if valid butterfly
t4 = true if valid crab
t5 = true if valid shark
t6 = true if valid cypher
harmonic_xabcd_validateIncomplete(xX, xY, aX, aY, bX, bY, cX, cY, pErr, pAsym, gart, bat, bfly, crab, shark, cyph)
Validate the first 3 legs of a harmonic XABCD pattern
Parameters:
xX (int) : X coordinate of point X (int)
xY (float) : Y coordinate of point X (float)
aX (int) : X coordinate of point A (int)
aY (float) : Y coordinate of point A (float)
bX (int) : X coordinate of point B (int)
bY (float) : Y coordinate of point B (float)
cX (int) : X coordinate of point C (int)
cY (float) : Y coordinate of point C (float)
pErr (float) : Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
pAsym (float) : Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
gart (bool) : Flag to validate Gartley pattern (bool)
bat (bool) : Flag to validate Bat pattern (bool)
bfly (bool) : Flag to validate Butterfly pattern (bool)
crab (bool) : Flag to validate Crab pattern (bool)
shark (bool) : Flag to validate Shark pattern (bool)
cyph (bool) : Flag to validate Cypher pattern (bool)
Returns:
flag = true if valid harmonic
t1 = true if valid gartley
t2 = true if valid bat
t3 = true if valid butterfly
t4 = true if valid crab
t5 = true if valid shark
t6 = true if valid cypher
harmonic_xabcd_prz(type, xY, aY, bY, cY)
Get the potential reversal zone (PRZ) levels of a harmonic XABCD pattern
Parameters:
type (int) : Harmonic pattern type (int - 1 = Gartley, 2 = Bat, 3 = Butterfly, 4 = Crab, 5 = Shark, 6 = Cypher)
xY (float) : Y coordinate of point X (float)
aY (float) : Y coordinate of point A (float)
bY (float) : Y coordinate of point B (float)
cY (float) : Y coordinate of point C (float)
Returns:
bc_u = nearest BC retracement/extension level (nearest to point C)
bc_l = farthest BC retracement/extension level (nearest to point C)
xa_u = nearest XA retracement/extension level (or the only XA level, if applicable)
xa_l = farthest XA retracement/extension level (or na if not applicable)
harmonic_xabcd_przClosest(l1, l2, l3, l4)
Get the confluent PRZ levels (i.e. the two closest PRZ levels)
Order of arguments does not matter
Parameters:
l1 (float) : level 1 (float)
l2 (float) : level 2 (float)
l3 (float) : level 3 (float)
l4 (float) : level 4 (optional, float)
Returns:
lL = lower confluent PRZ level
lH = higher confluent PRZ level
harmonic_xabcd_przRange(l1, l2, l3, l4)
Get upper and lower PRZ levels
Parameters:
l1 (float)
l2 (float)
l3 (float)
l4 (float)
harmonic_xabcd_eD(cpl1, cpl2, xY, aY, dY)
Measure closeness of D to either of the two closest PRZ levels, relative to height of the XA leg
Parameters:
cpl1 (float)
cpl2 (float)
xY (float)
aY (float)
dY (float)
harmonic_xabcd_przScore(xY, aY, l1, l2, l3, l4)
Measure the closeness of the two closest PRZ levels, relative to the height of the XA leg
Parameters:
xY (float)
aY (float)
l1 (float)
l2 (float)
l3 (float)
l4 (float)
harmonic_xabcd_rAndE(type, l, l1, l2)
Get the ratio of two pattern legs, and the percent error from the theoretical harmonic ratio
Order of arguments does not matter
Parameters:
type (int) : Harmonic pattern type (int - 1 = Gartley, 2 = Bat, 3 = Butterfly, 4 = Crab)
l (string) : Leg ID ("xab", "abc", "bcd", or "xad") (string)
l1 (float) : Line 1 height (float)
l2 (float) : Line 2 height (float)
Returns:
harmonic_xabcd_eAvg(xbre, acre, bdre, xdre, xcdre)
Get the avg retracement ratio % error
Parameters:
xbre (float)
acre (float)
bdre (float)
xdre (float)
xcdre (float)
pat_xabcd_asym(xX, aX, bX, cX, dX)
Get the avg asymmetry %
Parameters:
xX (int)
aX (int)
bX (int)
cX (int)
dX (int)
harmonic_xabcd_entry(t, tp, xY, aY, bY, cY, dY, e_afterC, e_lvlc, e_afterD, e_lvldPct)
Get potential entry levels for a harmonic XABCD pattern
Parameters:
t (bool)
tp (int)
xY (float)
aY (float)
bY (float)
cY (float)
dY (float)
e_afterC (bool)
e_lvlc (string)
e_afterD (bool)
e_lvldPct (float)
xabcd_entryHit(t, afterC, afterD, dX, e_afterC, e_afterD, dValBars)
Determine if entry level was reached. Assumes pattern is active/not timed out.
Parameters:
t (bool)
afterC (float)
afterD (float)
dX (int)
e_afterC (bool)
e_afterD (bool)
dValBars (int)
pat_xabcd_validate(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, xab, abc, bcd, xad, xcd, pErr, pAsym)
Validate custom XABCD pattern
Parameters:
xX (int) : X coordinate of point X (int)
xY (float) : Y coordinate of point X (float)
aX (int) : X coordinate of point A (int)
aY (float) : Y coordinate of point A (float)
bX (int) : X coordinate of point B (int)
bY (float) : Y coordinate of point B (float)
cX (int) : X coordinate of point C (int)
cY (float) : Y coordinate of point C (float)
dX (int) : X coordinate of point D (int)
dY (float) : Y coordinate of point D (float)
xab (float)
abc (float)
bcd (float)
xad (float)
xcd (float)
pErr (float) : Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
pAsym (float) : Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
Returns: TRUE if pattern is valid
pat_xabcd_validateIncomplete(xX, xY, aX, aY, bX, bY, cX, cY, xab, abc, pErr, pAsym)
Validate the first 3 legs of a custom XABCD pattern
Parameters:
xX (int) : X coordinate of point X (int)
xY (float) : Y coordinate of point X (float)
aX (int) : X coordinate of point A (int)
aY (float) : Y coordinate of point A (float)
bX (int) : X coordinate of point B (int)
bY (float) : Y coordinate of point B (float)
cX (int) : X coordinate of point C (int)
cY (float) : Y coordinate of point C (float)
xab (float)
abc (float)
pErr (float) : Acceptable percent error of leg ratios (does not apply to legs defined within a range) (float)
pAsym (float) : Acceptable percent asymmetry of leg ΔX (each leg tested against average ΔX of prior legs) (float)
Returns: TRUE if first 3 legs are valid
pat_xabcd_prz(xY, aY, bY, cY, xad, bcd, xcd)
Get the potential reversal zone (PRZ) levels of a custom XABCD pattern
Parameters:
xY (float) : Y coordinate of point X (float)
aY (float) : Y coordinate of point A (float)
bY (float) : Y coordinate of point B (float)
cY (float) : Y coordinate of point C (float)
xad (float)
bcd (float)
xcd (float)
Returns:
pat_xabcd_avgDev(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY)
Get the average deviation of an XABCD pattern
Parameters:
xX (int)
xY (float)
aX (int)
aY (float)
bX (int)
bY (float)
cX (int)
cY (float)
dX (int)
dY (float)
harmonic_xabcd_score(tp, xX, xY, aX, aY, bX, bY, cX, cY, dX, dY)
Get score values for a pattern
Parameters:
tp (int)
xX (int)
xY (float)
aX (int)
aY (float)
bX (int)
bY (float)
cX (int)
cY (float)
dX (int)
dY (float)
harmonic_xabcd_scoreTot(asym, eavg, przscore, eD, tp, w_a, w_e, w_p, w_d)
Get total weighted score value for a pattern
Parameters:
asym (float)
eavg (float)
przscore (float)
eD (float)
tp (int)
w_a (float)
w_e (float)
w_p (float)
w_d (float)
harmonic_xabcd_targets(xY, aY, bY, cY, dY, tgt1, tgt2, tgt3)
Get target level
Parameters:
xY (float)
aY (float)
bY (float)
cY (float)
dY (float)
tgt1 (string)
tgt2 (string)
tgt3 (string)
harmonic_xabcd_stop(stop, stopPct, bull, xY, dY, upper, lower, t1, eY)
Get stop level
Parameters:
stop (string)
stopPct (float)
bull (bool)
xY (float)
dY (float)
upper (float)
lower (float)
t1 (float)
eY (float)
harmonic_xabcd_fibDispTxt(tp)
Get fib ratio display text
Parameters:
tp (int)
harmonic_xabcd_symbol(tp)
Get pattern symbol
Parameters:
tp (int)
pat_xabcd(x_is_low, pivot_length, source, conf_length, incomplete)
Determine if an XABCD pattern has just completed (i.e. point D is on the previous bar)
Parameters:
x_is_low (bool) : Flag to determine if point X is a low pivot, i.e. bullish pattern (bool, dft = true)
pivot_length (int) : Number of bars before and after a valid pivot (int, dft = 5)
source (float) : Source series (float, dft = na, will use high and low series)
conf_length (int) : Number of trailing bars after pivot point D to confirm a valid pattern (int, dft = 1)
incomplete (bool) : Flag to return an incomplete XABC pattern (bool, dft = false)
Returns:
flag = true if valid XABCD pattern completed on previous bar
xx = X coordinate of point X (int)
xy = Y coordinate of point X (float)
ax = X coordinate of point A (int)
ay = Y coordinate of point A (float)
bx = X coordinate of point B (int)
by = Y coordinate of point B (float)
cx = X coordinate of point C (int)
cy = Y coordinate of point C (float)
dx = X coordinate of point D (int)
dy = Y coordinate of point D (float)
pat_xabcdIncomplete(x_is_low, pivot_length, source, conf_length)
Determine if an XABCD pattern is in progress (point C was just confirmed)
Parameters:
x_is_low (bool) : Flag to determine if point X is a low pivot, i.e. bullish M pattern (bool, dft = true)
pivot_length (int) : Number of bars before and after a valid pivot (int, dft = 5)
source (float) : Source series (float, dft = na, will use high and low series)
conf_length (int) : Number of trailing bars after pivot point D to confirm a valid pattern (int, dft = 1)
Returns:
flag = true if valid XABC pattern completed on bar_index
xx = X coordinate of point X (int)
xy = Y coordinate of point X (float)
ax = X coordinate of point A (int)
ay = Y coordinate of point A (float)
bx = X coordinate of point B (int)
by = Y coordinate of point B (float)
cx = X coordinate of point C (int)
cy = Y coordinate of point C (float)
dx = X coordinate of point D (int)
dy = Y coordinate of point D (float)
success(eX, stop, t1, t2)
Determine if trade is successful
Parameters:
eX (int) : Entry bar index (int)
stop (float) : Stop level (float)
t1 (float) : Target 1 level (float)
t2 (float) : Target 2 level (float)
Returns:
tradeClosed(eX, eY, stop, t1h, t2h, t1, t2)
Determine if Target or Stop was hit on the current bar
Parameters:
eX (int)
eY (float)
stop (float)
t1h (bool)
t2h (bool)
t1 (float)
t2 (float)
TrigLibrary "Trig"
Trigonometric functions
rt_get_angleAlpha(a, b, c, deg)
Get angle α of a right triangle, given the lengths of its sides
Parameters:
a (float) : length of leg a (float)
b (float) : length of leg b (float)
c (float) : length of hypotenuse (float)
deg (simple bool) : flag to return angle in degrees (bool - default = false)
Returns: angle α in radians (or degrees if deg == true)
rt_get_angleAlphaFromLine(x1, y1, x2, y2, l, deg)
Get angle α of a right triangle formed by the given line
Parameters:
x1 (int) : x coordinate 1 (int - optional, required if argument l is not specified)
y1 (float) : y coordinate 1 (float - optional, required if argument l is not specified)
x2 (int) : x coordinate 2 (int - optional, required if argument l is not specified)
y2 (float) : y coordinate 2 (float - optional, required if argument l is not specified)
l (line) : line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
deg (simple bool) : flag to return angle in degrees (bool - default = false)
Returns: angle α in radians (or degrees if deg == true)
rt_get_angleBeta(a, b, c, deg)
Get angle β of a right triangle, given the lengths of its sides
Parameters:
a (float) : length of leg a (float)
b (float) : length of leg b (float)
c (float) : length of hypotenuse (float)
deg (simple bool) : flag to return angle in degrees (bool - default = false)
Returns: angle β in radians (or degrees if deg == true)
rt_get_angleBetaFromLine(x1, y1, x2, y2, l, deg)
Get angle β of a right triangle formed by the given line
Parameters:
x1 (int) : x coordinate 1 (int - optional, required if argument l is not specified)
y1 (float) : y coordinate 1 (float - optional, required if argument l is not specified)
x2 (int) : x coordinate 2 (int - optional, required if argument l is not specified)
y2 (float) : y coordinate 2 (float - optional, required if argument l is not specified)
l (line) : line object (line - optional, required if x1, y1, x2, and y2 agruments are not specified)
deg (simple bool) : flag to return angle in degrees (bool - default = false)
Returns: angle β in radians (or degrees if deg == true)
AlgebraLibrary "Algebra"
line_fromXy(x1, y1, x2, y2)
Get line slope and y-intercept from coordinates
Parameters:
x1 (int) : x coordinate 1 (int - bar index)
y1 (float) : y coordinate 1 (float - price/value)
x2 (int) : x coordinate 2 (int - bar index)
y2 (float) : y coordinate 2 (float - price/value)
Returns: of line
line_getPrice(x, slope, yInt)
Get price at X coordinate, given line slope and y-intercept
Parameters:
x (int) : x coordinate to solve for y (int - bar index)
slope (float) : slope of line (float)
yInt (float) : y-intercept of line (float)
Returns: y (price/value)
line_getPrice_fromXy(x, x1, y1, x2, y2)
Get price at X coordinate, given two points on a line
Parameters:
x (int) : x coordinate to solve for y (int - bar index)
x1 (int) : x coordinate 1 (int - bar index)
y1 (float) : y coordinate 1 (float - price/value)
x2 (int) : x coordinate 2 (int - bar index)
y2 (float) : y coordinate 2 (float - price/value)
Returns: y (price/value)
line_getRtSides(x1, y1, x2, y2, l)
Get length of sides of a right triangle formed by a given line
Parameters:
x1 (int) : x coordinate 1 (int - optional, required if argument l is not specified)
y1 (float) : y coordinate 1 (float - optional, required if argument l is not specified)
x2 (int) : x coordinate 2 (int - optional, required if argument l is not specified)
y2 (float) : y coordinate 2 (float - optional, required if argument l is not specified)
l (line) : line object (line - optional, required if x1, y1, x2, y2 agruments are not specified)
Returns:
line_length(x1, y1, x2, y2, l)
Get length of line, given a line object or two sets of coordinates
Parameters:
x1 (int) : x coordinate 1 (int - optional, required if argument l is not specified)
y1 (float) : y coordinate 1 (float - optional, required if argument l is not specified)
x2 (int) : x coordinate 2 (int - optional, required if argument l is not specified)
y2 (float) : y coordinate 2 (float - optional, required if argument l is not specified)
l (line) : line object (line - optional, required if x1, y1, x2, y2 agruments are not specified)
Returns: length of line (float)
FibonacciLibrary "Fibonacci"
General Fibonacci functions. Get fib numbers, ratios, etc.
fib_derived(f, precision)
Get the precise Fibonacci ratio, to the specified number of decimal places
Parameters:
f (float) : Fibonacci ratio (string, in form #.###)
precision (simple int) : Number of decimal places (optional int, dft = 16, max = 32)
Returns: Precise Fibonacci ratio (float)
* Deprecated (use fib_precise() instead), but keeping it here for science / experimenting with derivations
fib_precise(f, precision)
Get the precise Fibonacci ratio, to the specified number of decimal places
Parameters:
f (float) : Fibonacci ratio (string, in form #.###)
precision (simple int) : Number of decimal places (optional int, dft = 16, max = 16)
Returns: Precise Fibonacci ratio (float)
fib_from_string(r)
Get fib ratio value from string
Parameters:
r (string) : Fib ratio string (e.g. ".618")
Returns: Fibonacci ratio value (float)
fib_n(n)
Calculate the Nth number in the Fibonacci sequence
Parameters:
n (int) : Index/number in sequence (int)
Returns: Fibonacci number (int)
UtilitiesLibrary "Utilities"
General utilities
print_series(s, skip_na, position, show_index, from_index, to_index)
Print series values
Parameters:
s (string) : Series (string)
skip_na (simple bool) : Flag to skip na values (optional bool, dft = false)
position (simple string) : Position to print the Table (optional string, dft = position.bottom_center)
show_index (simple bool) : Flag to show series indices (optional bool, dft = true)
from_index (int) : First index to print (optional int, dft = 0)
to_index (int) : Last index to print (optional int, dft = last_bar_index)
Returns: Table object, if series was printed
print(v, position, at_index)
Print value
Parameters:
v (string) : Value (string)
position (simple string) : Position to print the Table (optional string, dft = position.bottom_center)
at_index (int) : Index at which to print (optional int, dft = bar_index)
Returns: Table object, if value was printed
print(v, position, at_index)
Print value
Parameters:
v (int) : Value (int)
position (simple string) : Position to print the Table (optional string, dft = position.bottom_center)
at_index (int) : Index at which to print (optional int, dft = bar_index)
Returns: Table object, if value was printed
print(v, position, at_index)
Print value
Parameters:
v (float) : Value (float)
position (simple string) : Position to print the Table (optional string, dft = position.bottom_center)
at_index (int) : Index at which to print (optional int, dft = bar_index)
Returns: Table object, if value was printed
print(v, position, at_index)
Print value
Parameters:
v (bool) : Value (bool)
position (simple string) : Position to print the Table (optional string, dft = position.bottom_center)
at_index (int) : Index at which to print (optional int, dft = bar_index)
Returns: Table object, if value was printed
boolToIntArr(a)
return array of offsets (int) of true values
Parameters:
a (array)
intToBoolArr(a, n)
Parameters:
a (array)
n (int)
LogNormalLibrary "LogNormal"
A collection of functions used to model skewed distributions as log-normal.
Prices are commonly modeled using log-normal distributions (ie. Black-Scholes) because they exhibit multiplicative changes with long tails; skewed exponential growth and high variance. This approach is particularly useful for understanding price behavior and estimating risk, assuming continuously compounding returns are normally distributed.
Because log space analysis is not as direct as using math.log(price) , this library extends the Error Functions library to make working with log-normally distributed data as simple as possible.
- - -
QUICK START
Import library into your project
Initialize model with a mean and standard deviation
Pass model params between methods to compute various properties
var LogNorm model = LN.init(arr.avg(), arr.stdev()) // Assumes the library is imported as LN
var mode = model.mode()
Outputs from the model can be adjusted to better fit the data.
var Quantile data = arr.quantiles()
var more_accurate_mode = mode.fit(model, data) // Fits value from model to data
Inputs to the model can also be adjusted to better fit the data.
datum = 123.45
model_equivalent_datum = datum.fit(data, model) // Fits value from data to the model
area_from_zero_to_datum = model.cdf(model_equivalent_datum)
- - -
TYPES
There are two requisite UDTs: LogNorm and Quantile . They are used to pass parameters between functions and are set automatically (see Type Management ).
LogNorm
Object for log space parameters and linear space quantiles .
Fields:
mu (float) : Log space mu ( µ ).
sigma (float) : Log space sigma ( σ ).
variance (float) : Log space variance ( σ² ).
quantiles (Quantile) : Linear space quantiles.
Quantile
Object for linear quantiles, most similar to a seven-number summary .
Fields:
Q0 (float) : Smallest Value
LW (float) : Lower Whisker Endpoint
LC (float) : Lower Whisker Crosshatch
Q1 (float) : First Quartile
Q2 (float) : Second Quartile
Q3 (float) : Third Quartile
UC (float) : Upper Whisker Crosshatch
UW (float) : Upper Whisker Endpoint
Q4 (float) : Largest Value
IQR (float) : Interquartile Range
MH (float) : Midhinge
TM (float) : Trimean
MR (float) : Mid-Range
- - -
TYPE MANAGEMENT
These functions reliably initialize and update the UDTs. Because parameterization is interdependent, avoid setting the LogNorm and Quantile fields directly .
init(mean, stdev, variance)
Initializes a LogNorm object.
Parameters:
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
set(ln, mean, stdev, variance)
Transforms linear measurements into log space parameters for a LogNorm object.
Parameters:
ln (LogNorm) : Object containing log space parameters.
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
quantiles(arr)
Gets empirical quantiles from an array of floats.
Parameters:
arr (array) : Float array object.
Returns: Quantile Object
- - -
DESCRIPTIVE STATISTICS
Using only the initialized LogNorm parameters, these functions compute a model's central tendency and standardized moments.
mean(ln)
Computes the linear mean from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
median(ln)
Computes the linear median from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
mode(ln)
Computes the linear mode from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
variance(ln)
Computes the linear variance from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
skewness(ln)
Computes the linear skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
kurtosis(ln, excess)
Computes the linear kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Kurtosis (true) or regular Kurtosis (false).
Returns: Between 0 and ∞
hyper_skewness(ln)
Computes the linear hyper skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
hyper_kurtosis(ln, excess)
Computes the linear hyper kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Hyper Kurtosis (true) or regular Hyper Kurtosis (false).
Returns: Between 0 and ∞
- - -
DISTRIBUTION FUNCTIONS
These wrap Gaussian functions to make working with model space more direct. Because they are contained within a log-normal library, they describe estimations relative to a log-normal curve, even though they fundamentally measure a Gaussian curve.
pdf(ln, x, empirical_quantiles)
A Probability Density Function estimates the probability density . For clarity, density is not a probability .
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate for which a density will be estimated.
empirical_quantiles (Quantile) : Quantiles as observed in the data (optional).
Returns: Between 0 and ∞
cdf(ln, x, precise)
A Cumulative Distribution Function estimates the area under a Log-Normal curve between Zero and a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ccdf(ln, x, precise)
A Complementary Cumulative Distribution Function estimates the area under a Log-Normal curve between a linear X coordinate and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
cdfinv(ln, a, precise)
An Inverse Cumulative Distribution Function reverses the Log-Normal cdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
ccdfinv(ln, a, precise)
An Inverse Complementary Cumulative Distribution Function reverses the Log-Normal ccdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
cdfab(ln, x1, x2, precise)
A Cumulative Distribution Function from A to B estimates the area under a Log-Normal curve between two linear X coordinates (A and B).
Parameters:
ln (LogNorm) : Object of log space parameters.
x1 (float) : First linear X coordinate .
x2 (float) : Second linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ott(ln, x, precise)
A One-Tailed Test transforms a linear X coordinate into an absolute Z Score before estimating the area under a Log-Normal curve between Z and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 0.5
ttt(ln, x, precise)
A Two-Tailed Test transforms a linear X coordinate into symmetrical ± Z Scores before estimating the area under a Log-Normal curve from Zero to -Z, and +Z to Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ottinv(ln, a, precise)
An Inverse One-Tailed Test reverses the Log-Normal ott() by estimating a linear X coordinate for the right tail from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Half a normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
tttinv(ln, a, precise)
An Inverse Two-Tailed Test reverses the Log-Normal ttt() by estimating two linear X coordinates from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Linear space tuple :
- - -
UNCERTAINTY
Model-based measures of uncertainty, information, and risk.
sterr(sample_size, fisher_info)
The standard error of a sample statistic.
Parameters:
sample_size (float) : Number of observations.
fisher_info (float) : Fisher information.
Returns: Between 0 and ∞
surprisal(p, base)
Quantifies the information content of a single event.
Parameters:
p (float) : Probability of the event .
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
entropy(ln, base)
Computes the differential entropy (average surprisal).
Parameters:
ln (LogNorm) : Object of log space parameters.
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
perplexity(ln, base)
Computes the average number of distinguishable outcomes from the entropy.
Parameters:
ln (LogNorm)
base (float) : Logarithmic base used for Entropy (optional).
Returns: Between 0 and ∞
value_at_risk(ln, p, precise)
Estimates a risk threshold under normal market conditions for a given confidence level.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
value_at_risk_inv(ln, value_at_risk, precise)
Reverses the value_at_risk() by estimating the confidence level from the risk threshold.
Parameters:
ln (LogNorm) : Object of log space parameters.
value_at_risk (float) : Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
conditional_value_at_risk(ln, p, precise)
Estimates the average loss beyond a confidence level, aka. expected shortfall.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_value_at_risk_inv(ln, conditional_value_at_risk, precise)
Reverses the conditional_value_at_risk() by estimating the confidence level of an average loss.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_value_at_risk (float) : Conditional Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
partial_expectation(ln, x, precise)
Estimates the partial expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and µ
partial_expectation_inv(ln, partial_expectation, precise)
Reverses the partial_expectation() by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
partial_expectation (float) : Partial Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_expectation(ln, x, precise)
Estimates the conditional expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between X and ∞
conditional_expectation_inv(ln, conditional_expectation, precise)
Reverses the conditional_expectation by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_expectation (float) : Conditional Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
fisher(ln, log)
Computes the Fisher Information Matrix for the distribution, not a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the distribution
fisher(ln, x, log)
Computes the Fisher Information Matrix for a linear X coordinate, not the distribution itself.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the linear X coordinate
confidence_interval(ln, x, sample_size, confidence, precise)
Estimates a confidence interval for a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
sample_size (float) : Number of observations.
confidence (float) : Confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: CI for the linear X coordinate
- - -
CURVE FITTING
An overloaded function that helps transform values between spaces. The primary function uses quantiles, and the overloads wrap the primary function to make working with LogNorm more direct.
fit(x, a, b)
Transforms X coordinate between spaces A and B.
Parameters:
x (float) : Linear X coordinate from space A .
a (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
b (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
Returns: Adjusted X coordinate
- - -
EXPORTED HELPERS
Small utilities to simplify extensibility.
z_score(ln, x)
Converts a linear X coordinate into a Z Score.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate.
Returns: Between -∞ and +∞
x_coord(ln, z)
Converts a Z Score into a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
z (float) : Standard normal Z Score.
Returns: Between 0 and ∞
iget(arr, index)
Gets an interpolated value of a pseudo -element (fictional element between real array elements). Useful for quantile mapping.
Parameters:
arr (array) : Float array object.
index (float) : Index of the pseudo element.
Returns: Interpolated value of the arrays pseudo element.
Min_Position_Size_ALLLibrary "Min_Position_Size_ALL"
getMinPositionSize(symbol_, type_, broker_)
Parameters:
symbol_ (string)
type_ (string)
broker_ (string)
ICOptimizerLibrary "ICOptimizer"
Library for IC-based parameter optimization
findOptimalParam(testParams, icValues, currentParam, smoothing)
Find optimal parameter from array of IC values
Parameters:
testParams (array) : Array of parameter values being tested
icValues (array) : Array of IC values for each parameter (same size as testParams)
currentParam (float) : Current parameter value (for smoothing)
smoothing (simple float) : Smoothing factor (0-1, e.g., 0.2 means 20% new, 80% old)
Returns: New parameter value, its IC, and array index
adaptiveParamWithStarvation(opt, testParams, icValues, smoothing, starvationThreshold, starvationJumpSize)
Adaptive parameter selection with starvation handling
Parameters:
opt (ICOptimizer) : ICOptimizer object
testParams (array) : Array of parameter values
icValues (array) : Array of IC values for each parameter
smoothing (simple float) : Normal smoothing factor
starvationThreshold (simple int) : Number of updates before triggering starvation mode
starvationJumpSize (simple float) : Jump size when in starvation (as fraction of range)
Returns: Updated parameter and IC
detectAndAdjustDomination(longCount, shortCount, currentLongLevel, currentShortLevel, dominationRatio, jumpSize, minLevel, maxLevel)
Detect signal imbalance and adjust parameters
Parameters:
longCount (int) : Number of long signals in period
shortCount (int) : Number of short signals in period
currentLongLevel (float) : Current long threshold
currentShortLevel (float) : Current short threshold
dominationRatio (simple int) : Ratio threshold (e.g., 4 = 4:1 imbalance)
jumpSize (simple float) : Size of adjustment
minLevel (simple float) : Minimum allowed level
maxLevel (simple float) : Maximum allowed level
Returns:
calcIC(signals, returns, lookback)
Parameters:
signals (float)
returns (float)
lookback (simple int)
classifyIC(currentIC, icWindow, goodPercentile, badPercentile)
Parameters:
currentIC (float)
icWindow (simple int)
goodPercentile (simple int)
badPercentile (simple int)
evaluateSignal(signal, forwardReturn)
Parameters:
signal (float)
forwardReturn (float)
updateOptimizerState(opt, signal, forwardReturn, currentIC, metaICPeriod)
Parameters:
opt (ICOptimizer)
signal (float)
forwardReturn (float)
currentIC (float)
metaICPeriod (simple int)
calcSuccessRate(successful, total)
Parameters:
successful (int)
total (int)
createICStatsTable(opt, paramName, normalSuccess, normalTotal)
Parameters:
opt (ICOptimizer)
paramName (string)
normalSuccess (int)
normalTotal (int)
initOptimizer(initialParam)
Parameters:
initialParam (float)
ICOptimizer
Fields:
currentParam (series float)
currentIC (series float)
metaIC (series float)
totalSignals (series int)
successfulSignals (series int)
goodICSignals (series int)
goodICSuccess (series int)
nonBadICSignals (series int)
nonBadICSuccess (series int)
goodICThreshold (series float)
badICThreshold (series float)
updateCounter (series int)
IC optimiser libLibrary "IC optimiser lib"
Library for IC-based parameter optimization
findOptimalParam(testParams, icValues, currentParam, smoothing)
Find optimal parameter from array of IC values
Parameters:
testParams (array) : Array of parameter values being tested
icValues (array) : Array of IC values for each parameter (same size as testParams)
currentParam (float) : Current parameter value (for smoothing)
smoothing (simple float) : Smoothing factor (0-1, e.g., 0.2 means 20% new, 80% old)
Returns: New parameter value, its IC, and array index
adaptiveParamWithStarvation(opt, testParams, icValues, smoothing, starvationThreshold, starvationJumpSize)
Adaptive parameter selection with starvation handling
Parameters:
opt (ICOptimizer) : ICOptimizer object
testParams (array) : Array of parameter values
icValues (array) : Array of IC values for each parameter
smoothing (simple float) : Normal smoothing factor
starvationThreshold (simple int) : Number of updates before triggering starvation mode
starvationJumpSize (simple float) : Jump size when in starvation (as fraction of range)
Returns: Updated parameter and IC
detectAndAdjustDomination(longCount, shortCount, currentLongLevel, currentShortLevel, dominationRatio, jumpSize, minLevel, maxLevel)
Detect signal imbalance and adjust parameters
Parameters:
longCount (int) : Number of long signals in period
shortCount (int) : Number of short signals in period
currentLongLevel (float) : Current long threshold
currentShortLevel (float) : Current short threshold
dominationRatio (simple int) : Ratio threshold (e.g., 4 = 4:1 imbalance)
jumpSize (simple float) : Size of adjustment
minLevel (simple float) : Minimum allowed level
maxLevel (simple float) : Maximum allowed level
Returns:
calcIC(signals, returns, lookback)
Parameters:
signals (float)
returns (float)
lookback (simple int)
classifyIC(currentIC, icWindow, goodPercentile, badPercentile)
Parameters:
currentIC (float)
icWindow (simple int)
goodPercentile (simple int)
badPercentile (simple int)
evaluateSignal(signal, forwardReturn)
Parameters:
signal (float)
forwardReturn (float)
updateOptimizerState(opt, signal, forwardReturn, currentIC, metaICPeriod)
Parameters:
opt (ICOptimizer)
signal (float)
forwardReturn (float)
currentIC (float)
metaICPeriod (simple int)
calcSuccessRate(successful, total)
Parameters:
successful (int)
total (int)
createICStatsTable(opt, paramName, normalSuccess, normalTotal)
Parameters:
opt (ICOptimizer)
paramName (string)
normalSuccess (int)
normalTotal (int)
initOptimizer(initialParam)
Parameters:
initialParam (float)
ICOptimizer
Fields:
currentParam (series float)
currentIC (series float)
metaIC (series float)
totalSignals (series int)
successfulSignals (series int)
goodICSignals (series int)
goodICSuccess (series int)
nonBadICSignals (series int)
nonBadICSuccess (series int)
goodICThreshold (series float)
badICThreshold (series float)
updateCounter (series int)
LIB_SDz_AucLibrary "LIB_SDz_Auc"
TODO: add library description here
getLineStyle(style)
Parameters:
style (string)
testLibLibrary "testLib"
TODO: add library description here
mySMA(x)
TODO: add function description here
Parameters:
x (int) : TODO: add parameter x description here
Returns: TODO: add what function returns
livremySMATestLibLibrary "livremySMATestLib"
TODO: add library description here
mySMA(x)
TODO: add function description here
Parameters:
x (int) : TODO: add parameter x description here
Returns: TODO: add what function returns
Material Color Palette Library█ OVERVIEW
Unlock a world of color in your Pine Script® projects with the Material Color Palette Library . This library provides a comprehensive and structured color system based on Google's Material Design palette, making it incredibly easy to create visually appealing and professional-looking indicators and strategies.
Forget about guessing hex codes. With this library, you have access to 19 distinct color families, each offering a wide range of shades. Every color can be fine-tuned with saturation, darkness, and opacity levels, giving you precise control over your script's appearance.
To make development even easier, the library includes a visual cheatsheet. Simply add the script to your chart to display a full table of all available colors and their corresponding parameters.
█ KEY FEATURES
Vast Spectrum: 19 distinct color families, from vibrant reds and blues to subtle greys and browns.
Fine-Tuned Control: Each color function accepts parameters for `saturationLevel` (1-13 or 1-9) and `darkLevel` (1-3) to select the perfect shade.
Opacity Parameter: Easily add transparency to any color for fills, backgrounds, or lines.
Quick Access Tones: A simple `tone()` function to grab base colors by name.
Visual Cheatsheet: An on-chart table displays the entire color palette, serving as a handy reference guide during development.
█ HOW TO USE
As a library, this script is meant to be imported into your own indicators or strategies.
1. Import the Library
Add the following line to the top of your script. Remember to replace `YourUsername` with your TradingView username.
import mastertop/ColorPalette/1 as colors
2. Call a Color Function
You can now use any of the exported functions to set colors for your plots, backgrounds, tables, and more.
The primary functions take three arguments: `functionName(saturationLevel, darkLevel, opacity)`
`saturationLevel`: An integer that controls the intensity of the color. Ranges from 1 (lightest) to 13 (most vibrant) for most colors, and 1-9 for `brown`, `grey`, and `blueGrey`.
`darkLevel`: An integer from 1 to 3 (1: light, 2: medium, 3: dark).
`opacity`: An integer from 0 (opaque) to 100 (invisible).
Example Usage:
Let's plot a moving average with a specific shade of teal.
// Import the library
import mastertop/ColorPalette/1 as colors
indicator("My Script with Custom Colors", overlay = true)
// Calculate a moving average
ma = ta.sma(close, 20)
// Plot the MA using a color from the library
// We'll use teal with saturation level 7, dark level 2, and 0% opacity
plot(ma, "MA", color = colors.teal(7, 2, 0), linewidth = 2)
3. Using the `tone()` Function
For quick access to a base color, you can use the `tone()` function.
// Set a red background with 85% transparency
bgcolor(colors.tone('red', 85))
█ VISUAL REFERENCE
To see all available colors at a glance, you can add this library script directly to your chart. It will display a comprehensive table showing every color variant. This makes it easy to pick the exact shade you need without guesswork.
This library is designed for fellow Pine Script® developers to streamline their workflow and enhance the visual quality of their scripts. Enjoy!
UTBotLibrary "UTBot"
is a powerful and flexible trading toolkit implemented in Pine Script. Based on the widely recognized UT Bot strategy originally developed by Yo_adriiiiaan with important enhancements by HPotter, this library provides users with customizable functions for dynamic trailing stop calculations using ATR (Average True Range), trend detection, and signal generation. It enables developers and traders to seamlessly integrate UT Bot logic into their own indicators and strategies without duplicating code.
Key features include:
Accurate ATR-based trailing stop and reversal detection
Multi-timeframe support for enhanced signal reliability
Clean and efficient API for easy integration and customization
Detailed documentation and examples for quick adoption
Open-source and community-friendly, encouraging collaboration and improvements
We sincerely thank Yo_adriiiiaan for the original UT Bot concept and HPotter for valuable improvements that have made this strategy even more robust. This library aims to honor their work by making the UT Bot methodology accessible to Pine Script developers worldwide.
This library is designed for Pine Script programmers looking to leverage the proven UT Bot methodology to build robust trading systems with minimal effort and maximum maintainability.
UTBot(h, l, c, multi, leng)
Parameters:
h (float) - high
l (float) - low
c (float)-close
multi (float)- multi for ATR
leng (int)-length for ATR
Returns:
xATRTS - ATR Based TrailingStop Value
pos - pos==1, long position, pos==-1, shot position
signal - 0 no signal, 1 buy, -1 sell
mt_elliott_coreLibrary "mt_elliott_core"
ewo(maFastLen, maSlowLen, smoothLen)
Parameters:
maFastLen (simple int)
maSlowLen (simple int)
smoothLen (simple int)
mt_phase_num(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
mt_color_from_phase(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
mt_phase_progress_pct(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
anchor_p1_close(len, minGap)
Parameters:
len (simple int)
minGap (simple float)
anchor_p1_pivot(len, minGap)
Parameters:
len (simple int)
minGap (simple float)
row_group_from_ewo(ewoValue, atrValue, strongPct, neutralPct)
Parameters:
ewoValue (float)
atrValue (float)
strongPct (simple float)
neutralPct (simple float)
wave_event_pivot_aligned(ewoSeries, left, right, divTolPct, minBarsGap)
Parameters:
ewoSeries (float)
left (simple int)
right (simple int)
divTolPct (simple float)
minBarsGap (simple int)
DynLenLibLibrary "DynLenLib"
sum_dyn(src, len)
Parameters:
src (float)
len (int)
lag_dyn(src, len)
Parameters:
src (float)
len (int)
highest_dyn(src, len)
Parameters:
src (float)
len (int)
lowest_dyn(src, len)
Parameters:
src (float)
len (int)
var_dyn(src, len)
Parameters:
src (float)
len (int)
stdev_dyn(src, len)
Parameters:
src (float)
len (int)
hl2()
hlc3()
ohlc4()
sma_dyn(src, len)
Parameters:
src (float)
len (int)
ema_dyn(src, len)
Parameters:
src (float)
len (int)
rma_dyn(src, len)
Parameters:
src (float)
len (int)
smma_dyn(src, len)
Parameters:
src (float)
len (int)
wma_dyn(src, len)
Parameters:
src (float)
len (int)
vwma_dyn(price, vol, len)
Parameters:
price (float)
vol (float)
len (int)
hma_dyn(src, len)
Parameters:
src (float)
len (int)
dema_dyn(src, len)
Parameters:
src (float)
len (int)
tema_dyn(src, len)
Parameters:
src (float)
len (int)
kama_dyn(src, erLen, fastLen, slowLen)
Parameters:
src (float)
erLen (int)
fastLen (int)
slowLen (int)
mcginley_dyn(src, len)
Parameters:
src (float)
len (int)
median_price()
true_range()
atr_dyn(len)
Parameters:
len (int)
bbands_dyn(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_percent_b(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_bandwidth(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
keltner_dyn(src, lenEMA, lenATR, multATR)
Parameters:
src (float)
lenEMA (int)
lenATR (int)
multATR (float)
donchian_dyn(len)
Parameters:
len (int)
choppiness_index(len)
Parameters:
len (int)
vol_stop(lenATR, mult)
Parameters:
lenATR (int)
mult (float)
roc_dyn(src, len)
Parameters:
src (float)
len (int)
rsi_dyn(src, len)
Parameters:
src (float)
len (int)
stoch_dyn(kLen, dLen, smoothK)
Parameters:
kLen (int)
dLen (int)
smoothK (int)
stoch_rsi_dyn(rsiLen, stochLen, kSmooth, dLen)
Parameters:
rsiLen (int)
stochLen (int)
kSmooth (int)
dLen (int)
cci_dyn(src, len)
Parameters:
src (float)
len (int)
cmo_dyn(src, len)
Parameters:
src (float)
len (int)
trix_dyn(len)
Parameters:
len (int)
tsi_dyn(shortLen, longLen)
Parameters:
shortLen (int)
longLen (int)
ultimate_osc(len1, len2, len3)
Parameters:
len1 (int)
len2 (int)
len3 (int)
dpo_dyn(src, len)
Parameters:
src (float)
len (int)
willr_dyn(len)
Parameters:
len (int)
macd_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
ppo_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
aroon_dyn(len)
Parameters:
len (int)
dmi_adx_dyn(diLen, adxLen)
Parameters:
diLen (int)
adxLen (int)
vortex_dyn(len)
Parameters:
len (int)
coppock_dyn(rocLen1, rocLen2, wmaLen)
Parameters:
rocLen1 (int)
rocLen2 (int)
wmaLen (int)
rvi_dyn(len)
Parameters:
len (int)
price_osc_dyn(src, fastLen, slowLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
rci_dyn(src, len)
Parameters:
src (float)
len (int)
obv()
pvt()
cmf_dyn(len)
Parameters:
len (int)
adl()
chaikin_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
mfi_dyn(len)
Parameters:
len (int)
volume_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
up_down_volume()
cvd()
supertrend_dyn(atrLen, mult)
Parameters:
atrLen (int)
mult (float)
envelopes_dyn(src, len, pct)
Parameters:
src (float)
len (int)
pct (float)
linreg_line_slope(src, len)
Parameters:
src (float)
len (int)
lsma_dyn(src, len)
Parameters:
src (float)
len (int)
corrcoef_dyn(a, b, len)
Parameters:
a (float)
b (float)
len (int)
psar(step, maxStep)
Parameters:
step (float)
maxStep (float)
pivots_standard()
williams_alligator(src, jawLen, teethLen, lipsLen)
Parameters:
src (float)
jawLen (int)
teethLen (int)
lipsLen (int)
twap_dyn(src, len)
Parameters:
src (float)
len (int)
vwap_anchored(price, volume, reset)
Parameters:
price (float)
volume (float)
reset (bool)
performance_pct(len)
Parameters:
len (int)
AlgebraGeometryLabLibrary "AlgebraGeometryLab"
Algebra & 2D geometry utilities absent from Pine built-ins.
Rigorous, no-repaint, export-ready: vectors, robust roots, linear solvers, 2x2/3x3 det/inverse,
symmetric 2x2 eigensystem, orthogonal regression (TLS), affine transforms, intersections,
distances, projections, polygon metrics, point-in-polygon, convex hull (monotone chain),
Bezier/Catmull-Rom/Barycentric tools.
clamp(x, lo, hi)
clamp to
Parameters:
x (float)
lo (float)
hi (float)
near(a, b, atol, rtol)
approximately equal with relative+absolute tolerance
Parameters:
a (float)
b (float)
atol (float)
rtol (float)
sgn(x)
sign as {-1,0,1}
Parameters:
x (float)
hypot(x, y)
stable hypot (sqrt(x^2+y^2))
Parameters:
x (float)
y (float)
method length(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method length2(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method normalized(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method add(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method sub(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method muls(v, s)
Namespace types: Vec2
Parameters:
v (Vec2)
s (float)
method dot(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method crossz(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method rotate(v, ang)
Namespace types: Vec2
Parameters:
v (Vec2)
ang (float)
method apply(v, T)
Namespace types: Vec2
Parameters:
v (Vec2)
T (Affine2)
affine_identity()
identity transform
affine_translate(tx, ty)
translation
Parameters:
tx (float)
ty (float)
affine_rotate(ang)
rotation about origin
Parameters:
ang (float)
affine_scale(sx, sy)
scaling about origin
Parameters:
sx (float)
sy (float)
affine_rotate_about(ang, px, py)
rotation about pivot (px,py)
Parameters:
ang (float)
px (float)
py (float)
affine_compose(T2, T1)
compose T2∘T1 (apply T1 then T2)
Parameters:
T2 (Affine2)
T1 (Affine2)
quadratic_roots(a, b, c)
Real roots of ax^2 + bx + c = 0 (numerically stable)
Parameters:
a (float)
b (float)
c (float)
Returns: with n∈{0,1,2}; r1<=r2 when n=2.
cubic_roots(a, b, c, d)
Real roots of ax^3+bx^2+cx+d=0 (Cardano; returns up to 3 real roots)
Parameters:
a (float)
b (float)
c (float)
d (float)
Returns: (valid r2/r3 only if n>=2/n>=3)
det2(a, b, c, d)
det2 of
Parameters:
a (float)
b (float)
c (float)
d (float)
inv2(a, b, c, d)
inverse of 2x2; returns
Parameters:
a (float)
b (float)
c (float)
d (float)
solve2(a, b, c, d, e, f)
solve 2x2 * = via Cramer
Parameters:
a (float)
b (float)
c (float)
d (float)
e (float)
f (float)
det3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
det3 of 3x3
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
inv3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
inverse 3x3; returns
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
eig2_symmetric(a, b, d)
symmetric 2x2 eigensystem: [ , ]
Parameters:
a (float)
b (float)
d (float)
Returns: with unit eigenvectors
tls_line(xs, ys)
Orthogonal (total least squares) regression line through point cloud
Input arrays must be same length N>=2. Returns line in normal form n•x + c = 0
Parameters:
xs (array)
ys (array)
Returns: where (nx,ny) unit normal; (cx,cy) centroid.
orient(a, b, c)
orientation (signed area*2): >0 CCW, <0 CW, 0 collinear
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
project_point_line(p, a, d)
project point p onto infinite line through a with direction d
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
Returns: where proj = a + t*d
closest_point_segment(p, a, b)
closest point on segment to p
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
Returns: where t∈ on segment
dist_point_line(p, a, d)
distance from point to line (infinite)
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
dist_point_segment(p, a, b)
distance from point to segment
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
intersect_lines(p1, d1, p2, d2)
line-line intersection: L1: p1+d1*t, L2: p2+d2*u
Parameters:
p1 (Vec2)
d1 (Vec2)
p2 (Vec2)
d2 (Vec2)
Returns:
intersect_segments(s1, s2)
segment-segment intersection (closed segments)
Parameters:
s1 (Segment2)
s2 (Segment2)
Returns: where kind: 0=no, 1=proper point, 2=overlap (ix/iy=na)
circumcircle(a, b, c)
circle through 3 non-collinear points
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
intersect_circle_line(C, p, d)
intersections of circle and line (param p + d t)
Parameters:
C (Circle2)
p (Vec2)
d (Vec2)
Returns: with n∈{0,1,2}
intersect_circles(A, B)
circle-circle intersection
Parameters:
A (Circle2)
B (Circle2)
Returns: with n∈{0,1,2}
polygon_area(xs, ys)
signed area (shoelace). Positive if CCW.
Parameters:
xs (array)
ys (array)
polygon_centroid(xs, ys)
polygon centroid (for non-self-intersecting). Fallback to vertex mean if area≈0.
Parameters:
xs (array)
ys (array)
point_in_polygon(px, py, xs, ys)
point-in-polygon test (ray casting). Returns true if inside; boundary counts as inside.
Parameters:
px (float)
py (float)
xs (array)
ys (array)
convex_hull(xs, ys)
convex hull (monotone chain). Returns array of hull vertex indices in CCW order.
Uses array.sort_indices(xs) (ascending by x). Ties on x are handled; result is deterministic.
Parameters:
xs (array)
ys (array)
lerp(a, b, t)
linear interpolate between a and b
Parameters:
a (float)
b (float)
t (float)
bezier2(p0, p1, p2, t)
quadratic Bezier B(t) for points p0,p1,p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
t (float)
bezier3(p0, p1, p2, p3, t)
cubic Bezier B(t) for p0,p1,p2,p3
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
catmull_rom(p0, p1, p2, p3, t, alpha)
Catmull-Rom interpolation (centripetal form when alpha=0.5)
t∈ , returns point between p1 and p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
alpha (float)
barycentric(A, B, C, P)
barycentric coordinates of P wrt triangle ABC
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Returns:
point_in_triangle(A, B, C, P)
point-in-triangle using barycentric (boundary included)
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Vec2
Fields:
x (series float)
y (series float)
Line2
Fields:
p (Vec2)
d (Vec2)
Segment2
Fields:
a (Vec2)
b (Vec2)
Circle2
Fields:
c (Vec2)
r (series float)
Affine2
Fields:
a (series float)
b (series float)
c (series float)
d (series float)
tx (series float)
ty (series float)
ema 狀態機Library "ema_flow_lib"
ema_flow_state(e10, e20, e100, entanglePct, farPct, e10_prev, e20_prev)
Parameters:
e10 (float)
e20 (float)
e100 (float)
entanglePct (float)
farPct (float)
e10_prev (float)
e20_prev (float)
state_name(s)
Parameters:
s (int)






















