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)
Indikator dan strategi
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)
phx_liq_tlLibrary "phx_liq_tl"
new_state()
update(st, len, cup, cdn, space, proximity_pct, shs)
โโParameters:
โโโโ st (LTState)
โโโโ len (int)
โโโโ cup (color)
โโโโ cdn (color)
โโโโ space (float)
โโโโ proximity_pct (float)
โโโโ shs (bool)
LTState
โโFields:
โโโโ upln (array)
โโโโ dnln (array)
โโโโ upBroken (series bool)
โโโโ dnBroken (series bool)
phx_kroLibrary "phx_kro"
compute(src, bandwidth, bbwidth, sdLook, sdMult, obos_mult)
โโParameters:
โโโโ src (float)
โโโโ bandwidth (int)
โโโโ bbwidth (float)
โโโโ sdLook (int)
โโโโ sdMult (float)
โโโโ obos_mult (float)
start_flags(src, bandwidth, bbwidth)
โโParameters:
โโโโ src (float)
โโโโ bandwidth (int)
โโโโ bbwidth (float)
KROFeed
โโFields:
โโโโ Wave (series float)
โโโโ is_green (series bool)
โโโโ is_red (series bool)
โโโโ band_width (series float)
โโโโ band_width_sma (series float)
โโโโ band_width_std (series float)
โโโโ is_hyper_wide (series bool)
โโโโ wave_sma (series float)
โโโโ wave_std (series float)
โโโโ wave_ob_threshold (series float)
โโโโ wave_os_threshold (series float)
โโโโ is_overbought (series bool)
โโโโ is_oversold (series bool)
โโโโ is_oversold_confirmed (series bool)
โโโโ is_overbought_confirmed (series bool)
โโโโ enhanced_os_confirmed (series bool)
โโโโ enhanced_ob_confirmed (series bool)
โโโโ triple_green_transition (series bool)
โโโโ triple_red_transition (series bool)
โโโโ startwave_bull (series bool)
โโโโ startwave_bear (series bool)
phx_fvgfvg generator 4h and current time frame
library to import fvg from 4h with midle line and proximity support and resistance
JK_Traders_Reality_LibLibrary "JK_Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
โโcalculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
โโParameters:
โโโโ pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
โโโโ pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
โโโโ pvsraLow (float) : the instrument low series (obtained from request.sequrity)
โโโโ pvsraClose (float) : the instrument close series (obtained from request.sequrity)
โโโโ pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
โโโโ redVectorColor (simple color) : red vector candle color
โโโโ greenVectorColor (simple color) : green vector candle color
โโโโ violetVectorColor (simple color) : violet/pink vector candle color
โโโโ blueVectorColor (simple color) : blue vector candle color
โโโโ darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
โโโโ lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
โโParameters:
โโโโ length (simple int) : how many elements of the series to calculate on
โโโโ barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
โโCalculate the ADR high given an ADR
โโParameters:
โโโโ adr (float) : the adr
โโโโ fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
โโParameters:
โโโโ adr (float) : the adr
โโโโ fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
โโgiven a session in the format 0000-0100:23456 split out the hours and minutes
โโParameters:
โโโโ sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
โโcalculate the start and end timestamps of the session
โโParameters:
โโโโ sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
โโโโ gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
โโdraw open range for a session
โโParameters:
โโโโ sessXTime (simple string) : session string in the format 0000-0100:23456
โโโโ sessXcol (simple color) : the color to be used for the opening range box shading
โโโโ showOrX (simple bool) : boolean flag to toggle displaying the opening range
โโโโ gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
โโParameters:
โโโโ sessXTime (simple string) : session string in the format 0000-0100:23456
โโโโ showRectangleX (simple bool)
โโโโ showLabelX (simple bool)
โโโโ sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
โโโโ sessXLabel (simple string) : the session label text
โโโโ gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
โโโโ sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
calcDst()
โโcalculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
โโTimestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
โโParameters:
โโโโ previousDayOfWeek (simple string) : Monday or Satruday
โโโโ hourOfDay (simple int) : the hour of the day when psy calc is to start
โโโโ gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
โโโโ oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
โโget the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
โโnew_bar: check if we're on a new bar within the session in a given resolution
โโParameters:
โโโโ res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
โโto_pips Convert value to pips
โโParameters:
โโโโ val (float) : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
โโa function that draws a right aligned lable for a series during the current bar
โโParameters:
โโโโ ry (float) : series float the y coordinate of the lable
โโโโ rtext (simple string) : the text of the label
โโโโ rstyle (simple string) : the style for the lable
โโโโ rcolor (simple color) : the color for the label
โโโโ valid (simple bool) : a boolean flag that allows for turning on or off a lable
โโโโ labelXOffset (int) : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset)
โโa function that draws a right aligned lable for a series during the current bar
โโParameters:
โโโโ ry (float) : series float the y coordinate of the lable
โโโโ rtext (string) : the text of the label
โโโโ rstyle (simple string) : the style for the lable
โโโโ rcolor (simple color) : the color for the label
โโโโ valid (simple bool) : a boolean flag that allows for turning on or off a lable
โโโโ labelOffset (int)
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
โโa function that draws a right aligned lable for a series only on the last bar
โโParameters:
โโโโ ry (float) : series float the y coordinate of the lable
โโโโ rtext (string) : the text of the label
โโโโ rstyle (simple string) : the style for the lable
โโโโ rcolor (simple color) : the color for the label
โโโโ valid (simple bool) : a boolean flag that allows for turning on or off a lable
โโโโ labelXOffset (int) : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
โโa function that draws a line and a label for a series
โโParameters:
โโโโ xSeries (float) : series float the y coordinate of the line/label
โโโโ res (simple string) : the desired resolution controlling when a new line will start
โโโโ tag (simple string) : the text for the lable
โโโโ xColor (simple color) : the color for the label
โโโโ xStyle (simple string) : the style for the line
โโโโ xWidth (simple int) : the width of the line
โโโโ xExtend (simple string) : extend the line
โโโโ isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
โโโโ xLabelOffset (int)
โโโโ validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
โโa function that draws a line and a label for the daily open series
โโParameters:
โโโโ xSeries (float) : series float the y coordinate of the line/label
โโโโ res (simple string) : the desired resolution controlling when a new line will start
โโโโ tag (simple string) : the text for the lable
โโโโ xColor (simple color) : the color for the label
โโโโ xStyle (simple string) : the style for the line
โโโโ xWidth (simple int) : the width of the line
โโโโ xExtend (simple string) : extend the line
โโโโ isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
โโโโ xLabelOffset (int)
โโโโ validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
โโdraw a pivot line - the line starts one day into the past
โโParameters:
โโโโ pivotLevel (float) : series of the pivot point
โโโโ res (simple string) : the desired resolution
โโโโ tag (simple string) : the text to appear
โโโโ pivotColor (simple color) : the color of the line
โโโโ pivotLabelColor (simple color) : the color of the label
โโโโ pivotStyle (simple string) : the line style
โโโโ pivotWidth (simple int) : the line width
โโโโ pivotExtend (simple string) : extend the line
โโโโ isLabelValid (simple bool) : boolean param allows to turn label on and off
โโโโ validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
โโโโ levelStart (int) : basically when to start drawing the levels
โโโโ pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
โโconvert the pvsra color to an internal code
โโParameters:
โโโโ pvsraColor (color) : the calculated pvsra color
โโโโ redVectorColor (simple color) : the user defined red vector color
โโโโ greenVectorColor (simple color) : the user defined green vector color
โโโโ violetVectorColor (simple color) : the user defined violet vector color
โโโโ blueVectorColor (simple color) : the user defined blue vector color
โโโโ lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
โโa function that draws the unrecovered vector candle zones
โโParameters:
โโโโ pvsra (int) : internal code
โโโโ direction (simple int) : above or below the current pa
โโโโ boxArr (array) : the array containing the boxes that need to be updated
โโโโ maxlevels (simple int) : the maximum number of boxes to draw
โโโโ pvsraHigh (float) : the pvsra high value series
โโโโ pvsraLow (float) : the pvsra low value series
โโโโ pvsraOpen (float) : the pvsra open value series
โโโโ pvsraClose (float) : the pvsra close value series
โโโโ transperancy (simple int) : the transparencfy of the vecor candle zones
โโโโ zoneupdatetype (simple string) : the zone update type
โโโโ zonecolor (simple color) : the zone color if overriden
โโโโ zonetype (simple string) : the zone type
โโโโ borderwidth (simple int) : the width of the border
โโโโ coloroverride (simple bool) : if the color overriden
โโโโ redVectorColor (simple color) : the user defined red vector color
โโโโ greenVectorColor (simple color) : the user defined green vector color
โโโโ violetVectorColor (simple color) : the user defined violet vector color
โโโโ blueVectorColor (simple color) : the user defined blue vector color
cleanarr(arr)
โโclean an array from na values
โโParameters:
โโโโ arr (array) : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
โโcalculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
โโParameters:
โโโโ oneWeekMillis (simple int) : a constant value
โโโโ showPsylevels (simple bool) : should psy levels be calculated
โโโโ psyType (simple string) : the type of Psylevels - crypto or forex
โโโโ sydDST (bool) : is Sydney in DST
@return
adrHiLo(length, barsBack, fromDO)
โโParameters:
โโโโ length (simple int) : how many elements of the series to calculate on
โโโโ barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
โโโโ fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh - the adr, the position of the adr High and adr Low with respect to price
drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol)
โโParameters:
โโโโ sessXTime (simple string) : session string in the format 0000-0100:23456
โโโโ showRectangleX (simple bool)
โโโโ showLabelX (simple bool)
โโโโ sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
โโโโ sessXLabel (simple string) : the session label text
โโโโ gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
โโโโ sessionLineStyle (simple string) : the line stile for the session high low lines
โโโโ sessXcol (simple color) : - the color for the box color that will color the session
@return void
msToHmsString(ms)
โโconverts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
โโParameters:
โโโโ ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
countdownString(openToday, closeToday, showMarketsWeekends, oneDay)
โโthat calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
โโParameters:
โโโโ openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
โโโโ closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
โโโโ showMarketsWeekends (simple bool)
โโโโ oneDay (simple int)
countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay)
โโthat calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
โโParameters:
โโโโ sydOpenToday (int)
โโโโ sydCloseToday (int)
โโโโ showMarketsWeekends (simple bool)
โโโโ oneDay (simple int)
Market Structure Report Library [TradingFinder]๐ต Introduction
Market Structure is one of the most fundamental concepts in Price Action and Smart Money theory. In simple terms, it represents how price moves between highs and lows and reveals which phase of the market cycle we are currently in uptrend, downtrend, or transition.
Each structure in the market is formed by a combination of Breaks of Structure (BoS) and Changes of Character (CHoCH) :
BoS occurs when the market breaks a previous high or low, confirming the continuation of the current trend.
CHoCH occurs when price breaks in the opposite direction for the first time, signaling a potential trend reversal.
Since price movement is inherently fractal, market structure can be analyzed on two distinct levels :
Major / External Structure: represents the dominant macro trend.
Minor / Internal Structure: represents corrective or smaller-scale movements within the larger trend.
๐ต Library Purpose
The โMarket Structure Report Libraryโ is designed to automatically detect the current market structure type in real time.
Without drawing or displaying any visuals, it analyzes raw price data and returns a series of logical and textual outputs (Return Values) that describe the current structural state of the market.
It provides the following information :
Trend Type :
External Trend (Major): Up Trend, Down Trend, No Trend
Internal Trend (Minor): Up Trend, Down Trend, No Trend
Structure Type :
BoS : Confirms trend continuation
CHoCH : Indicates a potential trend reversal
Consecutive BoS Counter : Measures trend strength on both Major and Minor levels.
Candle Type : Returns the current candleโs condition(Bullish, Bearish, Doji)
This library is specifically designed for use in Smart Moneyโbased screeners, indicators, and algorithmic strategies.
It can analyze multiple symbols and timeframes simultaneously and return the exact structure type (BoS or CHoCH) and trend direction for each.
๐ต Function Outputs
The function MS() processes the price data and returns seven key outputs,
each representing a distinct structural state of the market. These values can be used in indicators, strategies, or multi-symbol screeners.
๐ฃ ExternalTrend
Type : string
Description : Represents the direction of the Major (External) market structure.
Possible values :
Up Trend
Down Trend
No Trend
This is determined based on the behavior of Major Pivots (swing highs/lows).
๐ฃ InternalTrend
Type : string
Description : Represents the direction of the Minor (Internal) market structure.
Possible values :
Up Trend
Down Trend
No Trend
๐ฃ M_State
Type : string
Description : Specifies the type of the latest Major Structure event.
Possible values :
BoS
CHoCH
๐ฃ m_State
Type : string
Description : Specifies the type of the latest Minor Structure event.
Possible values :
BoS
CHoCH
๐ฃ MBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks (BoS) in the Major structure.
Useful for evaluating trend strength :
Increasing count: indicates trend continuation.
Reset to zero: typically occurs after a CHoCH.
๐ฃ mBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks in the Minor structure.
Helps analyze the micro structure of the market on lower timeframes.
Higher value : strong internal trend.
Reset : indicates a minor pullback or reversal.
๐ฃ Candle_Type
Type : string
Description : Represents the type of the current candle.
Possible values :
Bullish
Bearish
Doji
import TFlab/Market_Structure_Report_Library_TradingFinder/1 as MSS
PP = input.int (5 , 'Market Structure Pivot Period' , group = 'Symbol 1' )
= MSS.MS(PP)
SequencerLibraryLibrary "SequencerLibrary"
SequencerLibrary v1 is a Pine Scriptโข library for identifying, tracking, and visualizing
sequential bullish and bearish patterns on price charts.
It provides a complete framework for building sequence-based trading systems, including:
โข Automatic detection and counting of setup and countdown phases.
โข Real-time tracking of completion states, perfected setups, and exhaustion signals.
โข Dynamic support and resistance thresholds derived from recent price structure.
โข Customizable visual highlighting for both setup and countdown sequences.
method doSequence(s, src, config, condition)
โโUpdates the sequence state based on the source value, and user configuration.
โโNamespace types: Sequence
โโParameters:
โโโโ s (Sequence) : The sequence object containing bullish and bearish setups.
โโโโ src (float) : The source value (e.g., close price) used for evaluating sequence conditions.
โโโโ config (SequenceInputs) : The user-defined settings for sequence analysis.
โโโโ condition (bool) : When true, executes the sequence logic.
โโReturns:
highlight(s, css, condition)
โโHighlights the bullish and bearish sequence setups and countdowns on the chart.
โโParameters:
โโโโ s (Sequence) : The sequence object containing bullish and bearish sequence states.
โโโโ css (SequenceCSS) : The styling configuration for customizing label appearances.
โโโโ condition (bool) : When true, the function creates and displays labels for setups and countdowns.
โโReturns:
SequenceState
โโA type representing the configuration and state of a sequence setup.
โโFields:
โโโโ setup (series int) : Current count of the setup phase (e.g., how many bars have met the setup criteria).
โโโโ countdown (series int) : Current count of the countdown phase (e.g., bars meeting countdown criteria).
โโโโ threshold (series float) : The price threshold level used as support/resistance for the sequence.
โโโโ priceWhenCompleted (series float) : The closing price when the setup or countdown phase is completed.
โโโโ indicatorWhenCompleted (series float) : The indicator value when the setup or countdown phase is completed.
โโโโ setupCompleted (series bool) : Indicates if the setup phase has been completed (i.e., reached the required count).
โโโโ countdownCompleted (series bool) : Indicates if the countdown phase has been completed (i.e., reached exhaustion).
โโโโ perfected (series bool) : Indicates if the setup meets the "perfected" condition (e.g., aligns with strict criteria).
โโโโ highlightSetup (series bool) : Determines whether the setup phase should be visually highlighted on the chart.
โโโโ highlightCountdown (series bool) : Determines whether the countdown phase should be visually highlighted on the chart.
Sequence
โโA type containing bullish and bearish sequence setups.
โโFields:
โโโโ bullish (SequenceState) : Configuration and state for bullish sequences.
โโโโ bearish (SequenceState) : Configuration and state for bearish sequences.
SequenceInputs
โโA type for user-configurable input settings for sequence-based analysis.
โโFields:
โโโโ showSetup (series bool) : Enables or disables the display of setup sequences.
โโโโ showCountdown (series bool) : Enables or disables the display of countdown sequences.
โโโโ setupFilter (series string) : A commaโseparated string containing setup sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9").
โโโโ countdownFilter (series string) : A commaโseparated string containing countdown sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9,10,11,12,13").
โโโโ lookbackSetup (series int) : Defines the lookback period for evaluating setup conditions (default: 4 bars).
โโโโ lookbackCountdown (series int) : Defines the lookback period for evaluating countdown conditions (default: 2 bars).
โโโโ lookbackSetupPerfected (series int) : Defines the lookback period to determine a perfected setup condition (default: 6 bars).
โโโโ maxSetup (series int) : The maximum count required to complete a setup phase (default: 9).
โโโโ maxCountdown (series int) : The maximum count required to complete a countdown phase (default: 13).
SequenceCSS
โโA type defining the visual styling options for sequence labels.
โโFields:
โโโโ bullish (series color) : Color used for bullish sequence labels.
โโโโ bearish (series color) : Color used for bearish sequence labels.
โโโโ imperfect (series color) : Color used for labels representing imperfect sequences.
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_moving_average_source(_source, _length, _ma_type)
โโgbb_moving_average_source
@description Calculates the moving average of a source series.
โโParameters:
โโโโ _source (float) : (series float)
โโโโ _length (simple int) : (int)
โโโโ _ma_type (string) : (string)
โโReturns: (series) Moving average series
gbb_tf_to_display(tf_minutes, tf_string)
โโgbb_tf_to_display
@description Converts minutes and TF string into a short standard label.
โโParameters:
โโโโ tf_minutes (float) : (float)
โโโโ tf_string (string) : (string)
โโReturns: (string) Timeframe label (M1,H1,D1,...)
gbb_convert_bars(_bars)
โโgbb_convert_bars
@description Formats a number of bars into a duration (days, hours, minutes + bar count).
โโParameters:
โโโโ _bars (int) : (int)
โโReturns: (string)
gbb_goldorak_init(_tf5Levels_input)
โโgbb_goldorak_init
@description Builds a contextual message about the current timeframe and optional 5-level TF.
โโParameters:
โโโโ _tf5Levels_input (string) : (string) Alternative timeframe ("" = current timeframe).
โโReturns: (string, string, float)
CarolTradeLibLibrary "CarolTradeLib"
f_generateSignalID(strategyName)
โโParameters:
โโโโ strategyName (string)
f_buildJSON(orderType, action, symbol, price, strategyName, apiKey, additionalFields, indicatorJSON)
โโParameters:
โโโโ orderType (string)
โโโโ action (string)
โโโโ symbol (string)
โโโโ price (float)
โโโโ strategyName (string)
โโโโ apiKey (string)
โโโโ additionalFields (string)
โโโโ indicatorJSON (string)
sendSignal(action, symbol, price, strategyName, apiKey, indicatorJSON)
โโParameters:
โโโโ action (string)
โโโโ symbol (string)
โโโโ price (float)
โโโโ strategyName (string)
โโโโ apiKey (string)
โโโโ indicatorJSON (string)
marketOrder(action, symbol, price, strategyName, apiKey, stopLoss, takeProfit, rrRatio, size, indicatorJSON)
โโParameters:
โโโโ action (string)
โโโโ symbol (string)
โโโโ price (float)
โโโโ strategyName (string)
โโโโ apiKey (string)
โโโโ stopLoss (float)
โโโโ takeProfit (float)
โโโโ rrRatio (float)
โโโโ size (float)
โโโโ indicatorJSON (string)
limitOrder(action, symbol, price, strategyName, apiKey, limitPrice, size, indicatorJSON)
โโParameters:
โโโโ action (string)
โโโโ symbol (string)
โโโโ price (float)
โโโโ strategyName (string)
โโโโ apiKey (string)
โโโโ limitPrice (float)
โโโโ size (float)
โโโโ indicatorJSON (string)
stopLimitOrder(action, symbol, price, strategyName, apiKey, stopPrice, limitPrice, size, indicatorJSON)
โโParameters:
โโโโ action (string)
โโโโ symbol (string)
โโโโ price (float)
โโโโ strategyName (string)
โโโโ apiKey (string)
โโโโ stopPrice (float)
โโโโ limitPrice (float)
โโโโ size (float)
โโโโ indicatorJSON (string)
TrailingStopLossLibrary "TrailingStopLoss"
็ฎๆ่ฟฝ่ธชๆญขๆ๏ผ ๆชๅ
ๅๆต่ฏ๏ผๆฌข่ฟๆไบคissue
drawdown_percent(entry_bar_index, direction_long)
โโdrawdown_percent: ๅๆค็พๅๆฏ
โโParameters:
โโโโ entry_bar_index (int)
โโโโ direction_long (bool)
โโReturns: percentage: ๅๆค็พๅๆฏ > 0
closure_needed(entry_bar_index, initial_sl_price, percentage_ts, num_bars_tolerance, extra_drawdown_distance)
โโclosure_needed: ๆฏๅฆๆปก่ถณๅนณไปๆกไปถ
โโParameters:
โโโโ entry_bar_index (int)
โโโโ initial_sl_price (float)
โโโโ percentage_ts (float)
โโโโ num_bars_tolerance (int)
โโโโ extra_drawdown_distance (float)
โโReturns: do_closure: bool ๆฏๅฆๅนณไป
PubLibPivotLibrary "PubLibPivot"
Pivot detection library for harmonic pattern analysis - Fractal and ZigZag methods with validation and utility functions
fractalPivotHigh(depth)
โโFractal pivot high condition
โโParameters:
โโโโ depth (int)
โโReturns: bool
fractalPivotLow(depth)
โโFractal pivot low condition
โโParameters:
โโโโ depth (int)
โโReturns: bool
fractalPivotHighPrice(depth, occurrence)
โโGet fractal pivot high price
โโParameters:
โโโโ depth (int)
โโโโ occurrence (simple int)
โโReturns: float
fractalPivotLowPrice(depth, occurrence)
โโGet fractal pivot low price
โโParameters:
โโโโ depth (int)
โโโโ occurrence (simple int)
โโReturns: float
fractalPivotHighBarIndex(depth, occurrence)
โโGet fractal pivot high bar index
โโParameters:
โโโโ depth (int)
โโโโ occurrence (simple int)
โโReturns: int
fractalPivotLowBarIndex(depth, occurrence)
โโGet fractal pivot low bar index
โโParameters:
โโโโ depth (int)
โโโโ occurrence (simple int)
โโReturns: int
zigzagPivotHigh(deviation, backstep, useATR, atrLength)
โโZigZag pivot high condition
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโReturns: bool
zigzagPivotLow(deviation, backstep, useATR, atrLength)
โโZigZag pivot low condition
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโReturns: bool
zigzagPivotHighPrice(deviation, backstep, useATR, atrLength, occurrence)
โโGet ZigZag pivot high price
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโโโ occurrence (simple int)
โโReturns: float
zigzagPivotLowPrice(deviation, backstep, useATR, atrLength, occurrence)
โโGet ZigZag pivot low price
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโโโ occurrence (simple int)
โโReturns: float
zigzagPivotHighBarIndex(deviation, backstep, useATR, atrLength, occurrence)
โโGet ZigZag pivot high bar index
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโโโ occurrence (simple int)
โโReturns: int
zigzagPivotLowBarIndex(deviation, backstep, useATR, atrLength, occurrence)
โโGet ZigZag pivot low bar index
โโParameters:
โโโโ deviation (float)
โโโโ backstep (int)
โโโโ useATR (bool)
โโโโ atrLength (simple int)
โโโโ occurrence (simple int)
โโReturns: int
isValidPivotVolume(pivotPrice, pivotBarIndex, minVolumeRatio, volumeLength)
โโValidate pivot quality based on volume
โโParameters:
โโโโ pivotPrice (float)
โโโโ pivotBarIndex (int)
โโโโ minVolumeRatio (float)
โโโโ volumeLength (int)
โโReturns: bool
isValidPivotATR(pivotPrice, lastPivotPrice, minATRMultiplier, atrLength)
โโValidate pivot based on minimum ATR movement
โโParameters:
โโโโ pivotPrice (float)
โโโโ lastPivotPrice (float)
โโโโ minATRMultiplier (float)
โโโโ atrLength (simple int)
โโReturns: bool
isValidPivotTime(pivotBarIndex, lastPivotBarIndex, minBars)
โโValidate pivot based on minimum time between pivots
โโParameters:
โโโโ pivotBarIndex (int)
โโโโ lastPivotBarIndex (int)
โโโโ minBars (int)
โโReturns: bool
isPivotConfirmed(pivotBarIndex, depth)
โโCheck if pivot is not repainting (confirmed)
โโParameters:
โโโโ pivotBarIndex (int)
โโโโ depth (int)
โโReturns: bool
addPivotToArray(pivotArray, barArray, pivotPrice, pivotBarIndex, maxSize)
โโAdd pivot to array with validation
โโParameters:
โโโโ pivotArray (array)
โโโโ barArray (array)
โโโโ pivotPrice (float)
โโโโ pivotBarIndex (int)
โโโโ maxSize (int)
โโReturns: array - updated pivot array
getPivotFromArray(pivotArray, barArray, index)
โโGet pivot from array by index
โโParameters:
โโโโ pivotArray (array)
โโโโ barArray (array)
โโโโ index (int)
โโReturns: tuple - (price, bar_index)
getPivotsInRange(pivotArray, barArray, startIndex, count)
โโGet all pivots in range
โโParameters:
โโโโ pivotArray (array)
โโโโ barArray (array)
โโโโ startIndex (int)
โโโโ count (int)
โโReturns: tuple, array> - (prices, bar_indices)
pivotDistance(barIndex1, barIndex2)
โโCalculate distance between two pivots in bars
โโParameters:
โโโโ barIndex1 (int)
โโโโ barIndex2 (int)
โโReturns: int - distance in bars
pivotPriceRatio(price1, price2)
โโCalculate price ratio between two pivots
โโParameters:
โโโโ price1 (float)
โโโโ price2 (float)
โโReturns: float - price ratio
pivotRetracementRatio(startPrice, endPrice, currentPrice)
โโCalculate retracement ratio
โโParameters:
โโโโ startPrice (float)
โโโโ endPrice (float)
โโโโ currentPrice (float)
โโReturns: float - retracement ratio (0-1)
pivotExtensionRatio(startPrice, endPrice, currentPrice)
โโCalculate extension ratio
โโParameters:
โโโโ startPrice (float)
โโโโ endPrice (float)
โโโโ currentPrice (float)
โโReturns: float - extension ratio (>1 for extension)
isInFibZone(startPrice, endPrice, currentPrice, fibLevel, tolerance)
โโCheck if price is in Fibonacci retracement zone
โโParameters:
โโโโ startPrice (float)
โโโโ endPrice (float)
โโโโ currentPrice (float)
โโโโ fibLevel (float)
โโโโ tolerance (float)
โโReturns: bool - true if in zone
getPivotType(pivotPrice, pivotBarIndex, lookback)
โโGet pivot type (high/low) based on surrounding prices
โโParameters:
โโโโ pivotPrice (float)
โโโโ pivotBarIndex (int)
โโโโ lookback (int)
โโReturns: string - "high", "low", or "unknown"
calculatePivotStrength(pivotPrice, pivotBarIndex, lookback)
โโCalculate pivot strength based on volume and price action
โโParameters:
โโโโ pivotPrice (float)
โโโโ pivotBarIndex (int)
โโโโ lookback (int)
โโReturns: float - strength score (0-100)
AlertSenderLibrary_TradingFinderLibrary "AlertSenderLibrary_TradingFinder"
TODO: add library description here
AlertSender(Condition, Alert, AlertName, AlertType, DetectionType, SetupData, Frequncy, UTC, MoreInfo, Message, o, h, l, c, Entry, TP, SL, Distal, Proximal)
โโParameters:
โโโโ Condition (bool)
โโโโ Alert (string)
โโโโ AlertName (string)
โโโโ AlertType (string)
โโโโ DetectionType (string)
โโโโ SetupData (string)
โโโโ Frequncy (string)
โโโโ UTC (string)
โโโโ MoreInfo (string)
โโโโ Message (string)
โโโโ o (float)
โโโโ h (float)
โโโโ l (float)
โโโโ c (float)
โโโโ Entry (float)
โโโโ TP (float)
โโโโ SL (float)
โโโโ Distal (float)
โโโโ Proximal (float)
TAโ TA Library
๐ OVERVIEW
TA is a Pine Script technical analysis library. This library provides 25+ moving averages and smoothing filters , from classic SMA/EMA to Kalman Filters and adaptive algorithms, implemented based on academic research.
๐ฏ Core Features
Academic Based - Algorithms follow original papers and formulas
Performance Optimized - Pre-calculated constants for faster response
Unified Interface - Consistent function design
Research Based - Integrates technical analysis research
๐ฏ CONCEPTS
Library Design Philosophy
This technical analysis library focuses on providing:
Academic Foundation
Algorithms based on published research papers and academic standards
Implementations that follow original mathematical formulations
Clear documentation with research references
Developer Experience
Unified interface design for consistent usage patterns
Pre-calculated constants for optimal performance
Comprehensive function collection to reduce development time
Single import statement for immediate access to all functions
Each indicator encapsulated as a simple function call - one line of code simplifies complexity
Technical Excellence
25+ carefully implemented moving averages and filters
Support for advanced algorithms like Kalman Filter and MAMA/FAMA
Optimized code structure for maintainability and reliability
Regular updates incorporating latest research developments
๐ USING THIS LIBRARY
Import Library
//@version=6
import DCAUT/TA/1 as dta
indicator("Advanced Technical Analysis", overlay=true)
Basic Usage Example
// Classic moving average combination
ema20 = ta.ema(close, 20)
kama20 = dta.kama(close, 20)
plot(ema20, "EMA20", color.red, 2)
plot(kama20, "KAMA20", color.green, 2)
Advanced Trading System
// Adaptive moving average system
kama = dta.kama(close, 20, 2, 30)
= dta.mamaFama(close, 0.5, 0.05)
// Trend confirmation and entry signals
bullTrend = kama > kama and mamaValue > famaValue
bearTrend = kama < kama and mamaValue < famaValue
longSignal = ta.crossover(close, kama) and bullTrend
shortSignal = ta.crossunder(close, kama) and bearTrend
plot(kama, "KAMA", color.blue, 3)
plot(mamaValue, "MAMA", color.orange, 2)
plot(famaValue, "FAMA", color.purple, 2)
plotshape(longSignal, "Buy", shape.triangleup, location.belowbar, color.green)
plotshape(shortSignal, "Sell", shape.triangledown, location.abovebar, color.red)
๐ FUNCTIONS REFERENCE
ewma(source, alpha)
Calculates the Exponentially Weighted Moving Average with dynamic alpha parameter.
Parameters:
source (series float) : Series of values to process.
alpha (series float) : The smoothing parameter of the filter.
Returns: (float) The exponentially weighted moving average value.
dema(source, length)
Calculates the Double Exponential Moving Average (DEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Double Exponential Moving Average value.
tema(source, length)
Calculates the Triple Exponential Moving Average (TEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triple Exponential Moving Average value.
zlema(source, length)
Calculates the Zero-Lag Exponential Moving Average (ZLEMA) of a given data series. This indicator attempts to eliminate the lag inherent in all moving averages.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Zero-Lag Exponential Moving Average value.
tma(source, length)
Calculates the Triangular Moving Average (TMA) of a given data series. TMA is a double-smoothed simple moving average that reduces noise.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triangular Moving Average value.
frama(source, length)
Calculates the Fractal Adaptive Moving Average (FRAMA) of a given data series. FRAMA adapts its smoothing factor based on fractal geometry to reduce lag. Developed by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Fractal Adaptive Moving Average value.
kama(source, length, fastLength, slowLength)
Calculates Kaufman's Adaptive Moving Average (KAMA) of a given data series. KAMA adjusts its smoothing based on market efficiency ratio. Developed by Perry J. Kaufman.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the efficiency calculation.
fastLength (simple int) : Fast EMA length for smoothing calculation. Optional. Default is 2.
slowLength (simple int) : Slow EMA length for smoothing calculation. Optional. Default is 30.
Returns: (float) The calculated Kaufman's Adaptive Moving Average value.
t3(source, length, volumeFactor)
Calculates the Tilson Moving Average (T3) of a given data series. T3 is a triple-smoothed exponential moving average with improved lag characteristics. Developed by Tim Tillson.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
volumeFactor (simple float) : Volume factor affecting responsiveness. Optional. Default is 0.7.
Returns: (float) The calculated Tilson Moving Average value.
ultimateSmoother(source, length)
Calculates the Ultimate Smoother of a given data series. Uses advanced filtering techniques to reduce noise while maintaining responsiveness. Based on digital signal processing principles by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the smoothing calculation.
Returns: (float) The calculated Ultimate Smoother value.
kalmanFilter(source, processNoise, measurementNoise)
Calculates the Kalman Filter of a given data series. Optimal estimation algorithm that estimates true value from noisy observations. Based on the Kalman Filter algorithm developed by Rudolf Kalman (1960).
Parameters:
source (series float) : Series of values to process.
processNoise (simple float) : Process noise variance (Q). Controls adaptation speed. Optional. Default is 0.05.
measurementNoise (simple float) : Measurement noise variance (R). Controls smoothing. Optional. Default is 1.0.
Returns: (float) The calculated Kalman Filter value.
mcginleyDynamic(source, length)
Calculates the McGinley Dynamic of a given data series. McGinley Dynamic is an adaptive moving average that adjusts to market speed changes. Developed by John R. McGinley Jr.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the dynamic calculation.
Returns: (float) The calculated McGinley Dynamic value.
mama(source, fastLimit, slowLimit)
Calculates the Mesa Adaptive Moving Average (MAMA) of a given data series. MAMA uses Hilbert Transform Discriminator to adapt to market cycles dynamically. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Mesa Adaptive Moving Average value.
fama(source, fastLimit, slowLimit)
Calculates the Following Adaptive Moving Average (FAMA) of a given data series. FAMA follows MAMA with reduced responsiveness for crossover signals. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Following Adaptive Moving Average value.
mamaFama(source, fastLimit, slowLimit)
Calculates Mesa Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA).
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: ( ) Tuple containing values.
laguerreFilter(source, length, gamma, order)
Calculates the standard N-order Laguerre Filter of a given data series. Standard Laguerre Filter uses uniform weighting across all polynomial terms. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Higher order increases lag. Optional. Default is 8.
Returns: (float) The calculated standard Laguerre Filter value.
laguerreBinomialFilter(source, length, gamma)
Calculates the Laguerre Binomial Filter of a given data series. Uses 6-pole feedback with binomial weighting coefficients. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.5.
Returns: (float) The calculated Laguerre Binomial Filter value.
superSmoother(source, length)
Calculates the Super Smoother of a given data series. SuperSmoother is a second-order Butterworth filter from aerospace technology. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Period for the filter calculation.
Returns: (float) The calculated Super Smoother value.
rangeFilter(source, length, multiplier)
Calculates the Range Filter of a given data series. Range Filter reduces noise by filtering price movements within a dynamic range.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the average range calculation.
multiplier (simple float) : Multiplier for the smooth range. Higher values increase filtering. Optional. Default is 2.618.
Returns: ( ) Tuple containing filtered value, trend direction, upper band, and lower band.
qqe(source, rsiLength, rsiSmooth, qqeFactor)
Calculates the Quantitative Qualitative Estimation (QQE) of a given data series. QQE is an improved RSI that reduces noise and provides smoother signals. Developed by Igor Livshin.
Parameters:
source (series float) : Series of values to process.
rsiLength (simple int) : Number of bars for the RSI calculation. Optional. Default is 14.
rsiSmooth (simple int) : Number of bars for smoothing the RSI. Optional. Default is 5.
qqeFactor (simple float) : QQE factor for volatility band width. Optional. Default is 4.236.
Returns: ( ) Tuple containing smoothed RSI and QQE trend line.
sslChannel(source, length)
Calculates the Semaphore Signal Level (SSL) Channel of a given data series. SSL Channel provides clear trend signals using moving averages of high and low prices.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: ( ) Tuple containing SSL Up and SSL Down lines.
ma(source, length, maType)
Calculates a Moving Average based on the specified type. Universal interface supporting all moving average algorithms.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
maType (simple MaType) : Type of moving average to calculate. Optional. Default is SMA.
Returns: (float) The calculated moving average value based on the specified type.
atr(length, maType)
Calculates the Average True Range (ATR) using the specified moving average type. Developed by J. Welles Wilder Jr.
Parameters:
length (simple int) : Number of bars for the ATR calculation.
maType (simple MaType) : Type of moving average to use for smoothing. Optional. Default is RMA.
Returns: (float) The calculated Average True Range value.
macd(source, fastLength, slowLength, signalLength, maType, signalMaType)
Calculates the Moving Average Convergence Divergence (MACD) with customizable MA types. Developed by Gerald Appel.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
signalLength (simple int) : Period for the signal line moving average.
maType (simple MaType) : Type of moving average for main MACD calculation. Optional. Default is EMA.
signalMaType (simple MaType) : Type of moving average for signal line calculation. Optional. Default is EMA.
Returns: ( ) Tuple containing MACD line, signal line, and histogram values.
dmao(source, fastLength, slowLength, maType)
Calculates the Dual Moving Average Oscillator (DMAO) of a given data series. Uses the same algorithm as the Percentage Price Oscillator (PPO), but can be applied to any data series.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
maType (simple MaType) : Type of moving average to use for both calculations. Optional. Default is EMA.
Returns: (float) The calculated Dual Moving Average Oscillator value as a percentage.
continuationIndex(source, length, gamma, order)
Calculates the Continuation Index of a given data series. The index represents the Inverse Fisher Transform of the normalized difference between an UltimateSmoother and an N-order Laguerre filter. Developed by John F. Ehlers, published in TASC 2025.09.
Parameters:
source (series float) : Series of values to process.
length (simple int) : The calculation length.
gamma (simple float) : Controls the phase response of the Laguerre filter. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Optional. Default is 8.
Returns: (float) The calculated Continuation Index value.
๐ RELEASE NOTES
v1.0 (2025.09.24)
โ
25+ technical analysis functions
โ
Complete adaptive moving average series (KAMA, FRAMA, MAMA/FAMA)
โ
Advanced signal processing filters (Kalman, Laguerre, SuperSmoother, UltimateSmoother)
โ
Performance optimized with pre-calculated constants and efficient algorithms
โ
Unified function interface design following TradingView best practices
โ
Comprehensive moving average collection (DEMA, TEMA, ZLEMA, T3, etc.)
โ
Volatility and trend detection tools (QQE, SSL Channel, Range Filter)
โ
Continuation Index - Latest research from TASC 2025.09
โ
MACD and ATR calculations supporting multiple moving average types
โ
Dual Moving Average Oscillator (DMAO) for arbitrary data series analysis
tclibLibrary "tclib"
super_smoother(data, smoothing_period)
โโParameters:
โโโโ data (float)
โโโโ smoothing_period (int)
FiniteStateMachine๐ฉ OVERVIEW
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events.
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include:
โข Explicit logic : You can see all rules easily side-by-side.
โข Validation : Tables show your rules and validation results right on the chart.
โข Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
โข Type safety : Shows how to use enums for robustness while maintaining string compatibility.
โข Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
โข Priority control : Explicit control over which rules take precedence when multiple conditions are met.
โข Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
๐ฉ SIMPLE FSM (MATRIX-BASED)
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
๐ฉ CONCURRENT FSM (MAP-BASED)
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
๐ฉ HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/FiniteStateMachine/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
๐ฉ TECHNICAL IMPLEMENTATION
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
โข Exact state + exact event match
โข Exact state + empty event (event wildcard)
โข Empty state + exact event (state wildcard)
โข Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
โข o_eventRule : Maps a condition name to an output
โข o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
๐ฉ VALIDATION & ERROR HANDLING
The library includes comprehensive validation functions that catch common FSM design errors:
Error detection:
โข Empty next states
โข Invalid states not in the states array
โข Duplicate rules
โข Conflicting transitions
โข Unreachable states (no entry/exit rules)
Warning detection:
โข Redundant wildcards
โข Empty states/events (potential unintended wildcards)
โข Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
๐ฉ PRACTICAL EXAMPLES
The library includes four comprehensive demos:
Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red โ red+amber โ green โ amber โ red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
โข Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
โข Matrix FSM handles state transitions (idle โ setup โ entry โ position โ exit โ re-entry)
โข Includes position management, stop losses, and re-entry logic
Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
๐ฉ BRING ON THE FUNCTIONS
f_printFSMMatrix(_mat_rules, _a_states, _tablePosition)
โโPrints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
โโParameters:
โโโโ _mat_rules (matrix)
โโโโ _a_states (array)
โโโโ _tablePosition (simple string)
โโReturns: The table of states and rules.
method m_loadMatrixRulesFromText(_mat_rules, _rulesText)
โโLoads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
โโNamespace types: matrix
โโParameters:
โโโโ _mat_rules (matrix)
โโโโ _rulesText (string)
โโReturns: No explicit return. The matrix is modified as a side-effect.
method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState)
โโAdds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
โโNamespace types: matrix
โโParameters:
โโโโ _mat_rules (matrix)
โโโโ _currentState (string)
โโโโ _event (string)
โโโโ _nextState (string)
โโReturns: No explicit return. The matrix is modified as a side-effect.
method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition)
โโValidates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
โโNamespace types: matrix
โโParameters:
โโโโ _mat_rules (matrix)
โโโโ _a_states (array)
โโโโ _showTable (bool)
โโโโ _tablePosition (simple string)
โโReturns: `true` if the rules and states are valid; `false` if errors or warnings exist.
method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions)
โโReturns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
โโNamespace types: matrix
โโParameters:
โโโโ _mat_rules (matrix)
โโโโ _currentState (string)
โโโโ _event (string)
โโโโ _strictInput (bool)
โโโโ _strictTransitions (bool)
โโReturns: The next state or `na`.
method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output)
โโAdds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
โโNamespace types: map
โโParameters:
โโโโ _map_eventRules (map)
โโโโ _state (string)
โโโโ _condName (string)
โโโโ _output (string)
โโReturns: No explicit return. The map is modified as a side-effect.
method m_addEventRulesToMapFromText(_map_eventRules, _configText)
โโLoads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state | > output" (condition wildcard), " | > output" (full wildcard).
Splits lines by , extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
โโNamespace types: map
โโParameters:
โโโโ _map_eventRules (map)
โโโโ _configText (string)
โโReturns: No explicit return. The map is modified as a side-effect.
f_printFSMMap(_map_eventRules, _a_states, _tablePosition)
โโPrints a table of map-based event rules to the specified position on the chart.
โโParameters:
โโโโ _map_eventRules (map)
โโโโ _a_states (array)
โโโโ _tablePosition (simple string)
โโReturns: The table of map-based event rules.
method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition)
โโValidates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
โโNamespace types: map
โโParameters:
โโโโ _map_eventRules (map)
โโโโ _a_states (array)
โโโโ _a_validEvents (array)
โโโโ _showTable (bool)
โโโโ _tablePosition (simple string)
โโReturns: `true` if the event rules map is valid; `false` if errors or warnings exist.
method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules)
โโReturns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
โโNamespace types: series string, simple string, input string, const string
โโParameters:
โโโโ _currentState (string)
โโโโ _a_activeConditions (array)
โโโโ _map_eventRules (map)
โโReturns: The output string (event or state) for the first matching condition, or na if no match found.
o_eventRule
โโo_eventRule defines a condition-to-output mapping for the concurrent FSM.
โโFields:
โโโโ condName (series string) : The name of the condition to check.
โโโโ output (series string) : The output (event or state) when the condition is true.
o_eventRuleWrapper
โโo_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
โโFields:
โโโโ a_rules (array) : Array of o_eventRule objects for a specific state.
ApicodeLibrary "Apicode"
percentToTicks(percent, from)
โโConverts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
โโParameters:
โโโโ percent (float) : (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
โโโโ from (float) : (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
โโReturns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
โโCalculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
โโParameters:
โโโโ percent (float) : (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
โโโโ from (float) : (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
โโReturns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
โโParameters:
โโโโ price (float) : (series int/float) The price from which to calculate the percentage.
โโโโ percent (float) : (series int/float) The percentage of the `price` to calculate.
โโReturns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
โโCalculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
โโParameters:
โโโโ exitPrice (float) : (series int/float) The position's hypothetical closing price.
โโReturns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
โโConverts a price value to ticks.
โโParameters:
โโโโ price (float) : (series int/float) The price to convert.
โโReturns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
โโCalculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
โโParameters:
โโโโ ticks (float) : (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
โโโโ from (float) : (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
โโReturns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
โโConverts a specified number of ticks to an amount of the symbol's currency.
โโParameters:
โโโโ ticks (float) : (series int/float) The number of ticks to convert.
โโReturns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
โโCalculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
โโParameters:
โโโโ ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
โโReturns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
โโCalculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
โโParameters:
โโโโ ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
โโReturns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
โโCalculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
โโParameters:
โโโโ stopLossTicks (float) : (series int/float) The number of ticks in the stop-loss distance.
โโโโ riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
โโReturns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
โโCalculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
โโParameters:
โโโโ stopLossPercent (float) : (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
โโโโ riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
โโโโ entryPrice (float) : (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
โโReturns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
โโA wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
โโParameters:
โโโโ id (string) : (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
โโโโ lossPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
โโโโ profitPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
โโโโ qty (float) : (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
โโโโ qtyPercent (float) : (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
โโโโ comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
โโโโ alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
โโReturns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
โโA wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
โโParameters:
โโโโ comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
โโโโ alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
โโReturns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
โโA wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
โโParameters:
โโโโ entryId (string)
โโโโ comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
โโโโ alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
โโReturns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
โโCalculates the Sortino ratio of the strategy based on realized monthly returns.
โโParameters:
โโโโ interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
โโโโ forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
โโReturns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
โโCalculates the Sharpe ratio of the strategy based on realized monthly returns.
โโParameters:
โโโโ interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
โโโโ forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
โโReturns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
GBB_lib_fiboLibrary "GBB_lib_fibo"
draw_fibo(high_point, low_point)
โโdraw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
โโParameters:
โโโโ high_point (float)
โโโโ low_point (float)
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_tf_to_display(tf_minutes, tf_string)
โโgbb_tf_to_display
/ @description Converts minutes and TF string into a short standard label.
/ @param tf_minutes (float)
/ @param tf_string (string)
/ @returns (string) Timeframe label (M1,H1,D1,...)
โโParameters:
โโโโ tf_minutes (float)
โโโโ tf_string (string)
gbb_convert_bars(_bars)
โโgbb_convert_bars
/ @description Formats a number of bars into a duration (days, hours, minutes + bar count).
/ @param _bars (int)
/ @returns (string)
โโParameters:
โโโโ _bars (int)
gbb_goldorak_init(_tf5Levels_input)
โโgbb_goldorak_init
/ @description Builds a contextual message about the current timeframe and optional 5-level TF.
/ @param _tf5Levels_input (string) Alternative timeframe ("" = current timeframe).
/ @returns (string, string, float)
โโParameters:
โโโโ _tf5Levels_input (string)
GGB_lib_fiboLibrary "GGB_lib_fibo"
draw_fibo(high_point, low_point)
โโdraw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
โโParameters:
โโโโ high_point (float)
โโโโ low_point (float)
GGB_lib_utilsLibrary "GGB_lib_utils"
gbb_tf_to_display(tf_minutes, tf_string)
โโgbb_tf_to_display
/ @description Converts minutes and TF string into a short standard label.
/ @param tf_minutes (float)
/ @param tf_string (string)
/ @returns (string) Timeframe label (M1,H1,D1,...)
โโParameters:
โโโโ tf_minutes (float)
โโโโ tf_string (string)
gbb_convert_bars(_bars)
โโgbb_convert_bars
/ @description Formats a number of bars into a duration (days, hours, minutes + bar count).
/ @param _bars (int)
/ @returns (string)
โโParameters:
โโโโ _bars (int)
gbb_goldorak_init(_tf5Levels_input)
โโgbb_goldorak_init
/ @description Builds a contextual message about the current timeframe and optional 5-level TF.
/ @param _tf5Levels_input (string) Alternative timeframe ("" = current timeframe).
/ @returns (string, string, float)
โโParameters:
โโโโ _tf5Levels_input (string)
delta_leverage_lib๐ Delta Leverage Library - Exchange Max Leverage Data
Comprehensive Pine v6 library providing maximum leverage data for USDT perpetual contracts across major exchanges. Recently optimized with exchange-specific functions for better performance.
๐ Coverage & Stats
โข 2,357 symbols across 6 exchanges
โข BINANCE: 533 symbols (BTC/ETH: 125x)
โข BITGET: 551 symbols (BTC: 125x, ETH: 100x)
โข BYBIT: 441 symbols (BTC/ETH: 100x)
โข KUCOIN: 478 symbols (ETH: 100x)
โข OKX: 244 symbols (BTC/ETH: 100x)
โข BITMEX: 110 symbols (BTC/ETH: 100x)
โก Core Functions
โข get_max_leverage(exchangePrefix, tvTicker) - Main lookup function
โข get_max_leverage_for_chart() - Current chart leverage
โข get_max_leverage_or_default(exchange, ticker, defaultLev) - With fallback
๐ก Usage Examples
// Get leverage for current chart
leverage = get_max_leverage_for_chart()
// Get specific exchange/ticker
binanceBTC = get_max_leverage("BINANCE", "BTCUSDT.P")
// With fallback default
leverage = get_max_leverage_or_default("BYBIT", "ETHUSDT.P", 50)
๐ง Technical Details
โข Auto-generated from live exchange APIs
โข Exchange-specific functions for optimal performance
โข Switch-based dispatcher for efficient lookups
โข Supports only USDT perpetuals (.P suffix)
โข Realistic leverage tiers based on market categories
๐ Data Sources
โข Binance: Realistic tiers (Major coins 125x, memes 10x)
โข Bybit/Bitget/KuCoin/OKX: Live API leverage filters
โข BitMEX: Conservative defaults for USDT contracts
โ๏ธ Maintenance
Data refreshes via Python generator script with exchange API polling. Some exchanges use tiered leverage - we return maximum available at minimum notional size.
Recent Updates
โข Fixed Pine Script compilation errors via function splitting
โข Improved performance with exchange-specific lookup functions
โข Enhanced Python generator with debug mode and statistics
This updated description:
1. **Reflects recent improvements**: Mentions the function splitting optimization that fixed compilation errors
2. **Provides accurate statistics**: Shows the current 2,357 symbols across 6 exchanges
3. **Better organized**: Uses clear sections with emojis for visual appeal
4. **Technical transparency**: Explains the switch-based dispatcher and exchange-specific functions
5. **Practical usage**: Shows realistic code examples
6. **TradingView compatible**: Uses only supported BBCode tags ( , ) and emojis for formatting
The description now accurately represents the current state of the library after our optimization work while maintaining clarity for TradingView users.
get_max_leverage_binance(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage_bitget(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage_bitmex(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage_bybit(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage_kucoin(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage_okx(tvTicker)
โโParameters:
โโโโ tvTicker (string)
get_max_leverage(exchangePrefix, tvTicker)
โโParameters:
โโโโ exchangePrefix (string)
โโโโ tvTicker (string)
get_max_leverage_for_chart()
get_max_leverage_or_default(exchangePrefix, tvTicker, defaultLev)
โโParameters:
โโโโ exchangePrefix (string)
โโโโ tvTicker (string)
โโโโ defaultLev (int)






















