PivotStructureOutline_UtilitiesThis library contains reusable pivot structure outline helpers for Pine scripts that already work with confirmed pivot highs and lows. It is designed to provide the reusable outline and anchor-box layer for scripts that already have their own pivot-confirmation logic, so those scripts can keep their structure visuals consistent without repeatedly rebuilding the same framework.
It brings together the parts of the workflow that are often rewritten in structure-based scripts: resolving pivot-close anchors, selecting wick vs close anchor behavior, building live outline geometry, building pivot structure anchor-box geometry, and managing the line and box objects that render those visuals.
Everything on the example chart is materially driven by the library, whether through the selected outline anchor source, the outline geometry itself, the midpoint-start logic, the pivot structure anchor boxes, or the shared line/box lifecycle helpers used to keep those visuals updated cleanly on the chart.
How to use
Import the library near the top of your script in global scope, alongside any other imports, before you start calling its helpers. This mirrors the import-first usage pattern shown on your recent library page.
Typical placement:
//@version=6
indicator(...) or strategy(...)
import MYNAMEISBRANDON/PivotStructureOutline_Utilities/1 as PSOutils
This library is engine-agnostic. It does not confirm pivots for you. Instead, it expects your script to already know its confirmed high/low pivot indexes and anchor values, then uses those resolved inputs to build the outline and anchor-box layer.
➖Outline Line Style Helpers➖
These helpers convert simple UI-facing style strings into Pine line style enums so scripts can keep one consistent style resolver across outline lines, midpoint lines, and connector lines.
outlineLineStyle(styleIn)
Resolves a Pine line style from a string input.
Parameters:
styleIn (simple string): Style string. Expected values: "Solid", "Dashed", or "Dotted"
Returns:
Pine line style enum
➖Pivot Structure Outline Helpers➖
These helpers build the actual pivot structure outline framework from already-confirmed high/low pivot anchors. They let a script resolve a pivot-close anchor, choose whether the outline should use wick or close anchors, and generate the live geometry needed for the top line, bottom line, midpoint, and left-side connectors.
outlinePivotCloseFromIdx(pivotIdx, closeValue)
Returns the close value belonging to a confirmed pivot index.
Parameters:
pivotIdx (int): Confirmed pivot bar_index
closeValue (float): Close series
Returns:
Confirmed pivot close value
outlineSelectedAnchors(anchorMode, highWickAnchor, lowWickAnchor, highCloseAnchor, lowCloseAnchor)
Selects the active outline anchors from Wick or Close mode.
Parameters:
anchorMode (simple string): Anchor mode. Expected values: "Wick" or "Close"
highWickAnchor (float): Confirmed high-side wick anchor
lowWickAnchor (float): Confirmed low-side wick anchor
highCloseAnchor (float): Confirmed high-side close anchor
lowCloseAnchor (float): Confirmed low-side close anchor
Returns:
Selected high anchor, selected low anchor, is outline-valid
outlineGeometry(highPivotIdx, lowPivotIdx, highAnchor, lowAnchor, connectorSourceMode, midlineStartMode, highValue, lowValue, closeValue)
Returns the live geometry for the pivot structure outline system.
Parameters:
highPivotIdx (int): Confirmed high pivot bar_index
lowPivotIdx (int): Confirmed low pivot bar_index
highAnchor (float): Selected top outline anchor
lowAnchor (float): Selected bottom outline anchor
connectorSourceMode (simple string): Connector source mode. Expected values: "Wick" or "Close"
midlineStartMode (simple string): Midline start mode. Expected values: "Most Recent Pivot" or "Left Outline"
highValue (float): High series
lowValue (float): Low series
closeValue (float): Close series
Returns:
ok, leftX, rightX, midX1, topY, bottomY, midY, leftTopConnectorY, leftBottomConnectorY
➖Pivot Structure Anchor Box Helpers➖
These helpers build directional top and bottom pivot structure anchor boxes from confirmed pivot bars. They let a script choose whether those boxes use wick-only extension from the candle body or the full candle body, then return the live coordinates needed to render those boxes forward to the current bar.
outlineAnchorBoxGeometry(highPivotIdx, lowPivotIdx, boxAreaMode, openValue, highValue, lowValue, closeValue)
Returns the live geometry for top and bottom pivot structure anchor boxes.
Parameters:
highPivotIdx (int): Confirmed high pivot bar_index
lowPivotIdx (int): Confirmed low pivot bar_index
boxAreaMode (simple string): Box area mode. Expected values: "Wick" or "Body"
openValue (float): Open series
highValue (float): High series
lowValue (float): Low series
closeValue (float): Close series
Returns:
showHighBox, showLowBox, highLeftX, lowLeftX, boxRightX, highTopY, highBottomY, lowTopY, lowBottomY
➖Line Object Helpers➖
These helpers manage the lifecycle of live line objects so scripts can create, update, or delete outline-related lines without rewriting that object-management logic each time.
outlineManageLine(enabled, ln, x1, y1, x2, y2, col, width, style)
Creates, updates, or deletes a line object.
Parameters:
enabled (bool): Whether the line should exist
ln (line): Existing line reference
x1 (int): Start x position
y1 (float): Start y position
x2 (int): End x position
y2 (float): End y position
col (color): Line color
width (int): Line width
style (string): Line style
Returns:
Updated line reference
➖Box Object Helpers➖
These helpers manage the lifecycle of live box objects so scripts can create, update, or delete pivot structure anchor boxes without repeating the same box-management code in every script.
outlineManageBox(enabled, bx, left, top, right, bottom, bgColor, borderColor, borderStyle, borderWidth)
Creates, updates, or deletes a box object.
Parameters:
enabled (bool): Whether the box should exist
bx (box): Existing box reference
left (int): Left x position
top (float): Top y position
right (int): Right x position
bottom (float): Bottom y position
bgColor (color): Box background color
borderColor (color): Box border color
borderStyle (string): Box border style
borderWidth (int): Box border width
Returns:
Updated box reference
Library

Pine3D: A Native 3D Graphical Rendering EnginePine3D is a full 3D rendering engine for PulseWire, powered by Pine Script™ v6.
Pine3D pushes forward the frontier of PulseWire 3D rendering capabilities, providing a fully fledged graphical engine under an intuitive, chainable, object oriented API. Build meshes, transform them in world space, light them, cast shadows, project them through a perspective camera, and render the result directly on your chart, all without ever bothering about trigonometry synchronization or optimization.
The library brings forth a streamlined process for anyone that wishes to visualize data in 3D, without needing to know anything about the complex math that has previously gatekept such indicators. Pine3D does all the heavy lifting, including extreme optimization techniques designed for production ready indicators.
The entire API is chainable and tag addressable, so spawning a mesh, registering it, pointing the camera at it, and rendering the frame is a four line affair:
Mesh mybox = cube(40.0, color.orange).setTag("hero").rotateBy(0.0, 45.0, 0.0)
scene.add(mybox)
scene.lookAt("hero")
render(scene)
🔷 SURFACES: CONTOUR BAND RENDERING
Pine Script imposes a hard ceiling of 100 polylines and 500 lines per indicator . On the surface this looks fatal for dense 3D meshes: every triangle drawn naively burns one of those 100 slots, or two of the 500, and the budget evaporates within a few hundred faces.
The conventional escape hatch is strip stitching , tracing a polyline forward along one row of a grid and back along the next, packing a ribbon of quads into a single drawing slot. It buys a meaningful multiplier, but it pays for that multiplier with two structural constraints baked into the geometry itself:
One color per strip. A polyline carries a single stroke and fill color, so every cell along the ribbon must share the same shade. The moment you want per cell lighting, contour banding, or value driven gradients, every color change forces a new polyline and the budget collapses.
One contiguous ribbon per slot. Strips can only describe topologically connected runs of cells. Disjoint regions, holes, islands, and value clustered fragments scattered across the surface each demand their own polyline.
Pine3D breaks both constraints at once.
At the core of the engine sits an innovation that redefines the limits for visual fidelity: contour band rendering using degenerate bridge stitching . The technique quantizes a surface's elevation into colored bands, then collapses every cell that falls inside the same band, no matter where it sits on the screen , into one continuous, hole aware polyline path per band, threading invisible zero width bridges between disjoint islands so that a single polyline can carry thousands of polygon equivalent fragments scattered across the geometry.
The result:
A single polyline can render up to 2,000 disconnected triangle equivalents , spread across arbitrarily separated regions of the surface.
Theoretical ceiling of around 200,000 disconnected faces inside the 100 polyline budget, a regime that strip based stitching cannot enter at any color count above one.
A 40 x 40 heightmap (around 3,000 triangles) renders inside the budget with full per band contour coloring and room to spare. Stress harnesses have run 40 x 80 grids .
Each band's path is depth sorted and near plane culled, and cached between bars , so once geometry is built only the screen space projection runs per frame.
This algorithm enables scenes with extreme detail relative to the 100 polyline limit, and shifts the optimization focus from "drawing limits" to "CPU limits", which Pine3D natively handles with aggressive caching at every layer of the pipeline. The contour technique is currently integrated into the surface() function, with the same compression strategy generalizable to any mesh class and ultimately full scene rendering in future versions.
Non-uniform grids out of the box. surface() accepts optional axisX and axisZ arrays that override the default uniform spacing with custom column and row positions. This means logarithmic strike spacing on an option volatility surface, irregular timestamp spacing on a market depth heatmap, or any other non-evenly-sampled grid renders correctly without resampling the data first. The contour band engine, axis ticks, and gridBox cage all snap to the custom positions automatically.
A full contour surface is just a handful of lines; the damped ripple below builds once and never needs updating:
//@version=6
indicator("Pine3D - Contour Surface", overlay = false, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
var p3d.Scene scene = p3d.newScene()
var p3d.Mesh heatmap = na
if barstate.isfirst
// Damped cosine ripple
int N = 20
matrix data = matrix.new(N, N, 0.0)
for r = 0 to N - 1
for c = 0 to N - 1
float dx = c - (N - 1) / 2.0
float dz = r - (N - 1) / 2.0
float d = math.sqrt(dx * dx + dz * dz) * 0.7
data.set(r, c, math.cos(d) * math.exp(-d * 0.12) * 50.0)
heatmap := p3d.surface(data, 200.0, color.blue, color.red, 24)
.gridBox()
.gridLabels(color.white, "X", "Amplitude", "Z")
scene.add(heatmap)
scene.camera.orbit(35.0, 25.0, 380.0)
if barstate.islast
p3d.render(scene, lighting = true)
🔷 TRAIL3D: STREAMED OSCILLATOR PATHS
Trail3D is a first class streaming primitive built for visualizing two correlated time series as a 3D ribbon evolving through time. You give it a rolling buffer capacity and push (u, v) samples bar by bar; the primitive maintains the buffer, builds the ribbon geometry, and renders it inside a normalized bounding cube so the path always fits cleanly in view regardless of the underlying data range.
Under the hood, Trail3D is a coordinated bundle of polylines: one for the main ribbon, two for optional shadow projections onto the back wall and floor, and one for the wireframe cage. All four are depth sorted and occlusion clipped against the rest of the scene, and the primitive auto normalizes incoming samples against the rolling window's min/max so streaming data always fills the cube without manual scaling.
This enables a class of visualizations that would otherwise require dozens of polylines and manual buffer management: phase space portraits, Lissajous figures, oscillator pair correlations, attractor trajectories, and any "two indicators evolving together over time" study. The demo above shows a sine and cosine pair pushing samples each bar to trace a clean spiral inside the cage, the same pattern you would use to plot RSI vs MFI, momentum vs volatility, or any custom (u, v) signal pair.
A full streamed scene is a handful of lines:
//@version=6
indicator("Pine3D - Trail3D", overlay = false, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
var p3d.Scene scene = p3d.newScene()
var p3d.Trail3D trail = na
if barstate.isfirst
trail := p3d.trail3D(220.0, 200, color.yellow)
.cage(true)
.axisLabels("sin", "cos", color.white)
trail._uProj.col := #00ffff69
trail._vProj.col := #ff00ff71
scene.add(trail)
scene.camera.orbit(215.0, 20.0, 360.0)
float phase = bar_index * 0.15
float sinX = math.sin(phase) * 100.0
float cosY = math.cos(phase) * 100.0
if barstate.isconfirmed
trail.pushSample(sinX, cosY)
p3d.render(scene)
🔷 BARS3D: CATEGORICAL 3D BAR CHARTS
bars3D() turns any series of values into a fully lit, depth sorted 3D bar chart in a single call. Each bar is height mapped to its value, color graded between a low and high color, and packed into one combined mesh with per bar depth grouping so individual bars sort correctly even inside the merged geometry. The companion updateBars() mutator refreshes heights, colors, and labels in place every bar without rebuilding geometry, making it suitable for live rankings, rolling windows, and animated comparisons.
The chainable barLabels(catNames, valNames) helper attaches category labels at the base of each bar and value labels at the top, both depth sorted with the rest of the scene. Category labels are set once at build time, while value labels can be passed to updateBars(values, valLabels = ...) each frame to reflect live data. Combined with wireGrid() for the floor and a contour surface() in the background, bars3D() becomes the centerpiece of dashboards comparing assets, sectors, timeframes, or any categorical metric.
Negative values are handled automatically: bars below zero extrude downward from the base plane with reversed face winding, so signed series like PnL, delta, or momentum histograms render correctly without any extra setup.
A complete labeled bar chart is just a few lines:
//@version=6
indicator("Pine3D - Bars3D", overlay = false, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
var p3d.Scene scene = p3d.newScene()
var p3d.Mesh bars = na
array values = array.from(volume - volume , volume - volume , volume - volume , volume - volume , volume - volume , volume - volume )
array names = array.from("ΔV0", "ΔV-1", "ΔV-2", "ΔV-3", "ΔV-4", "ΔV-5")
if barstate.isfirst
bars := p3d.bars3D(values, 30.0, 30.0, 10.0, color.blue, color.red, 200.0)
.barLabels(names)
scene.add(bars)
p3d.wireGrid(scene, 300.0, 300.0, 6, 6, color.new(color.gray, 80))
scene.camera.orbit(215.0, 25.0, 360.0)
if barstate.islast
bars.updateBars(values)
p3d.render(scene, lighting = true)
Omitting valLabels in updateBars() tells the engine to auto format each numeric value via str.tostring() . Pass valLabels only when you need custom strings.
🔷 SCATTER CLOUDS: POINTS IN 3D SPACE
Pine3D treats scatter clouds as a first class use case without needing a dedicated scatter API. Because Label3D is the primitive and scene.add(array) is a single batch operation, you can scatter up to 500 points anywhere in 3D space, each with independent color, symbol, size, and tooltip , and have them depth sorted and occlusion clipped against the rest of the scene automatically.
Each point is a fully addressable Label3D with mutable fields. You can change position , textColor , bgColor , labelStyle (any label.style_* glyph including circles, squares, diamonds, triangles, crosses, arrows, flags), labelSize (any size.* preset), and text per point per bar. The renderer reads these mutations every frame, so animation is just direct field assignment.
This unlocks a wide class of visualizations: clustered data scatter, K means visualizations, particle systems, parametric surfaces sampled as point clouds, gradient colored attractors, multi class classification overlays, and structured curves like the demo above. The double helix demo plots two intertwined parametric strands as ~500 points with alternating colors and per point sizing, all inside the standard scene.add(array) pipeline.
The pattern is straightforward: build the array once in barstate.isfirst , add it to the scene, then mutate point fields per bar to animate.
//@version=6
indicator("Pine3D - Scatter Cloud", overlay = false, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
var p3d.Scene scene = p3d.newScene()
var array points = array.new()
if barstate.isfirst
for i = 0 to 499
p3d.Vec3 pos = p3d.vec3(0.0, 0.0, 0.0)
points.push(p3d.Label3D.new(position = pos, txt = "•"))
scene.add(points)
scene.camera.orbit(35.0, 20.0, 400.0)
if barstate.islast
for i = 0 to points.size() - 1
float t = i * 0.05 + bar_index * 0.01
p3d.Label3D pt = points.get(i)
pt.position := p3d.vec3(80.0 * math.cos(t), i * 0.4 - 100.0, 80.0 * math.sin(t))
pt.textColor := i % 2 == 0 ? color.aqua : color.fuchsia
p3d.render(scene)
----------------------------------------------------------------------------------------------------------------
🔷 TWO LAYER ARCHITECTURE
Pine3D ships as a clean, two layer library:
🔸 Layer 1 - DIY API. First principle building blocks ( Vec3 , Mesh , Camera , Light , Scene , plus world space overlay primitives) for total creative control. Author your own geometry, camera behavior, lighting setup, and scene graph from scratch.
🔸 Layer 2 - High Level Helpers. Production ready wrappers like surface() , bars3D() , trail3D() , updateBars() , updateSurface() , sphere() , torus() , cylinder() , and wireGrid() , plus chainable contour helpers gridBox() and gridLabels() that wrap the primitives into a few lines of code. Scatter clouds use the standard Label3D primitive directly.
The object model is chainable and scene oriented, so complex setups still read cleanly.
🔷 FEATURE LIST
Contour Surface Rendering - The most powerful 3D surface engine ever released for Pine Script. Render tens of thousands of polygon equivalent faces using a single polyline per contour band, delivering smooth, continuous terrain with natural ridges and valleys.
Adaptive Rail Sharing - Solid meshes drawn with the default linefill backend reuse one edge line between adjacent coplanar faces, averaging roughly 1.6 lines per face instead of the naive two, pushing practical mesh capacity up to ~360 faces depending on topology.
Interior Face Culling on Merge - mergeMeshes(meshes, removeInterior = true) detects coincident faces with opposing normals and strips them, so voxel style scenes (stacked cubes, block walls, lattice geometry) ship only their exterior shell and spend no budget on hidden interior faces.
True Perspective Camera System - Full 3D camera with position, target, fov, and orbit() controls. Supports cinematic camera movement, lookAt by mesh tag, and realistic depth.
Real Time Lighting and Shadows - Directional and point lights with configurable ambient, shadow strength, self shadowing, and a spatial grid acceleration structure for fast shadow queries.
High Performance Update System - updateSurface() and updateBars() let you animate massive datasets bar by bar without rebuilding geometry, keeping CPU usage minimal.
Rich Primitive Library - Cubes, cuboids, spheres, cylinders, tori, pyramids, planes, discs, circles, custom meshes, and the groundbreaking bars3D() with automatic labels.
Streamed Trail Primitive - trail3D() maintains a rolling buffer of (u, v) samples and renders them as a 3D ribbon inside a bounding cube, with optional projections onto the back wall and floor and a wireframe cage.
Depth Sorted Overlays - 3D labels, lines, polylines, wire grids, and trails, all correctly occluded and painter sorted against the rest of the scene.
Professional Contour Helpers - gridBox() and gridLabels() automatically add clean bounding boxes and axis titles, ticks, and series names that refresh on every updateSurface() call.
Tag Based Scene Graph - Every Mesh , Label3D , Line3D , and Polyline3D can carry a string tag. Scene exposes getMesh() , getLabel() , getLine() , getPolyline() , lookAt() , and remove() by tag, turning your scene into a lookup by name graph instead of an index juggling exercise.
Chainable, Intuitive API - Everything is designed for maximum readability and speed of development. Build complex scenes in just a few lines.
Production Ready Optimizations - World vertex caching, view projection caching, face preprocessing cache, shadow grid cache, and contour geometry cache, all managed automatically.
----------------------------------------------------------------------------------------------------------------
🔷 THE RENDERER
Every frame is produced by a single call to render(scene, ...) . The renderer runs the full pipeline: world transform, camera transform, back face culling, occlusion culling, depth sort, directional or point lighting with shadows, and perspective projection.
⚠ render() clears the entire chart drawing pool at the start of every call - every polyline , line , label , and linefill on the chart is deleted before Pine3D redraws, not just the ones it created. If you mix Pine3D with manual label.new() , line.new() , or similar calls, those drawings must be emitted after render() or they will be wiped every frame.
🔸 Setup Requirements. Pine3D consumes polylines, lines, and labels simultaneously, so your indicator() declaration must raise all three budgets, and the library must be imported under an alias:
indicator("My 3D Scene", overlay = false,
max_polylines_count = 100,
max_lines_count = 500,
max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
🔸 render() parameters.
maxFaces (int, default 100). Hard cap on solid faces drawn per frame. Contour bands, wireframe edges, labels, lines, and overlay polylines are not counted against this cap, and are bounded only by PulseWire's global 100 polyline / 500 line / 500 label budgets.
culling (bool, default true). Enable back face culling.
lighting (bool, default false). Enable diffuse shading. Reads scene.light if set; otherwise falls back to the render() args.
lightDir (Vec3). Overrides scene.light.direction when provided. Points toward the light.
ambient (float, default 0.3). Minimum brightness for shadowed faces (0.0-1.0).
wireframe (bool, default false). Force outline only output for the entire scene.
occlusion (bool, default true). Sparse raster pass that drops hidden faces before drawing. Major perf win on dense scenes.
occlusionRaster (int, default 768). Raster resolution of the occlusion buffer. Lower = faster but coarser; higher = stricter hidden face rejection.
Explicit render() args always win over scene.light , which makes render() the right place for ad hoc, per frame lighting tweaks.
----------------------------------------------------------------------------------------------------------------
🔷 MESH DRAWING MODES
Two independent axes control how a mesh appears on the chart:
🔸 Style (via mesh.setStyle(...) ) - what gets drawn:
"solid" . Filled faces. Default.
"wireframe" . All edges, no fill. Shows interior geometry.
"wireframe_front" . Only front facing edges. Cleaner silhouette for convex meshes.
🔸 Draw Mode (via mesh.drawMode ) - which PulseWire primitive carries the solid faces:
"linefill" (default). Uses the line and linefill budgets. An adaptive rail sharing optimization reuses one edge line between adjacent coplanar faces, pushing practical capacity up to ~360 faces per mesh depending on topology. Supports in place updates via updateSurface() and updateBars() . Rails are drawn transparent, so solid faces in this mode have no visible outline - use a wireframe style or "poly" drawMode if you need stroked edges. Recommended for all new code.
"poly" . Legacy polyline backend. Capacity ~100 faces, no in place updates, but renders the face outline using mesh.lineStyle and mesh.lineWidth . Use only when you need styled solid face outlines.
Wireframe styles always render with line primitives regardless of drawMode. Stroke width and style on edges (and on poly mode face outlines) come from mesh.lineWidth and mesh.lineStyle , which you mutate by direct field assignment.
----------------------------------------------------------------------------------------------------------------
🔷 QUICK START
The best practice lifecycle is simple:
Create one persistent Scene with newScene() .
Build meshes and helper overlays once in barstate.isfirst .
On later bars, mutate objects in place with transforms or helper mutators like updateBars() and updateSurface() .
Call render(scene, ...) once per frame. It automatically clears the previous chart drawings.
A complete, lit, animated 3D scene is still a handful of lines:
//@version=6
indicator("My First 3D Scene", overlay = false, max_polylines_count = 100, max_lines_count = 500, max_labels_count = 500)
import Alien_Algorithms/Pine3D/1 as p3d
var p3d.Scene scene = p3d.newScene()
var p3d.Mesh sun = na
if barstate.isfirst
scene.setLightDir(1.0, -1.0, 0.5).setAmbient(0.3)
sun := p3d.sphere(50.0, 16, 12, color.orange).setTag("sun")
scene.add(sun)
p3d.wireGrid(scene, 300.0, 300.0, 6, 6, color.new(color.gray, 80))
scene.camera.orbit(35.0, 25.0, 220.0)
if barstate.islast
sun.rotateBy(0.0, 1.5, 0.0)
p3d.render(scene, lighting = true)
----------------------------------------------------------------------------------------------------------------
🔷 RECOMMENDED USAGE PATTERN
Use your Scene and major meshes in var .
Build geometry once in barstate.isfirst .
Use updateSurface() and updateBars() on later bars instead of rebuilding meshes.
Use scene level helpers like wireGrid() when you want overlays added immediately.
Use trail3D() when you want a streamed oscillator style path with built in wall projections and cage geometry.
For scatter clouds, build an array once, hand it to scene.add(pts) , then mutate pt.position , pt.textColor , etc. each bar to animate.
Use mesh level gridBox() and gridLabels() (contour) and barLabels() (bars) to attach overlays to the mesh setup chain. They are drained into the scene by scene.add(mesh) .
🔷 CONSIDERATIONS
scene.clear() vs render(). scene.clear() removes objects from the scene graph (meshes, labels, lines, polylines). render() only clears the previous frame's PulseWire drawings and redraws from the current scene graph. You almost never need scene.clear() in the build once and update pattern.
Global scope series for updateSurface() / updateBars(). If your data uses Pine's history operator ( ) or calls functions like ta.rsi() , ta.atr() , request.security() , those must be declared at global scope so Pine tracks their bar by bar history. Calling them inside barstate.islast produces inconsistent results or compiler errors.
gridLabels() tick values auto refresh. When you call updateSurface() , any tick value labels created by gridLabels() are automatically updated to reflect the new data range. Axis titles and positions stay constant. You don't need to rebuild them.
barLabels() value labels via updateBars(). Create category labels once with mesh.barLabels(catNames) at build time, then pass valLabels to updateBars() on each frame. Value labels are refreshed automatically. Don't call barLabels() again.
Lighting convenience methods are chainable. scene.setLightDir() , setLightPos() , setLightMode() , setAmbient() , setShadowStrength() , and showLightSource() all return Scene and can be chained: scene.setLightMode("point").setLightPos(0, 200, 150).setAmbient(0.25) .
Mesh transforms return Mesh. moveTo() , moveBy() , rotateTo() , rotateBy() , scaleTo() , scaleUniform() , setTag() , setStyle() , setColor() , show() , hide() all return Mesh for chaining: mesh.moveTo(0, -20, 0).rotateTo(0, 45, 0).setStyle("solid") .
Degrees vs radians. rotateTo() and rotateBy() on Mesh expect degrees. The low level Vec3.rotateX/Y/Z() methods expect radians.
scene.lookAt() is tag only. scene.lookAt(t) accepts a string tag and points the camera at that mesh. To aim the camera at an arbitrary Vec3 , call scene.camera.lookAt(vec) directly.
remove(tag) removes one object. The search order is meshes, then labels, then lines, then polylines, and the first hit wins. Avoid reusing tags across primitive types if you intend to delete by tag.
Shadow grid acceleration is directional light only. The spatial shadow grid is only built when lightMode == "directional" . Point lights fall back to a linear O(M) scan, so heavy shadow scenes are fastest in directional mode.
guiShift and yOffset. scene.guiShift and scene.yOffset position the 3D viewport on the chart without consuming historical bar slots. Increase guiShift to push the scene rightward into future bar space; adjust yOffset to slide it vertically in price units.
bar_time projection. All chart drawings are emitted with xloc.bar_time , so the scene can sit arbitrarily far left or right of bar_index without forcing Pine to extend its history buffer. This is what keeps the engine stable on long charts and future projected scenes.
barLabels() without values. When you call mesh.barLabels(catNames) and omit value labels, every later updateBars(values) auto formats the numeric values via str.tostring() . Pass valLabels only when you need custom strings.
Direct mesh.vertices mutation requires invalidateCache(). Transform mutators ( moveTo , rotateBy , scaleTo , etc.) invalidate the world vertex cache on their own. Only raw index writes like mesh.vertices.set(i, newVec) need a manual mesh.invalidateCache() call to force re-projection. Skipping it will make the renderer draw stale geometry.
Drawing budgets fail silently. If a scene emits more than 100 polylines, 500 lines, or 500 labels in a single frame, PulseWire silently drops the overflow without raising a runtime error. Missing geometry almost always means a budget overrun - lower maxFaces , drop a contour level, or simplify overlay primitives to bring the frame back inside the caps.
render() deletes non Pine3D drawings too. Every render() call clears polyline.all , line.all , label.all , and linefill.all before redrawing. Any manual label.new() , line.new() , etc. issued before render() in the same frame will be wiped. Issue custom drawings after the render call if you need them to persist.
mergeMeshes() preserves depth grouping. When every source mesh passed into mergeMeshes() has the same vertex and face count (e.g. identical primitives in a voxel grid), the merged mesh auto derives depth group boundaries so the combined geometry still sorts correctly per original instance. Mixing primitives with different topologies disables the grouping.
CPU timeouts: knobs to turn. Pine Script enforces a per bar execution budget, and dense scenes can trip it before the drawing budget ever does. If a scene compiles but times out at runtime, reach for these levers in order: lower occlusionRaster (e.g. 768 -> 384) for the biggest single perf win, reduce maxFaces to cap the solid face pool, drop levels on contour surfaces, simplify sphere/torus segment counts, and gate heavy work behind barstate.islast so history bars only build geometry rather than render it.
----------------------------------------------------------------------------------------------------------------
🔷 MORE EXAMPLES
The following scenes were all built entirely in Pine Script™ v6 using Pine3D as the rendering layer. They exist to demonstrate that the library is a real engine capable of complex, production grade visualizations.
🔸 4D Hypercube (Tesseract). A rotating tesseract, projected from 4D to 3D to 2D in real time using a custom 4D rotation matrix layered on top of Pine3D's standard projection pipeline.
🔸 Solar System. Following the publication of my 3D Solar System back in 2024, which introduced new graphical rendering concepts into Pine Script, we have seen a wave of various interpretations of the underlying vector classes, ranging from tutorials to niche specific integrations using hardcoded math. It became clear that a unified architecture was needed, one that would lower the barrier to entry while simultaneously handling the optimization process, which is both complex and error prone to do manually.
That architecture is what Pine3D delivers. Below is a re-creation of the classic 3D Solar System rebuilt entirely on top of the library. It uses a fraction of the original code , renders roughly 5x faster , and adds real lighting cast directly from the Sun , all while consuming only a third of the available drawing budget thanks to the occlusion and culling mechanisms Pine3D handles out of the box.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Top Level Entry Points. newScene() creates a ready to use Scene with a default camera and light. render(scene, ...) draws the current frame and auto clears the previous frame's chart drawings; see the Renderer section above for the full parameter list. vec3(x, y, z) creates a Vec3. colorBrightness() is an exported color utility helper.
🔸 Mesh Factories.
Primitives - cube() , cuboid() , pyramid() , plane() , sphere() , cylinder() , torus() , grid() , disc() , circle() for ready made geometry.
customMesh(verts, faces) - Low level escape hatch for authoring your own topology.
mergeMeshes(meshes, tag, removeInterior) - Bakes transforms and combines many meshes into one. With removeInterior = true , coincident faces with opposing normals (e.g. shared walls between adjacent cubes in a grid) are culled so only the exterior shell survives, a major optimization for dense voxel style scenes.
surface(heights, size, lowCol, highCol, levels, axisX, axisZ) - Creates a contour surface mesh.
bars3D(values, barWidth, barDepth, spacing, lowCol, highCol, maxHeight) - Creates a combined 3D bar chart mesh; add labels with the chainable barLabels(names, values) method.
🔸 UDT Constructors. Overlay primitives and face descriptors are plain UDTs. Because these types have many fields, always instantiate them with named arguments rather than positional, e.g. Label3D.new(position = pos, txt = "•") :
Face - fields: vi (array of vertex indices into the parent mesh), col . Used when authoring customMesh() topology; every face must have at least 3 indices and should be planar.
Label3D - fields: position , txt , textColor , bgColor , labelStyle , labelSize , fontFamily , tooltip , visible , tag . Only position is required.
Line3D - fields: start , end , col , width , visible , tag , lineStyle .
Polyline3D - fields: points , col , fillColor , width , closed , visible , tag , lineStyle .
Vec3.new(x, y, z) or the vec3(x, y, z) shorthand.
🔸 Trail Primitive. trail3D(size, capacity, trailCol, minSamples) creates a streamed Trail3D primitive with a main trail, two projection polylines, and a cage polyline. capacity is internally clamped to 300 samples to keep the rolling buffer inside Pine's execution budget; passing a larger value silently resolves to 300. minSamples (default 60) is the sample count at which the cage reaches its full cube width: below that the cage stays cube shaped and samples stretch across it; above that the cage grows rightward at a fixed step until capacity is hit. scene.add(trail) registers the sub primitives into the scene. Trail3D methods: pushSample() , axisLabels() , cage() , moveTo() , show() , hide() .
🔸 Mesh Methods.
Transform - moveTo() , moveBy() , rotateTo() , rotateBy() , scaleTo() , scaleUniform() .
Appearance - setColor() , setFaceColor() , setStyle() , show() , hide() , setTag() .
Stroke styling (direct) - mesh.lineWidth := 3 and mesh.lineStyle := line.style_dashed control width and style of every visible mesh edge in wireframe modes and the outline of solid faces in drawMode = "poly" .
Shadow opt out (direct) - mesh.castShadow := false excludes the mesh from shadow casting while still receiving light. Useful for ghost overlays, debug geometry, or semi transparent meshes you do not want occluding the scene.
Lifecycle - clone() , faceCount() , invalidateCache() .
Data mutation - updateSurface() and updateBars() refresh persistent meshes in place. updateBars() refreshes any bar label positions automatically; pass catLabels / valLabels to also update the text.
Contour helpers - gridBox() and gridLabels() queue overlays on the mesh and hand them to the scene when you call scene.add(mesh) .
Bar helpers - barLabels() is chainable on a bars3D() mesh and queues its category and value labels for the next scene.add(mesh) .
Note: rotateTo() and rotateBy() expect degrees. The low level Vec3.rotateX/Y/Z() methods work in radians.
🔸 Scene Methods.
Lighting - setLightDir() , setLightPos() , setLightMode() , setAmbient() , setShadowStrength() , showLightSource() .
Scene graph - add(mesh) , add(label) , add(array) , add(line) , add(polyline) , add(trail) , remove(index) , remove(tag) , clear() .
Lookup and navigation - getMesh() , getLabel() , getLine() , getPolyline() , lookAt() , totalFaces() .
Cache control - invalidateLightCache() after mutating light direction or scene bounds externally; invalidateAllCaches() to also invalidate every mesh's world vertex cache (use after directly mutating mesh.vertices ).
Note: scene.clear() clears the scene graph itself. render() only clears the previous frame's PulseWire drawings.
🔸 Camera Methods. setPosition(x, y, z) moves the camera. lookAt(x, y, z) / lookAt(vec3) points at a world space target. orbit(angleX, angleY, distance) does a spherical orbit around the current target. setFov(val) sets the perspective scale factor. Camera fields ( position , target , fov ) are also directly mutable via assignment when you need to tune them outside the provided setters, e.g. scene.camera.fov := 1200.0 .
🔸 Light Field Mutation. In addition to the scene level convenience setters, every field on scene.light is directly mutable for fine grained tuning: scene.light.selfShadow := true enables self shadowing, scene.light.shadowBias := 0.2 adjusts the shadow acne offset, scene.light.shadowStrength and scene.light.ambient are also exposed. Mutate them after newScene() or between frames; the renderer reads them every call.
🔸 Vec3 Methods. Core math: add() , sub() , scale() , negate() , dot() , cross() , length() , normalize() , distanceTo() , lerp() . Rotation and helpers: rotateX() , rotateY() , rotateZ() , copy() , toString() .
🔸 Overlay Primitive Methods.
Label3D - moveTo() , moveBy() , setText() , setTextColor() , setTooltip() , show() , hide() , setTag() .
Line3D - setStart() , setEnd() , setPoints() , setColor() , show() , hide() , setTag() .
Polyline3D - setColor() , show() , hide() , setTag() .
Every UDT field is mutable via direct assignment for properties without a chainable setter:
Label3D - bgColor , labelStyle (label.style_*), labelSize (size.*), fontFamily (font.family_*), visible .
Line3D - width , lineStyle (line.style_solid / _dashed / _dotted / _arrow_left / _arrow_right / _arrow_both), visible .
Polyline3D - width , lineStyle (line.style_solid / _dashed / _dotted only; arrow styles are not supported by PulseWire's polyline primitive), fillColor , closed , visible .
Mutations are read per frame by the renderer, so they animate freely.
🔸 High Level Scene Helpers. wireGrid(scene, w, d, divX, divZ, col) adds a depth sorted ground grid. scene.add(array) adds a batch of labels in one call - the idiomatic way to push a scatter cloud into the scene.
🔸 Mesh Level Chainable Overlays. mesh.barLabels(names, values, ...) adds category and value labels on a bars3D() mesh. mesh.gridBox(col, divs) adds a wireframe bounding box cage on a surface() mesh. mesh.gridLabels(col, xName, yName, zName, ticks, fmt) adds axis titles and tick value labels on a surface() mesh; tick values auto refresh on updateSurface() . All three are queued on the mesh and drained into the scene by scene.add(mesh) .
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
Library

PriceActionLibrary "PriceAction"
Will draw out the market structure for the disired pivot length.
SetBarIndices(pivotHigh, pivotLow)
Sets the 'BarIndex' value of the 'Pivot' object. Useful if the pivot is from an other timeframe.
Parameters:
pivotHigh (Pivot) : The 'Pivot' object for the high pivot.
pivotLow (Pivot) : The 'Pivot' object for the low pivot.
Alert(turtleSoupsContext, settings)
Will fire off an alert if there is one. To be used lastly in the calling script.
Parameters:
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
VisualizeTurtleSoups(pivots, turtleSoups, turtleSoupsContext, settings)
Will visulize found turtle soups and add alert messages for it.
Parameters:
pivots (array) : All current pivots (high or low).
turtleSoups (array) : All bullish or bearish turtle soups.
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
GetPivots(settings)
Will get available pivots. Can be called from another timeframe.
Parameters:
settings (TurtleSoupSettings) : The settings for turtle soups.
Returns: A tuple of high and then low pivots.
SetPivots(turtleSoupsContext, settings, pivotHigh, pivotLow)
Will set the new pivots in turtleSoupsContext.
Parameters:
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
pivotHigh (Pivot) : The 'Pivot' object for the high pivot.
pivotLow (Pivot) : The 'Pivot' object for the low pivot.
Confirm(turtleSoups, turtleSoupsContext, settings, previousStructureBreakBarIndex, screener)
Will visualize turtle soups. To be called if 'TurtleSoupSettings.Confirmation' is true.
Parameters:
turtleSoups (array) : All bullish or bearish turtle soups.
turtleSoupsContext (TurtleSoups) : The context of all turtle soups.
settings (TurtleSoupSettings) : The settings for turtle soups.
previousStructureBreakBarIndex (int) : The bar index of the previous structure break (BOS/CHoCH/CHoCH+).
screener (Screener) : The 'Screener' object to be used for Pine Screening by Tradingview. The function will set 'TurtleSoupUntilBarIndex' if there's a confirmed turtle soup.
Liqudity(liquidity)
Will draw liquidity.
Parameters:
liquidity (Liquidity) : The 'PriceAction.Liquidity' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
EqualHighOrLow(structure)
Draws the boxes for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: The 'Pivot' that caused the break of structure, na otherwise.
ChangeOfCharacter(structure)
Will create lines when a change of character occures. This line will have a label with "CHoCH" or "CHoCH+".
Parameters:
structure (Structure)
Returns: The 'Pivot' that caused the change of character, na otherwise.
VisualizeCurrent(structure)
Will create a box with a background for between the latest high and low pivots. This can be used as the current trading range (if the pivots broke strucure somehow).
Parameters:
structure (Structure)
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
Time (series int) : The time where the pivot occured.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
LiquidityBroken (series bool) : Sets to true if a liquidity of the price level has happened.
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
Structure
Holds all the values for the market structure.
Fields:
LeftLength (series int) : Define the left length of the pivots used.
RightLength (series int) : Define the right length of the pivots used.
Type (series Type) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
FontSize (series int) : Holds the size of the font displayed.
AlertChangeOfCharacter (series bool) : Holds true or false if a change of character should be alerted or not.
AlertBreakOfStructure (series bool) : Holds true or false if a break of structure should be alerted or not.
AlerEqualPivots (series bool) : Holds true or false if equal highs/lows should be alerted or not.
Liquidity
Holds all the values for liquidity.
Fields:
LiquidityPivotsHigh (array) : All high pivots for liquidity.
LiquidityPivotsLow (array) : All low pivots for liquidity.
LiquidityConfirmationBars (series int) : The number of bars to confirm that a liquidity is valid.
LiquidityPivotsLookback (series int) : A number of pivots to look back for.
FontSize (series int) : Holds the size of the font displayed.
PriceAction
Holds all the values for the general price action and the market structures.
Fields:
Liquidity (Liquidity)
Swing (Structure) : Placeholder for all objects used for the swing market structure.
Internal (Structure) : Placeholder for all objects used for the internal market structure.
TurtleSoupSettings
Holds sll the values for the settings for turtle soups.
Fields:
PivotLeftLenght (series int) : Define the left length of the pivots used.
PivotRightLenght (series int) : Define the right length of the pivots used.
Lookback (series int) : Set how many pivots back that will be used.
Confirmation (series bool) : Set if you want confirmation to be needed for q turtle soup to be formed (e g. a CHoCH).
Color (series color) : The color of turtle soups.
ScreenerKeep (series int) : Set the number of bars that the plot 'Turtle soup' will have a value after a turtle soup is found.
AlertFrequency (series string) : Set the frequency of alerts, possible values are 'alert.freq_all', 'alert.freq_once_per_bar' or 'alert.freq_once_per_bar_close'.
TurtleSoup
To be used when a turtle soup is found and holds all values needed for it.
Fields:
Line (series line) : The line object between the pivot and the turtle soup.
Box (series box) : The bos for the turtle soup.
Start (series int) : The first bar of the turtle soup.
End (series int) : The last bar of the turtle soup.
Pivot (Pivot) : The pivot which liquidity was taken by the turtle soup.
Screener
Holds all values to be used in the Pine Screener by Tradingview.
Fields:
TurtleSoupUntilBarIndex (series int) : Pine Screener value for turtle soups.
TurtleSoups
TurtleSoups The entire context for all turtle soups.
Fields:
Highs (array) : The high pivots.
Lows (array) : The low pivots.
Bullish (array) : Bullish turtle soups.
Bearish (array) : Bearish turtle soups.
AlertMessages (array) : All messages for the current iteration. Library

Library

OriginLifecycleLibrary "OriginLifecycle"
Strict Highlander v7 origin lifecycle for engulfing indicators.
Exports enums, an OriginCandidate UDT, and four helper functions
used by engulfing_opportunities_v20.6+ to detect, track, promote,
invalidate, and consume origin levels discovered on lower
timeframes inside an engulfment zone.
Published-as-library rationale: the engulfing indicator is already at Pine v6's
top-level-declaration limit (CE10295). Moving these types and functions into a
library frees ~7 declarations in the main script without changing semantics.
Reference: highlander_v7.pine:212-293 for the state-transition rules this
implementation mirrors.
tickStateMachine(c, bO, bH, bL, bC, bTime)
Pure state-transition function. One closed LTF bar in,
updated candidate out. Mirrors highlander_v7.pine:212-293.
Parameters:
c (OriginCandidate) : The current candidate state.
bO (float) : Bar open.
bH (float) : Bar high.
bL (float) : Bar low.
bC (float) : Bar close.
bTime (int) : Bar start time in ms.
Returns: Updated OriginCandidate with `lastProcessedTime := bTime`.
Caller is responsible for:
- Only passing CLOSED LTF bars.
- Skipping bars whose time <= c.lastProcessedTime.
- On BROKEN_BSUT, looking for a retest in subsequent bars to delete.
scanForBreakCandidates(isBullish, zoneLow, zoneHigh, prevO, prevH, prevL, prevC, prevT, currO, currH, currL, currC, currT, ltfValid, ltfMin, tfLabel, outCandidates)
Find new BREAK pairs in the engulfment zone and push
them to `outCandidates` if not already tracked. De-dup
key is (price, createdTime, tfLabel).
Parameters:
isBullish (bool) : true -> look for SUPPORT (green-green) pairs;
false -> look for RESISTANCE (red-red) pairs.
zoneLow (float) : Lower bound of the engulfment zone (inclusive).
zoneHigh (float) : Upper bound of the engulfment zone (inclusive).
prevO (array)
prevH (array)
prevL (array)
prevC (array)
prevT (array)
currO (array)
currH (array)
currL (array)
currC (array)
currT (array)
ltfValid (bool) : Pre-computed validity flag for this LTF.
ltfMin (int) : LTF length in minutes (baked into each new candidate).
tfLabel (string) : Display string, e.g. "1H".
outCandidates (array) : The per-pattern candidate array to push into.
Returns: Nothing (mutates outCandidates).
processNewLTFBars(candidates, ltfMin, prevO, prevH, prevL, prevC, prevT, currO, currH, currL, currC, currT, ltfValid)
Drive the state machine across unprocessed LTF bars for every
candidate whose `ltfMinutes == ltfMin`. Removes candidates
that reach BROKEN_BSUT AND see a retest within the buffer.
Parameters:
candidates (array) : The per-pattern candidate array to update.
ltfMin (int) : The LTF length this buffer represents; candidates with a
different ltfMinutes are skipped.
prevO (array)
prevH (array)
prevL (array)
prevC (array)
prevT (array)
currO (array)
currH (array)
currL (array)
currC (array)
currT (array)
ltfValid (bool) : Validity flag.
Returns: Nothing (mutates candidates).
applyConsumedOnTouch(candidates, greedyEntries, greedyConsumedFlags, isBullish, curLow, curHigh)
Per-tick sweep. Marks CONFIRMED origins and
untouched greedy entries as consumed once price
wicks into them. Caller passes `curLow`/`curHigh`
because library functions cannot reference the
`low`/`high` chart globals directly.
Parameters:
candidates (array) : Per-pattern origin-candidate array.
greedyEntries (array) : Per-pattern greedy-entry price array.
greedyConsumedFlags (array) : Parallel bool array — resized lazily to match
greedyEntries size.
isBullish (bool) : Drives the touch check for greedy entries
(origins use their own per-candidate dir).
curLow (float) : Current bar low (pass `low` from caller).
curHigh (float) : Current bar high (pass `high` from caller).
Returns: Nothing (mutates both arrays).
OriginCandidate
A single tracked origin candidate.
Fields:
tfLabel (series string) : Display string ("1H", "5m" etc.).
ltfMinutes (series int) : Lower-timeframe length in minutes; used for the
price (series float) : The origin level price.
dir (series OriginDir) : UP (support) or DOWN (resistance).
state (series OriginState) : Current lifecycle state.
firstTouchTime (series int) : ms timestamp of first touch (0 if `touchSeen == false`).
touchSeen (series bool) : True once this candidate has been touched at least once.
createdTime (series int) : ms timestamp of the d1 bar that formed the BREAK pair.
lastProcessedTime (series int) : ms timestamp of the last LTF bar fed through the
consecutiveDirCount (series int) : Counter for 2-bar CONFIRMED confirmation, 0-2. Library

HeikinAshiTrendUtilities
Library HeikinAshiTrendUtilities
This library contains reusable Heikin Ashi helpers for building Pine scripts that use Heikin Ashi as more than a candle style.
It centralizes the Heikin Ashi foundation, HA-based oscillator engines, streak and confirmed-trend logic, Pressure Meter helpers, max-move scanning, Fib Backbone structure helpers, and Primary Trend helpers so those parts do not need to be rewritten across multiple scripts.
Everything on the example chart is materially driven by the library, whether through the Heikin Ashi calculations themselves, the HA-based oscillator and pressure engine, the predictive close logic, the smoothed HA overlay, the Fib Backbone context window, or the structure geometry used to project key analytical visuals.
How to use
Import the library near the top of your script in global scope, alongside any other imports, before you start calling its helpers.
Typical placement:
• //@version=6
• indicator(...) or strategy(...)
• import MYNAMEISBRANDON/HeikinAshiTrendUtilities/1 as haUtils
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual: www.pulsewire.com
➖Heikin Ashi Core Helpers➖
These helpers handle the basic building blocks of Heikin Ashi. They let a script create standard HA candles, estimate the price needed to flip the current HA candle, and generate a smoothed HA version for a cleaner trend view. In other words, this region provides the core HA math used to build the rest of the library’s trend, engine, and structure tools.
heikinAshi(openValue, closeValue, highValue, lowValue, haOpenPrev, haClosePrev)
Builds one Heikin Ashi candle from real OHLC and prior HA state
Parameters:
openValue (float): Real open
closeValue (float): Real close
highValue (float): Real high
lowValue (float): Real low
haOpenPrev (float): Prior Heikin Ashi open
haClosePrev (float): Prior Heikin Ashi close
Returns: HA open, HA close, HA high, HA low, is HA up, is HA down
haPredictClose(haOpen, openValue, highValue, lowValue)
Estimates the real close price needed to flip the current HA candle
Parameters:
haOpen (float): Current Heikin Ashi open
openValue (float): Real open
highValue (float): Real high
lowValue (float): Real low
Returns: Predicted real close needed to flip the HA candle
smoothedHeikinAshi(openValue, highValue, lowValue, closeValue, len1, len2)
Builds double-smoothed Heikin Ashi values from real OHLC inputs
Parameters:
openValue (float): Real open
highValue (float): Real high
lowValue (float): Real low
closeValue (float): Real close
len1 (simple int): First EMA smoothing length applied to real OHLC
len2 (simple int): Second EMA smoothing length applied to HA OHLC
Returns: Smoothed HA open, smoothed HA high, smoothed HA low, smoothed HA close, is smoothed HA up, is smoothed HA down
➖HA Oscillator Foundation Helpers➖
These helpers turn raw Heikin Ashi candle movement into a usable oscillator foundation. They measure the HA candle’s bullish or bearish range, normalize that movement so it can be compared more consistently across bars, and build upper/lower guide levels that help a script judge when that oscillator is stretching into stronger trend pressure. In other words, this region creates the base signal that the HA Blend, HA Range Base, color engine, and Pressure Meter can build from.
haSignedRangePct(haHigh, haLow, haClose, haIsBull, haIsBear)
Returns the signed HA range-percent foundation used by the oscillator engine
Parameters:
haHigh (float): Heikin Ashi high
haLow (float): Heikin Ashi low
haClose (float): Heikin Ashi close
haIsBull (bool): True when the current HA candle is bullish
haIsBear (bool): True when the current HA candle is bearish
Returns: Signed HA range-percent foundation
haPreparedOscSource(signedSrc, normLen, useClamp, clampRange)
Returns the normalized / optionally clamped HA oscillator source
Parameters:
signedSrc (float): Signed HA foundation
normLen (simple int): Normalization lookback length
useClamp (simple bool): Whether the normalized result should be clamped
clampRange (float): Absolute clamp boundary when useClamp is true
Returns: Prepared HA oscillator source
haOscGuides(src, lookback, guideFactor)
Returns upper and lower threshold guides from an oscillator series
Parameters:
src (float): Oscillator series
lookback (simple int): Guide lookback window
guideFactor (float): Scaling factor applied to the highest/lowest values
Returns: Upper guide, lower guide
➖HA Blend Engine Helpers➖
These helpers take the prepared HA oscillator source and turn it into a smoother trend engine by blending multiple EMA pairs together. They let the script choose a faster, more balanced, or slower blend profile, then optionally smooth that final output one more time. In other words, this region builds the more layered, trend-following version of the HA oscillator engine.
haBlendPairStackText(pairSet)
Returns the active EMA pair-stack text for the selected HA Blend pair set
Parameters:
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
Returns: Pair-stack text
haBlendEngineCore(src, pairSet)
Returns the raw HA Blend engine core before final smoothing
Parameters:
src (float): Prepared HA signed source used by the blend engine
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
Returns: Raw HA Blend engine core
haBlendEngine(src, pairSet, useFinalSmooth, finalSmoothLen, finalSmoothType)
Returns the final HA Blend engine with optional final smoothing
Parameters:
src (float): Prepared HA signed source used by the blend engine
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
useFinalSmooth (simple bool): Whether final smoothing should be applied
finalSmoothLen (simple int): Final smoothing length
finalSmoothType (simple string): Final smoothing type. Expected values: "EMA" or "SMA"
Returns: Final HA Blend engine
➖HA Range Base Engine Helpers➖
These helpers take the prepared HA oscillator source and smooth it in a more direct way than the Blend engine. Instead of combining multiple EMA pairs, they use one selected smoothing length and MA type to create a cleaner base trend signal, with the option to smooth that result one more time. In other words, this region builds the simpler, more straightforward version of the HA oscillator engine.
haRangeEngineCore(src, rangeLen, rangeMaType)
Returns the raw HA Range Base engine core before final smoothing
Parameters:
src (float): Prepared HA signed source used by the Range Base engine
rangeLen (simple int): Core smoothing length used by the Range Base engine
rangeMaType (simple string): Core smoothing type. Expected values: "EMA" or "SMA"
Returns: Raw HA Range Base engine core
haRangeEngine(src, rangeLen, rangeMaType, useFinalSmooth, finalSmoothLen, finalSmoothType)
Returns the final HA Range Base engine with optional final smoothing
Parameters:
src (float): Prepared HA signed source used by the Range Base engine
rangeLen (simple int): Core smoothing length used by the Range Base engine
rangeMaType (simple string): Core smoothing type. Expected values: "EMA" or "SMA"
useFinalSmooth (simple bool): Whether final smoothing should be applied
finalSmoothLen (simple int): Final smoothing length
finalSmoothType (simple string): Final smoothing type. Expected values: "EMA" or "SMA"
Returns: Final HA Range Base engine
➖HA Threshold Color Helpers➖
This helper takes centered oscillator behavior and turns it into a usable visual color state. It helps a script decide when the HA-based oscillator is rising or falling above or below its guide levels so candles, rows, or other visuals can reflect stronger or weaker trend pressure.
haThresholdStateColor(src, upperGuide, lowerGuide, aboveUpperRiseColor, aboveZeroRiseColor, aboveZeroFallColor, belowZeroFallColor, belowLowerFallColor, belowZeroRiseColor)
Resolves a visual color from centered-oscillator threshold state
Parameters:
src (float): Source series
upperGuide (float): Upper threshold guide
lowerGuide (float): Lower threshold guide
aboveUpperRiseColor (color): Color used when src is above the upper guide and rising
aboveZeroRiseColor (color): Color used when src is above zero and rising
aboveZeroFallColor (color): Color used when src is above zero and falling
belowZeroFallColor (color): Color used when src is below zero and falling
belowLowerFallColor (color): Color used when src is below the lower guide and falling
belowZeroRiseColor (color): Color used when src is below zero and rising
Returns: Resolved visual color
➖HA Structure Scan Helpers➖
This helper scans a chosen lookback window and finds the strongest completed move inside it. It compares bullish and bearish candidates in the same scan, then returns whichever move was stronger along with the start and end anchors. In other words, this region gives a script a reusable way to locate the dominant move that can later be used for Fib Backbone structure, Primary Max Move logic, or other trend-structure work. :contentReference {index=0} :contentReference {index=1}
haScanMaxMove(lookback, includeCurrentBar, highSeries, lowSeries)
Scans a lookback window for the strongest upward or downward percentage move
Parameters:
lookback (simple int): Number of bars to scan
includeCurrentBar (simple bool): Whether bar 0 should be included in the scan
highSeries (float): High series used for upward and downward move detection
lowSeries (float): Low series used for upward and downward move detection
Returns: Winning direction, winning percent move, winning start bars-ago, winning end bars-ago, winning span bars
➖HA Streak Helpers➖
These helpers let a script keep track of active Heikin Ashi streaks. They determine whether the current HA sequence is bullish or bearish, count how long that streak has been running, assign a tier color based on streak length, and measure how far price has moved from the streak’s starting point. In other words, this region helps turn raw HA trend runs into usable streak state, color, and percent-move data for candles, rows, labels, and trend readouts. :contentReference {index=0}
haStreakState(haOpen, haClose, bullCountPrev, bearCountPrev)
Resolves raw HA bull/bear state, streak counts, and streak start offset
Parameters:
haOpen (float): Current Heikin Ashi open
haClose (float): Current Heikin Ashi close
bullCountPrev (int): Prior bullish streak count
bearCountPrev (int): Prior bearish streak count
Returns: is HA bullish, is HA bearish, bullish streak count, bearish streak count, current streak length, streak start bars-ago
haStreakTierColor(isHaBull, isHaBear, bullCount, bearCount, streakTierBars, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, neutralColor)
Returns the active streak-tier color from bull/bear streak counts
Parameters:
isHaBull (bool): True when the current HA streak is bullish
isHaBear (bool): True when the current HA streak is bearish
bullCount (int): Current bullish streak count
bearCount (int): Current bearish streak count
streakTierBars (simple int): Number of bars required before advancing to the next tier
bullTier1 (color): Bullish tier 1 color
bullTier2 (color): Bullish tier 2 color
bullTier3 (color): Bullish tier 3 color
bullTier4 (color): Bullish tier 4 color
bearTier1 (color): Bearish tier 1 color
bearTier2 (color): Bearish tier 2 color
bearTier3 (color): Bearish tier 3 color
bearTier4 (color): Bearish tier 4 color
neutralColor (color): Fallback color when no active streak is available
Returns: Active streak-tier color
haStreakPct(isHaBull, isHaBear, streakBars, highSeries, lowSeries)
Returns the wick-based percent move from the streak start to the current bar
Parameters:
isHaBull (bool): True when the current HA streak is bullish
isHaBear (bool): True when the current HA streak is bearish
streakBars (int): Current active streak length
highSeries (float): High series used for streak measurement
lowSeries (float): Low series used for streak measurement
Returns: Wick-based streak percent move
➖Confirmed HA Trend Helpers➖
These helpers let a script work with a slower, confirmation-based HA trend instead of flipping immediately on the first opposite HA candle. They track the currently confirmed direction, count how many opposite candles are building toward the next possible flip, project the confirmed trend using regular-price body or wick anchors, and measure how far that confirmed trend has moved from its confirmed start. In other words, this region helps scripts build a more stable HA trend model that filters out some of the noise of raw HA flips. :contentReference {index=0} :contentReference {index=1}
haConfirmedTrendState(enabled, rawDir, confirmBars, dirPrev, oppCountPrev, startBarPrev, firstOppBarPrev)
Resolves confirmed trend direction, build count, and confirmed start bar
Parameters:
enabled (simple bool): Whether the confirmed-trend engine is active
rawDir (int): Current raw HA direction: +1 bull, -1 bear, 0 neutral
confirmBars (simple int): Consecutive opposite raw HA bars required to confirm a flip
dirPrev (int): Prior confirmed direction
oppCountPrev (int): Prior opposite-side build count
startBarPrev (int): Prior confirmed trend start bar index
firstOppBarPrev (int): Prior first opposite raw HA bar index
Returns: Confirmed direction, opposite-side build count, confirmed start bar index, first opposite raw HA bar index, confirmed leg bars, confirmed start bars-ago
haConfirmedTrendProjection(confirmedDir, startOffset, openValue, highValue, lowValue, closeValue, anchorMode, pathMode, forwardBars)
Returns confirmed trend projection geometry from body/wick anchor rules
Parameters:
confirmedDir (int): Confirmed direction: +1 bull, -1 bear, 0 neutral
startOffset (int): Confirmed start bars-ago offset
openValue (float): Regular-price open
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
anchorMode (simple string): Projection anchor mode: "Body" or "Wick"
pathMode (simple string): Projection path mode: "Same Side" or "Opposite Side"
forwardBars (simple int): Number of bars forward for projection
Returns: Has valid projection, start Y, current Y, future Y, slope
haConfirmedTrendPct(confirmedDir, startOffset, highSeries, lowSeries)
Returns confirmed streak percent movement from the confirmed start bar
Parameters:
confirmedDir (int): Confirmed direction: +1 bull, -1 bear, 0 neutral
startOffset (int): Confirmed start bars-ago offset
highSeries (float): HA high series used for confirmed move measurement
lowSeries (float): HA low series used for confirmed move measurement
Returns: Confirmed streak percent move
➖HA Pressure Meter Helpers➖
These helpers take the HA-based oscillator engine and convert it into an easier 0–100 pressure reading. They help a script decide when bullish or bearish pressure is becoming active, assign matching tier colors for rows or other visuals, and return the color state for a pressure strip or similar chart-edge signal. In other words, this region turns the HA oscillator into a simpler pressure model that is easier to read at a glance.
haPressureMeter(rawOsc, bullAnchor, bearAnchor)
Normalizes a raw oscillator value into a 0-100 Pressure Meter
Parameters:
rawOsc (float): Raw oscillator value
bullAnchor (float): Raw oscillator value that should map to 100
bearAnchor (float): Raw oscillator value that should map to 0
Returns: Pressure Meter value in the 0-100 range
haPressureState(pressureMeter, bullThreshold, bearThreshold)
Resolves bullish, bearish, and neutral threshold state from the Pressure Meter
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullThreshold (float): Meter level where bullish pressure becomes active
bearThreshold (float): Meter level where bearish pressure becomes active
Returns: Bull-active, bear-active, neutral-between
haPressureTierColors(pressureMeter, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, fallbackBg)
Returns tier-based pressure-row background and readable text color
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullTier1 (color): Bull tier 1 color
bullTier2 (color): Bull tier 2 color
bullTier3 (color): Bull tier 3 color
bullTier4 (color): Bull tier 4 color
bearTier1 (color): Bear tier 1 color
bearTier2 (color): Bear tier 2 color
bearTier3 (color): Bear tier 3 color
bearTier4 (color): Bear tier 4 color
fallbackBg (color): Fallback background when the meter is na
Returns: Row background color, row text color
haPressureStripColor(pressureMeter, bullThreshold, bearThreshold, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, neutralColor, activeTransp, neutralTransp)
Returns active or neutral strip color from the Pressure Meter state
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullThreshold (float): Meter level where bullish pressure becomes active
bearThreshold (float): Meter level where bearish pressure becomes active
bullTier1 (color): Bull tier 1 color
bullTier2 (color): Bull tier 2 color
bullTier3 (color): Bull tier 3 color
bullTier4 (color): Bull tier 4 color
bearTier1 (color): Bear tier 1 color
bearTier2 (color): Bear tier 2 color
bearTier3 (color): Bear tier 3 color
bearTier4 (color): Bear tier 4 color
neutralColor (color): Neutral-zone base color
activeTransp (int): Transparency used when bull or bear pressure is active
neutralTransp (int): Transparency used inside the neutral zone
Returns: Strip color
➖Fib Backbone Structure Helpers➖
These helpers take a winning max-move scan and turn it into the structure a script can use for Fib Backbone analysis. They define the backbone’s start and end anchors, determine the related support/resistance anchor geometry, calculate Fib level prices between those anchors, and measure how far current price is from those levels. In other words, this region helps convert a dominant move into a reusable backbone structure that can support diagonals, S/R anchors, boxes, and Fib-based readouts.
haFibBackboneStructure(dir, startBA, endBA, openValue, highValue, lowValue, closeValue)
Returns backbone coordinates, S/R anchors, and anchor-box geometry
Parameters:
dir (int): Winning move direction: +1 bull, -1 bear, 0 none
startBA (int): Winning move start bars-ago
endBA (int): Winning move end bars-ago
openValue (float): Regular-price open
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
Returns: ok, xStart, xEnd, yStart, yEnd, startIsRes, endIsRes, anchorTopS, anchorBotS, anchorTopE, anchorBotE, isTopS, isTopE
haFibLevelPrice(yStart, yEnd, fibLevel)
Returns the price of one fib level between the backbone anchors
Parameters:
yStart (float): Backbone start anchor price
yEnd (float): Backbone end anchor price
fibLevel (float): Fib level such as 0.236, 0.382, 0.50, 0.618, 0.786
Returns: Fib level price
haFibPctFromClose(closeValue, fibPrice)
Returns percent distance from close to a fib level
Parameters:
closeValue (float): Current close
fibPrice (float): Fib level price
Returns: Percent from close to fib level
➖Fib Backbone Context Window Helpers➖
These helpers build the larger context window around the active Fib Backbone lookback. They let a script define the left/right range of that window, calculate its current high and low bounds, and find the midpoint of the same structure. In other words, this region helps frame the broader area that the active backbone move is being selected from, so the move can be viewed in context rather than in isolation.
haFibContextWindow(lookback, includeCurrentBar, sourceMode, highValue, lowValue, closeValue)
Returns the active Fib Backbone context window geometry
Parameters:
lookback (simple int): Context-window lookback length
includeCurrentBar (simple bool): Whether the current bar participates in the active window
sourceMode (simple string): Source selection. Expected values: "Wicks" or "Closes"
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
Returns: ok, leftX, rightX, windowBars, windowHigh, windowLow, leftHigh, leftLow
haFibContextMidpoint(ok, windowHigh, windowLow)
Returns the midpoint of the active Fib Backbone context window
Parameters:
ok (bool): Whether the context window is valid
windowHigh (float): Active context-window high
windowLow (float): Active context-window low
Returns: Context-window midpoint
➖Primary Trend Window Helpers➖
These helpers scan a lookback window to find the strongest completed HA streak and turn that winner into usable trend information. They identify the winning streak, assign it the correct tier color, and return the anchor coordinates needed to project that streak as a chart-side diagonal. In other words, this region helps a script reduce a larger HA trend window down to its most important completed streak structure.
haPrimaryTrendWinner(lookback, haBull, haBear, bullCount, bearCount, haHigh, haLow)
Returns the strongest completed HA streak inside the lookback window
Parameters:
lookback (simple int): Number of bars to scan
haBull (bool): Bullish HA state series
haBear (bool): Bearish HA state series
bullCount (int): Bullish HA streak-count series
bearCount (int): Bearish HA streak-count series
haHigh (float): HA high series used for wick-based streak measurement
haLow (float): HA low series used for wick-based streak measurement
Returns: Winning streak length, winning direction, winning percent move, winning start bars-ago, winning end bars-ago, winning validity state
haPrimaryTrendTierColor(dir, streakLen, streakTierBars, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, fallbackBg)
Returns the winning Primary Trend tier color
Parameters:
dir (int): Winning streak direction: +1 bull, -1 bear, 0 none
streakLen (int): Winning streak length
streakTierBars (simple int): Number of bars required before advancing to the next tier
bullTier1 (color): Bullish tier 1 color
bullTier2 (color): Bullish tier 2 color
bullTier3 (color): Bullish tier 3 color
bullTier4 (color): Bullish tier 4 color
bearTier1 (color): Bearish tier 1 color
bearTier2 (color): Bearish tier 2 color
bearTier3 (color): Bearish tier 3 color
bearTier4 (color): Bearish tier 4 color
fallbackBg (color): Fallback background when no valid winner exists
Returns: Winning tier color
haPrimaryTrendCoords(dir, startBA, endBA, highSeries, lowSeries)
Returns diagonal coordinates from the winning streak anchors
Parameters:
dir (int): Winning streak direction: +1 bull, -1 bear, 0 none
startBA (int): Winning start bars-ago
endBA (int): Winning end bars-ago
highSeries (float): High series used for line anchors
lowSeries (float): Low series used for line anchors
Returns: ok, x1, x2, y1, y2
NOTES
This is a Heikin-Ashi-specific utility library. It is meant to provide the reusable HA math, state, and structure layer. Final rendering choices such as plot style, line objects, boxes, labels, tables, and overall UI layout are expected to remain script-level decisions.
Thanks to SimpleCryptoLife for the open-source HA core functions heikinAshi() & haPredictClose() and thus the inspiration that they've given me to create HA-based indicators for the HA trader enthusiast.
Library

Library

AvwapLibLibrary "AvwapLib"
Shared functions: AVWAP, stage classification, position sizing,
swing detection, and risk helpers. Used by all strategy() scripts.
NOTE: rs_vs_spy() cannot live here (request.security() banned in
library exports) — each strategy implements it inline.
avwap(src, anchor_bar, max_lookback)
Anchored VWAP from a specific bar to current bar.
Uses loop approach with bounded max_lookback for robustness.
Parameters:
src (float) : Source price (typically hlc3)
anchor_bar (int) : Bar index of anchor point (from find_swing_high/low)
max_lookback (simple int) : Maximum bars to look back (cap for performance, default 500 ~2yr daily)
Returns: AVWAP value, or na if anchor invalid or out of range
avwap_slope(avwap_val, lookback)
AVWAP slope — rate of change over lookback period.
Parameters:
avwap_val (float) : AVWAP series
lookback (simple int) : Number of bars for slope calculation
Returns: Slope (positive = rising, negative = falling), or na
dcr()
Daily Closing Range — where price closed within the bar's range.
Returns: DCR as percentage (0 = closed at low, 100 = closed at high)
rvol(period)
Relative Volume — current bar volume vs historical average.
Uses volume offset to avoid including current bar in average.
Parameters:
period (simple int) : Lookback period for average calculation
Returns: RVOL ratio (>1 = above average)
is_stage2()
Stage 2 check (simplified Weinstein model).
Conditions: price > SMA50, SMA50 rising (vs 10 bars ago), price > SMA200.
Returns: true if all Stage 2 conditions met
calc_shares(entry, stop, risk_pct, equity)
Position size: shares = floor(equity * risk% / risk_per_share).
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
risk_pct (float) : Risk as decimal (0.01 = 1%)
equity (float) : Account equity
Returns: Number of shares (integer), 0 if invalid
rr_valid(entry, stop, target, min_rr)
Validate risk/reward ratio meets minimum threshold.
Parameters:
entry (float) : Entry price
stop (float) : Stop-loss price
target (float) : Target price
min_rr (float) : Minimum required R:R (e.g., 2.0 for 1:2)
Returns: true if R:R >= min_rr
confirmed()
Returns true only on confirmed (closed) bars.
MUST gate every entry/exit signal to prevent repainting.
Returns: true if bar is confirmed
find_swing_high(strength)
Bar index of the most recent confirmed swing high.
Uses ta.pivothigh — confirmed 'strength' bars after the actual high.
Result persists (via var) until a new swing high is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing high, or na if none found yet
find_swing_low(strength)
Bar index of the most recent confirmed swing low.
Uses ta.pivotlow — confirmed 'strength' bars after the actual low.
Result persists (via var) until a new swing low is detected.
Parameters:
strength (simple int) : Number of bars required on each side to confirm pivot
Returns: Bar index of last swing low, or na if none found yet Library

Library

KeyLevelsLibrary "KeyLevels"
Library for common trading levels including VWAP, session levels (Asia, London, NYC, Comex IB), HTF OHLC, and Opening Ranges.
--- IMPLEMENTATION INSTRUCTIONS ---
1. Save this script as a Library named "KeyLevels".
2. In your indicator/strategy, import it: `import /KeyLevels/1 as kl`
3. To get the data object, call: `levels = kl.getLevels()`
4. Access levels using dot notation: `levels.loH` (London High), `levels.nycH` (NYC High), `levels.cibH` (Comex IB High).
5. To get all levels in a single array for loops: `levelArray = kl.toArray(levels)`
--- TIMEZONE NOTE ---
The default timezone is "UTC-5" (New York). For accurate seasonal adjustments, use "America/New_York".
getLevels(vwapAnchor, vwapMult, rollingLen, htfAnchor, tz)
getLevels Calculates and returns a KeyLevelsData object with comprehensive trading levels.
Parameters:
vwapAnchor (string) : Anchor condition for the main VWAP (e.g., "1D", "1W").
vwapMult (float) : Standard deviation multiplier for VWAP bands.
rollingLen (int) : Length for the rolling VWAP calculation.
htfAnchor (string) : Anchor for the HTF VWAP (e.g., "1W", "1M").
tz (string) : Timezone for session calculations (default: "UTC-5").
Returns: A `KeyLevelsData` object containing the levels.
toArray(data)
toArray Converts a KeyLevelsData object into a flat array of floats.
Parameters:
data (KeyLevelsData) : The KeyLevelsData object to convert.
Returns: An array of floats containing all levels.
KeyLevelsData
KeyLevelsData Master structure to hold all calculated key levels (Flattened).
Fields:
vwapCenter (series float)
vwapUpper (series float)
vwapLower (series float)
htfVwapCenter (series float)
htfVwapUpper (series float)
htfVwapLower (series float)
rollingVwap (series float)
dailyOpen (series float)
asO (series float)
asH (series float)
asL (series float)
asC (series float)
loO (series float)
loH (series float)
loL (series float)
loC (series float)
nycO (series float)
nycH (series float)
nycL (series float)
nycC (series float)
cibO (series float)
cibH (series float)
cibL (series float)
cibC (series float)
ibO (series float)
ibH (series float)
ibL (series float)
ibC (series float)
ibMid (series float)
o5O (series float)
o5H (series float)
o5L (series float)
o5C (series float)
o15O (series float)
o15H (series float)
o15L (series float)
o15C (series float)
o30O (series float)
o30H (series float)
o30L (series float)
o30C (series float)
pdO (series float)
pdH (series float)
pdL (series float)
pdC (series float)
pwO (series float)
pwH (series float)
pwL (series float)
pwC (series float)
cwO (series float)
cwH (series float)
cwL (series float)
cwC (series float)
cmO (series float)
cmH (series float)
cmL (series float)
cmC (series float)
settlement (series float) Library

Library

BandsLibLibrary "BandsLib"
f_calc_survival_bands(basis, dev, shift_z, prob_pct, mr_shift)
Parameters:
basis (float) : Base price level (MA, median, etc.)
dev (float) : Standard deviation or volatility measure
shift_z (float) : Directional shift factor (e.g., vector pressure, momentum)
prob_pct (float) : Survival probability percentage (e.g., 10 = 10%)
mr_shift (float) : Mean reversion shift (optional, contrarian to shift_z)
Returns: Tuple of upper and lower survival bands
f_detect_squeeze(band_up, band_dn, price, damping)
Parameters:
band_up (float) : Upper band level
band_dn (float) : Lower band level
price (float) : Current price
damping (float) : Correlation damping factor (0-1)
Returns: Tuple of bullish/bearish squeeze signals and bandwidth percentile
f_detect_confluence(basis, fv, dev, tol_mult, min_lines)
Parameters:
basis (float) : Base price level (MA, median, etc.)
fv (float) : Fair value or equilibrium price
dev (float) : Standard deviation or volatility measure
tol_mult (float) : ATR multiplier for clustering tolerance
min_lines (int) : Minimum number of converging lines to trigger confluence Library

FMatrixSCLibraryLibrary "FMatrixSCLibrary"
defaultTheme()
calcEnv(adx, rsi, atr_pr, er, mean_ext, btcRet, date, dir)
Parameters:
adx (float)
rsi (float)
atr_pr (float)
er (float)
mean_ext (float)
btcRet (float)
date (string)
dir (string)
pushEnv(arr, snap, maxSize)
Parameters:
arr (array)
snap (EnvSnap)
maxSize (int)
calcSys(history, tradeNum, date, dir, r, wl, earlyExit, equity, peakEq, dd, dow, quarter, cycleYear)
Parameters:
history (array)
tradeNum (int)
date (string)
dir (string)
r (float)
wl (int)
earlyExit (bool)
equity (float)
peakEq (float)
dd (float)
dow (string)
quarter (string)
cycleYear (int)
pushSys(arr, snap, maxSize)
Parameters:
arr (array)
snap (SysSnap)
maxSize (int)
renderEnvTable(t, snaps, maxRows, sysCode, theme)
Parameters:
t (table)
snaps (array)
maxRows (int)
sysCode (string)
theme (SCTheme)
renderSysTable(t, snaps, maxRows, sysCode, theme)
Parameters:
t (table)
snaps (array)
maxRows (int)
sysCode (string)
theme (SCTheme)
SCTheme
Fields:
bg (series color)
hdr (series color)
row (series color)
row2 (series color)
txt (series color)
dim (series color)
cyan (series color)
bull (series color)
bear (series color)
gold (series color)
grid (series color)
EnvSnap
Fields:
date (series string)
dir (series string)
adx (series float)
rsi (series float)
atr_pr (series float)
er (series float)
mean_ext (series float)
btc_ret (series float)
SysSnap
Fields:
num (series int)
date (series string)
dir (series string)
r (series float)
wl (series int)
early_exit (series bool)
equity (series float)
peak_eq (series float)
dd (series float)
state (series string)
streak (series int)
wr20 (series float)
dow (series string)
quarter (series string)
cycle_year (series int) Library

Vantage_News_HistoricalVantage News is a Pine Script library that provides pre-market economic event filtering defaults intended for strategies that trade on YM futures. It determines a default for whether trading should be blocked, delayed, or allowed on any given day. This Historical file contains prior years.
Core Concept
News events are pre-compiled into Pine Script data libraries organized by half-year (LO1_News2025H1, LO1_News2025H2, etc.), updated weekly on Sundays. There are no API calls — events are baked into arrays of dates, times, type IDs, and severities.
Severity System
Can be configured to define or override three default severity tiers:
- Sev 3 (CPI, NFP, FOMC) — defaults to blocks the entire day or delays, depending on policy
- Sev 2 (ISM PMI, claims) — defaults to delay trading until the event time + a configurable post-delay window
- Sev 1 (secondary indicators) — defaults to no delays
Blocking vs Delaying
- Block: No trading for the full session. WillTradeToday() returns false.
- Delay: Trading allowed after eventTime + delayMinutes. IsDelayed(currentTimeMs) returns true until the release time passes.
Provides a per-event-type policy mechanism so overrides can force any event to block, delay, or be ignored regardless of its base severity.
Next Trading Window Calculation
FindNextTradingWindow() scans forward up to 14 days, skipping weekends and blocked days based on the provided configuration. If the next tradeable day has a delay, it returns the delayed start time — so an info panel can show e.g. "Mon 7:35 AM" to indicate the next trading opening
Exception Mappings
Each half-year library can ship per-event-type overrides (different severity, custom delay minutes, tags). When the applyLibExceptionMappings configuration is enabled, these override the base severity — allowing the data to carry date-specific adjustments.
Special Handling
CME early close days are encoded as a special event type. CheckCmeEarlyClose() returns a halt timestamp so a strategy can truncate the session.
Caching
Evaluation is lazy and memoized by date string — EvaluateForDate() only recomputes when the date changes. The event cache is built once at initialization via a day index for fast date lookups. Library

MarketStructureLibMarket Structure Library (MSL)
A Multi-Timeframe Structural Analysis Toolkit for Pine Script
A Developer's Library for Building Advanced Structural Analysis Indicators.
🎓 THEORETICAL FOUNDATION
The Market Structure Library (MSL) is a collection of functions and data types designed for Pine Script developers to build custom structural analysis indicators. It provides a framework for analyzing market geometry, liquidity, and order flow across multiple timeframes. The library's functions handle complex calculations related to multi-timeframe data aggregation and analysis.
The system is organized around four functional pillars that work together to provide a unified structural context.
Pillar 1: Unified Liquidity Context
The library's primary function is to create a unified view of market activity. It includes logic to automatically detect if real footprint data is available.
With Footprint Data: It utilizes bid-ask volume, delta, and Value Area metrics for analysis.
Without Footprint Data: It employs a mathematical OHLCV proxy to model bar dynamics and approximate buy/sell pressure, absorption, and aggressor intent.
This dual-mode capability allows indicators built with the library to function consistently regardless of the user's data source.
Pillar 2: Multi-Timeframe Structure Aggregation
Market structure is fractal, with higher timeframe levels influencing lower timeframe price action. The MSL is designed to manage this by providing a master container (MultiTFStructure) that holds and organizes structural data—including swing points, value areas, and dynamic levels—for up to four user-defined timeframes. This allows a script to query and act on a complete, multi-layered market picture.
Pillar 3: Dynamic Structure - The Siege Corridor
The MSL introduces ' Siege Corridors ,' which are dynamic trendlines projected from consecutive pivot points. These are data objects that are updated with price interaction statistics, including hit count , energy decay , order flow alignment , and the calculated probability of a break or failure .
Pillar 4: High-Probability Confluence Zones
Significant price action often occurs where structure from multiple timeframes aligns. The library's find_zones function is a discovery utility that scans all tracked levels across all timeframes. It identifies these Confluence Zones where levels cluster, calculating their combined strength, dominant type (supply/demand), and overall bias.
🔧 COMPREHENSIVE API & DATA TYPES
This library provides developers with a set of data structures (types) to utilize in their scripts. A clear understanding of these types is essential for proper implementation.
Core Data Types
MarketContext: A per-bar snapshot of liquidity, blending Footprint and OHLCV models. Includes unified_delta, absorption, spread_proxy, and vol_quality.
LevelLiquidity: A detailed analysis of order flow specifically at a structural level. Provides hold_probability, break_probability, and an action_type classifier ("defending", "absorbing", "attacking").
StructureLevel: Represents a single horizontal level (e.g., POC, VAH, Swing High/Low). Contains its price, level_type, timeframe, strength, age, and its own LevelLiquidity object.
SiegeCorridor: The complete object for a dynamic trendline. Contains anchor points, slope, hit_count, decay, and break_prob/fail_prob.
Container Types
TimeframeStructure: The container for all structural information for a single timeframe. It holds the poc, vah, val_, an array of all StructureLevel objects, and the res_corridor and sup_corridor.
MultiTFStructure: The master object that a script will primarily interact with. It holds up to four TimeframeStructure objects, providing the complete multi-timeframe view.
Analysis & State Types
ConfluenceZone: An object representing a cluster of levels. Contains the zone's average price, width, level_count, and combined_strength.
StructureState: A high-level summary for decision-making logic. Provides nearest_support, nearest_resistance, net_bias, and a boolean for whether price is inside_value.
IntrabarState: Designed for real-time, tick-level analysis. Indicates if price is currently touching a POC, VAH, Siege Corridor, or Confluence Zone.
🎨 VISUALIZING THE STRUCTURE (IMPLEMENTATION EXAMPLES)
The provided images demonstrate visualizations that can be built using the data objects from the MSL. The library supplies the calculated data; the developer controls the visual output.
Drawing Confluence Zones (Boxes)
Use the find_zones() function to get an array of ConfluenceZone objects. For each zone:
The box's vertical position is determined by zone.price.
The box's height is determined by zone.width.
The box's color can be conditional on zone.dominant_type ("supply" or "demand").
The box's styling (e.g., opacity) can be driven by zone.combined_strength.
Drawing Siege Corridors (Channels)
Access the res_corridor and sup_corridor from a TimeframeStructure object.
The central dashed line is drawn from corr.anchor_bar_a/corr.anchor_price_a to the current bar, extended by corr.slope.
Outer boundary lines can be drawn parallel to the central line, offset by an ATR-based value.
Drawing Value Area & Swing Levels (Horizontal Lines)
Iterate through the levels array within each TimeframeStructure.
Use level.price to draw the line.
Use get_level_color(level) to apply a consistent color scheme based on the level.level_type.
Creating Informative Labels
Labels can be generated by combining data from library objects. A label for a resistance level could display:
Level Type & Timeframe: level.level_type + level.timeframe
Hold/Break Probabilities: Access level.liquidity.hold_probability when price interacts with the level.
Siege Stats: For a siege corridor, display corr.hit_count and corr.fail_prob.
📚 DEVELOPER INTEGRATION GUIDE
This guide outlines the process for integrating the MSL into a Pine Script indicator.
Step 1: Import & Initialization
Import the library and initialize the master MultiTFStructure container in the script's global scope.
import DskyzInvestments/MarketStructureLib/1 as msl
var msl.MultiTFStructure structure = msl.create_structure()
Step 2: Define Timeframes & Collect Data
Define the timeframes for analysis. Use request.security to retrieve the required OHLCV and pivot data for each timeframe.
// --- INPUTS ---
tf1 = input.timeframe("15", "Timeframe 1")
pivot_len = input.int(15, "Pivot Lookback")
// --- DATA COLLECTION ---
// Request TF1 data using request.security()
// Collect historical arrays of highs, lows, pivots, etc. for TF1
Step 3: Get Unified Market Context
Once per bar, generate the fused liquidity context. This object is passed to other functions for liquidity calculations.
// --- MAIN LOGIC ---
float atr_val = ta.atr(14)
footprint fp = request.footprint(100, 70) // Optional: use 'na' if not using footprint
msl.MarketContext ctx = msl.get_market_context(open, high, low, close, volume, fp, ta.sma(volume, 20), nz(structure.tf1.poc ), atr_val)
Step 4: Update the Structure Container
On each bar, update the respective TimeframeStructure object within the master container.
// Calculate TF1's Value Area from historical arrays
= msl.calc_unified_poc_va(h_arr1, l_arr1, c_arr1, v_arr1, 24, fp)
// Update the structure object for TF1
structure.tf1 := msl.update_structure(structure.tf1, poc1, vah1, val1, sh_p1, sh_b1, sl_p1, sl_b1, tf1, atr_val, ctx)
// Repeat for structure.tf2, etc.
Step 5: Analyze and Use the Data
With the structure updated, perform high-level analysis using the state and zone functions.
// Find Confluence Zones with a 0.3% price tolerance
array zones = msl.find_zones(structure, 0.3)
// Get the high-level summary state
msl.StructureState state = msl.get_structure_state(structure, close, false)
// Use state.net_bias, state.nearest_support, etc. for indicator logic
// Get Real-Time Intra-Bar State for precise alerts
float alert_tolerance = atr_val * 0.1
msl.IntrabarState ib_state = msl.scan_intrabar_levels(structure, zones, close, alert_tolerance)
if ib_state.at_confluence
alert("Price is at " + ib_state.active_level_name, alert.freq_once_per_bar)
Step 6: Visualization
Use the data from the structure, zones, and state objects to implement the script's visual elements (lines, boxes, tables, labels).
🔮 CONCLUSION
The Market Structure Library (MSL) library provides a structured set of tools for developers working with multi-timeframe market structure. By encapsulating complex calculations for data aggregation, liquidity modeling, and geometric analysis, it allows developers to focus on the specific logic and visualization of their custom indicators. The library is designed to serve as a foundational component for building detailed and context-aware analysis tools in Pine Script. Library

equity_curveLibrary "equity_curve"
f_remove_exchange_name(name)
Remove exchange prefix from ticker string (e.g., "BINANCE:BTCUSD" → "BTCUSD")
Parameters:
name (simple string) : Ticker string potentially containing exchange prefix
Returns: Ticker without exchange prefix
f_roc()
Calculate bar-over-bar return as decimal (close-to-close, for buy-and-hold)
Returns: Return as decimal (e.g., 0.02 for +2%)
f_roc_entry()
Calculate open-to-close return (realistic strategy entry assumption at bar open)
Returns: Intrabar return as decimal
f_equity(ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, best_asset, r1, r2, r3, r4, r5, r6, backtest, prev_equity, prev_peak, prev_dd)
Calculate strategy equity for a rotation system (stateless — caller must maintain var state).
Uses best_asset so signal is visible 1 bar before equity acts on it.
Parameters:
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
best_asset (string) : The currently selected best-performing asset ticker
r1 (float) : Per-bar return for asset 1 (open-to-close)
r2 (float) : Per-bar return for asset 2
r3 (float) : Per-bar return for asset 3
r4 (float) : Per-bar return for asset 4
r5 (float) : Per-bar return for asset 5
r6 (float) : Per-bar return for asset 6
backtest (bool) : Whether backtesting is active this bar
prev_equity (float) : Previous bar's equity value (caller initializes var as na)
prev_peak (float) : Previous bar's peak equity value (caller initializes var as na)
prev_dd (float) : Previous bar's max drawdown value (caller initializes var as 0.0)
Returns:
f_buy_and_hold(r, backtest, prev_equity, prev_peak, prev_dd)
Calculate buy-and-hold equity for a single asset (stateless — caller must maintain var state)
Parameters:
r (float) : Per-bar return (close-to-close)
backtest (bool) : Whether backtesting is active this bar
prev_equity (float) : Previous bar's equity value (caller initializes var as na)
prev_peak (float) : Previous bar's peak equity value (caller initializes var as na)
prev_dd (float) : Previous bar's max drawdown value (caller initializes var as 0.0)
Returns:
f_since(active, prev_count)
Calculate lookback period as bar count since condition became true (stateless — caller must maintain var state)
Parameters:
active (bool) : Whether the counting condition is active this bar
prev_count (int) : Previous bar's raw count (caller initializes var as 0)
Returns: — output is the adjusted lookback for metrics; count is the raw counter to feed back next bar
f_best_asset_col(ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, best_asset, backtest, colors)
Return color for equity curve based on currently held asset.
Uses best_asset so signal is visible 1 bar before equity execution.
Parameters:
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
best_asset (string) : The confirmed best-performing asset ticker
backtest (bool) : Whether backtesting is active
colors (array) : Array of 8 colors:
Returns: Color corresponding to the currently held asset
f_PerformanceMetrics(base, Lookback, backtest, max_drawdown)
Calculate performance metrics from an equity curve
Parameters:
base (float) : The equity curve series
Lookback (int) : Number of bars to analyze (capped at 4998)
backtest (bool) : Whether backtesting is active
max_drawdown (float) : Maximum drawdown value (pre-calculated, as decimal e.g. 0.25 = 25%)
Returns: Array of 10 floats:
f_PerfMetricTable(p, ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, strategy, a1, a2, a3, a4, a5, a6, colors)
Populate a performance metrics comparison table. Caller must create the table with `var` and pass it in.
Should only be called on barstate.islast.
Parameters:
p (table) : Pre-created table (caller uses: var table p = table.new(position.top_left, 8, 15, ...))
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
strategy (array) : Strategy metrics array (from f_PerformanceMetrics)
a1 (array) : Buy-and-hold metrics for asset 1
a2 (array) : Buy-and-hold metrics for asset 2
a3 (array) : Buy-and-hold metrics for asset 3
a4 (array) : Buy-and-hold metrics for asset 4
a5 (array) : Buy-and-hold metrics for asset 5
a6 (array) : Buy-and-hold metrics for asset 6
colors (array) : Array of 8 colors
Returns: The table object Library

Lib_SW_VisualLibrary "Lib_SW_Visual"
drawEntryLabel(isLong, barIdx, priceY, txt, bgCol, txtCol, sz)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
priceY (float) : Y axis price
txt (string) : Label text
bgCol (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('tiny', 'small', 'normal')
Returns: Created label
drawTPLabel(isLong, barIdx, price, tpNum, pnlStr, isDCA, col)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
price (float) : TP price
tpNum (int) : TP number (1, 2, 3)
pnlStr (string) : PnL formatted string
isDCA (bool) : Is DCA TP
col (color) : TP color
Returns: Created label
drawSLLabel(isLong, barIdx, price, pnlStr, isTrailing, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
isTrailing (bool)
col (color)
drawForceExitLabel(isLong, barIdx, price, pnlStr, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawSwingLabel(fromLong, barIdx, price, pnlStr, col)
Parameters:
fromLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawLiqLabel(isLong, barIdx, liqPrice, col)
Parameters:
isLong (bool)
barIdx (int)
liqPrice (float)
col (color)
drawMPLabel(isLong, barIdx, priceY, totalProfit)
Parameters:
isLong (bool) : Direction
barIdx (int) : Bar index for label
priceY (float) : Y-axis price (high for Long, low for Short)
totalProfit (float) : Accumulated trade PnL
Returns: Created label
persistLabel(lbl, latch, cleanup, barIdx, price, txt, isUp, col, txtCol, sz, yloc_mode)
Parameters:
lbl (label) : Current label reference (var label)
latch (bool) : Is the trigger active
cleanup (bool) : Delete label when latch goes off (Webhook=true, swpspace=false)
barIdx (int) : Bar index
price (float) : Y axis price
txt (string) : Label text
isUp (bool) : Label style up (true) or down (false)
col (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('small', 'normal', 'tiny')
yloc_mode (string) : Yloc mode: 'price', 'abovebar', 'belowbar', 'default'
Returns: Updated label reference
persistFELabel(lbl, latch, cleanup, blocked, showBlockedLbl, barIdx, price, txt, isUp, col)
Parameters:
lbl (label) : Current label reference
latch (bool) : Is trigger active
cleanup (bool) : Delete on latch off
blocked (bool) : Is the exit blocked
showBlockedLbl (bool) : Show full label when blocked
barIdx (int) : Bar index
price (float) : Y price
txt (string) : Label text
isUp (bool) : true=style_label_up, false=style_label_down
col (color) : Background color
Returns: Updated label reference
updateHLine(ln, barIdx, price, col, style, width)
Parameters:
ln (line) : Current line (if na, creates new)
barIdx (int) : Start bar index
price (float) : Price level
col (color) : Line color
style (string) : Line style
width (int) : Line width
Returns: Updated/Created line
drawHLine(ln, price, col, w, sty)
Parameters:
ln (line) : Current line reference (will be deleted if not na)
price (float) : Price level
col (color) : Line color
w (int) : Line width (default 1)
sty (string) : Style string: 'solid', 'dashed', 'dotted'
Returns: New line
deleteLines9(l1, l2, l3, l4, l5, l6, l7, l8, l9)
Parameters:
l1 (line) : Line 1 to delete
l2 (line) : Line 2 to delete
l3 (line) : Line 3 to delete
l4 (line) : Line 4 to delete
l5 (line) : Line 5 to delete
l6 (line) : Line 6 to delete
l7 (line) : Line 7 to delete
l8 (line) : Line 8 to delete
l9 (line) : Line 9 to delete
deleteLine(ln)
Parameters:
ln (line) : Line to delete
deleteAllLines(grp)
Parameters:
grp (LineGroup) : Line group
updateTPLines(grp, barIdx, tp1, tp2, tp3, colTP)
Parameters:
grp (LineGroup) : Current line group
barIdx (int) : Start bar index
tp1 (float) : TP1 price
tp2 (float) : TP2 price (na if not drawn)
tp3 (float) : TP3 price (na if not drawn)
colTP (color) : TP color
Returns: Updated line group
updateSLLine(grp, barIdx, slPrice, colSL)
Parameters:
grp (LineGroup)
barIdx (int)
slPrice (float)
colSL (color)
updateAvgLine(grp, barIdx, avgPrice, colAvg)
Parameters:
grp (LineGroup)
barIdx (int)
avgPrice (float)
colAvg (color)
panelCell(tbl, row, txt, txtCol, bgCol, tipTxt)
Parameters:
tbl (table) : Table reference
row (int) : Row number
txt (string) : Content
txtCol (color) : Text color
bgCol (color) : Background color (optional)
tipTxt (string) : Tooltip (optional)
panelCellSimple(tbl, row, txt, txtCol, bgCol)
Parameters:
tbl (table)
row (int)
txt (string)
txtCol (color)
bgCol (color)
pnlColor(pnl, posColor, negColor)
Parameters:
pnl (float) : PnL value
posColor (color) : Positive color
negColor (color) : Negative color
Returns: Appropriate color
sessionStatus(dateError, activeSession, sessionStarted)
Parameters:
dateError (bool) : Is there a date error
activeSession (bool) : Is session active
sessionStarted (bool) : Has session started
Returns:
drawPivotLines(pp, r1, r2, r3, s1, s2, s3, showPivots, colPP, colR, colS)
Parameters:
pp (float) : Pivot Point
r1 (float) : Resistance 1
r2 (float) : Resistance 2
r3 (float) : Resistance 3
s1 (float) : Support 1
s2 (float) : Support 2
s3 (float) : Support 3
showPivots (bool) : Show/Hide
colPP (color) : Pivot color
colR (color) : Resistance color
colS (color) : Support color
Returns: void (lines updated)
tpColor(tpNum, col1, col2, col3)
Parameters:
tpNum (int) : TP number (1, 2, 3)
col1 (color) : TP1 color
col2 (color) : TP2 color
col3 (color) : TP3 color
Returns: Selected color
fade(col, transp)
Parameters:
col (color) : Color
transp (int) : Transparency (0-100)
Returns: Faded color
stackY(stackCount, baseOffset)
Parameters:
stackCount (int) : Current stack count
baseOffset (float) : Base offset value (h-l or mintick*50)
Returns: Y axis offset
safeOffset()
VisualMarker
Fields:
txt (series string)
bgColor (series color)
txtColor (series color)
sz (series string)
LineGroup
Fields:
entryLine (series line)
avgLine (series line)
tp1Line (series line)
tp2Line (series line)
tp3Line (series line)
slLine (series line)
liqLine (series line)
tsLine (series line)
PanelTheme
Fields:
bgColor (series color)
borderColor (series color)
textPrimary (series color)
textGreen (series color)
textRed (series color)
textYellow (series color)
textBlue (series color)
textOrange (series color)
textCyan (series color) Library

Lib_Sw_SignalsLibrary "Lib_Sw_Signals"
checkPivotCross_Anlik(sysEn, lvlEn, active, inPos, pVal)
Parameters:
sysEn (bool) : Pivot system active
lvlEn (bool) : This level active
active (bool) : This pivot active (reactivated)
inPos (bool) : Already entered from this pivot
pVal (float) : Pivot price value
Returns: Pivot triggered
checkPivotCross_MumKapanisi(sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
checkPivotReactivate(sysEn, pVal, isLong)
Parameters:
sysEn (bool)
pVal (float)
isLong (bool)
checkPivotCross(mode, sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
mode (string) : 'Anlık' (Instant) or 'Mum Kapanışı' (Bar Close)
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
Returns: Pivot triggered
f_calcMACD(cfg, flagsL, flagsS)
Parameters:
cfg (MACDConfig) : MACD configuration
flagsL (MACDTrigFlags) : Long trigger flags
flagsS (MACDTrigFlags) : Short trigger flags
Returns:
allowSignal(enabled, src, lvl, rule)
Parameters:
enabled (bool) : Filter active
src (float) : Source value
lvl (float) : Comparison level
rule (string) : 'Altında Engelle' (Block Below) or 'Üstünde Engelle' (Block Above)
Returns: true = signal allowed
allowPriceSignal(enabled, line, rule)
Parameters:
enabled (bool)
line (float)
rule (string)
allowZoneSignal(enabled, zoneSrc)
Parameters:
enabled (bool)
zoneSrc (float) : >= 0.5 means zone is active (entry allowed)
Returns: true = signal allowed
allowLineRangeDual(enabled, lineLevel, pctAbove, pctBelow, modeAbove, modeBelow)
Parameters:
enabled (bool) : Filter active
lineLevel (float) : Line price level
pctAbove (float) : Above % threshold
pctBelow (float) : Below % threshold
modeAbove (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
modeBelow (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
Returns: true = signal allowed
blockPass(mode, e1, p1, e2, p2, e3, p3, eZ, pZ)
Parameters:
mode (string) : 'AND' or 'OR'
e1 (bool) : Blocker 1 enabled
p1 (bool) : Blocker 1 passed
e2 (bool) : Blocker 2 enabled
p2 (bool) : Blocker 2 passed
e3 (bool) : Blocker 3 enabled
p3 (bool) : Blocker 3 passed
eZ (bool) : Zone enabled
pZ (bool) : Zone passed
Returns: true = signal allowed
checkSignalInstant(use, src)
Parameters:
use (bool) : Source active
src (float) : Source value (0 = no signal)
Returns: true = signal exists
detectTick(use, currentVal, lastVal, prevBarVal)
Parameters:
use (bool) : Source active
currentVal (float) : Current source value
lastVal (float) : Last recorded value (held with varip)
prevBarVal (float) : Previous bar value (src )
Returns: true = new signal tick detected
zoneOrCombine(enableArray, passArray)
Parameters:
enableArray (array) : bool array: Active states
passArray (array) : bool array: Pass results
Returns: true = all filters passed (or none active)
ppZoneBlock(blockEnable, blockMode, inZone, checkSide)
Parameters:
blockEnable (bool) : Block active
blockMode (string) : 'Long', 'Short', 'Her İkisi' (Both)
inZone (bool) : Is in zone (src >= 0.5)
checkSide (string) : 'Long' or 'Short' - checked direction
Returns: true = signal BLOCKED
anySignalActive(signals)
Parameters:
signals (array) : array: 7 signal slots + pivot + MACD latch results
Returns: true = at least one signal active
finalTrigger(rawTrigger, blockPassResult, zoneCombined, pivotDistPass, ppZoneBlocked)
Parameters:
rawTrigger (bool) : Raw signal (before filters)
blockPassResult (bool) : BlockPass result
zoneCombined (bool) : Zone OR combination
pivotDistPass (bool) : Pivot distance filter
ppZoneBlocked (bool) : PP zone blocked
Returns: true = signal valid (all filters passed)
MACDConfig
Fields:
oscType (series string)
fast (series int)
slow (series int)
sig (series int)
sigType (series string)
l1 (series float)
l2 (series float)
l3 (series float)
l4 (series float)
l5 (series float)
MACDTrigFlags
Fields:
crossUP (series bool)
crossDN (series bool)
ml1U (series bool)
ml1D (series bool)
ml2U (series bool)
ml2D (series bool)
ml3U (series bool)
ml3D (series bool)
ml4U (series bool)
ml4D (series bool)
ml5U (series bool)
ml5D (series bool)
sl1U (series bool)
sl1D (series bool)
sl2U (series bool)
sl2D (series bool)
sl3U (series bool)
sl3D (series bool)
sl4U (series bool)
sl4D (series bool)
sl5U (series bool)
sl5D (series bool)
SignalSlot
Fields:
use (series bool)
src (series float)
srcPrice (series float)
BlockerConfig
Fields:
enable (series bool)
src (series float)
level (series float)
rule (series string)
LineBlockerConfig
Fields:
enable (series bool)
src (series float)
pctAbove (series float)
pctBelow (series float)
modeAbove (series string)
modeBelow (series string)
ZoneBlocker
Fields:
enable (series bool)
src (series float) Library

Lib_SW_CoreLibrary "Lib_SW_Core"
f_pctToPrice(pct, basePrice)
Parameters:
pct (float) : Percentage value (e.g., 2.0 = 2%)
basePrice (float) : Reference price
Returns: Price difference
f_pipsToPrice(pips, pipVal)
Parameters:
pips (float) : Number of pips (e.g., 100 pips)
pipVal (float) : Price value of 1 pip (XAUUSD: 0.01)
Returns: Price difference
f_toPrice(value, basePrice, isForex, pipVal)
Parameters:
value (float) : Distance value (% or pip)
basePrice (float) : Reference price (for percentage mode)
isForex (bool) : Is Forex mode
pipVal (float) : Pip value (for Forex mode)
Returns: Price difference
f_lotToNotional(lots, price, contractSize)
Parameters:
lots (float) : Lot amount (e.g., 0.01)
price (float) : Instrument price
contractSize (float) : Contract size (XAUUSD: 100)
Returns: Position value in Dollars
f_lotToMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Required margin (USD)
f_calcFee(notional, useFee, feePercent)
Parameters:
notional (float) : Trade volume
useFee (bool) : Is fee active
feePercent (float) : Fee percentage
Returns: Calculated fee
f_calcAvgPrice(oldAvg, oldNotional, newPrice, newNotional)
Parameters:
oldAvg (float) : Current average price
oldNotional (float) : Current position volume
newPrice (float) : New entry price
newNotional (float) : New entry volume
Returns: New weighted average price
f_multiplier(lvl, dcaMode)
Parameters:
lvl (int) : Current DCA level
dcaMode (string) : DCA mode ('Adım'/'Step', '2x', 'Kapalı'/'Off', 'Seçim Adımlı'/'Selection Step')
Returns: Multiplier value
f_unrealizedPnL(isLong, avgPrice, totalNotional, currentPrice)
Parameters:
isLong (bool) : Long or Short
avgPrice (float) : Average entry price
totalNotional (float) : Total volume
currentPrice (float) : Current price
Returns: Unrealized PnL
f_totalUnrealizedPnL(avgLongPrice, totalLongNotional, avgShortPrice, totalShortNotional, currentPrice)
Parameters:
avgLongPrice (float)
totalLongNotional (float)
avgShortPrice (float)
totalShortNotional (float)
currentPrice (float)
f_liqPrice_Long(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Long average price
totalNotional (float) : Long total volume
availableEquity (float) : Available equity (balance + realized PNL - fee - short margin)
Returns: Estimated liquidation price
f_liqPrice_Short(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Short average price
totalNotional (float) : Short total volume
availableEquity (float) : Available equity
Returns: Estimated liquidation price
f_calcTPLevels_Long(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Short(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Long_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float) : Average entry price
tp1_val (float) : TP1 distance (% or pip)
tp2_val (float) : TP2 distance
tp3_val (float) : TP3 distance
isForex (bool) : Is Forex (pip) mode
pipVal (float) : Pip value (for Forex)
Returns: TPVisuals structure
f_calcTPLevels_Short_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float)
tp1_val (float)
tp2_val (float)
tp3_val (float)
isForex (bool)
pipVal (float)
f_calcSL_Long(avgPrice, level, cfg, trailHigh)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
f_calcSL_Short(avgPrice, level, cfg, trailLow)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
f_calcSL_Long_Unified(avgPrice, level, cfg, trailHigh, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
isForex (bool) : if true pip based, else % based
pipVal (float) : Forex pip value (for Forex mode)
Returns: tuple
f_calcSL_Short_Unified(avgPrice, level, cfg, trailLow, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
isForex (bool)
pipVal (float)
f_effectiveSL(isLong, slFixed, slTrail)
Parameters:
isLong (bool) : True if Long
slFixed (float) : Fixed SL
slTrail (float) : Trailing SL (can be na)
Returns: Effective SL price
f_calcEquity(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, unrealizedTotal)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
unrealizedTotal (float)
f_calcFreeMargin(equity, totalLongNotional, totalShortNotional, leverage)
Parameters:
equity (float)
totalLongNotional (float)
totalShortNotional (float)
leverage (int)
f_availableEquityForLiq(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, totalFees, useFee, otherSideNotional, leverage)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
totalFees (float)
useFee (bool)
otherSideNotional (float)
leverage (int)
Returns: Available equity
f_shouldForceFullExit(posNotional, exitAmount, leverage, minThreshold)
Parameters:
posNotional (float) : Current position volume
exitAmount (float) : Amount to exit
leverage (int) : Leverage
minThreshold (float) : Minimum position size (USDT)
Returns: true if full close required
f_calcExitPnL(isLong, avgPrice, exitPrice, exitAmount)
Parameters:
isLong (bool) : Is Long
avgPrice (float) : Average price
exitPrice (float) : Exit price
exitAmount (float) : Exit amount
Returns: PnL value
f_isApproachingSL(isLong, priceExtreme, slPrice, avgPrice, approachPct)
Parameters:
isLong (bool) : Is Long
priceExtreme (float) : Low (Long) or High (Short)
slPrice (float) : SL price
avgPrice (float) : Average price
approachPct (float) : Approach threshold percentage
Returns: true if approaching
f_isApproachingLiq(isLong, priceExtreme, liqPrice, avgPrice, approachPct)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachPct (float)
f_isApproachingSL_Unified(isLong, priceExtreme, slPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
slPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_isApproachingLiq_Unified(isLong, priceExtreme, liqPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_forexUsedMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Used margin (USD)
f_forexFreeMargin(equity, usedMarginL, usedMarginS)
Parameters:
equity (float)
usedMarginL (float)
usedMarginS (float)
f_forexPnL(isLong, entryPrice, exitPrice, lots, contractSize, pipVal)
Parameters:
isLong (bool) : Is Long
entryPrice (float) : Entry price
exitPrice (float) : Exit price
lots (float) : Lot amount
contractSize (float) : Contract size
pipVal (float) : Pip value
Returns: PnL (USD)
f_calcPivots(method, h, l, c)
Parameters:
method (string) : Pivot method ('Geleneksel', 'Fibonacci', 'Woodie', 'Camarilla')
h (float) : Previous High
l (float) : Previous Low
c (float) : Previous Close
Returns:
f_getPrice(inlinePrice, currentClose)
Parameters:
inlinePrice (float)
currentClose (float)
f_stackOffset(h, l)
Parameters:
h (float)
l (float)
TPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp1_reverse (series bool)
tp2_active (series bool)
tp2_pct (series float)
tp2_port (series float)
tp3_active (series bool)
tp3_pct (series float)
tp3_port (series float)
DCATPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp2_pct (series float)
tp2_port (series float)
tp3_pct (series float)
tp3_port (series float)
SLConfig
Fields:
l1_pct (series float)
dca_pct (series float)
useBE (series bool)
be_act_pct (series float)
be_offset_pct (series float)
useTS (series bool)
ts_act_pct (series float)
ts_dev_pct (series float)
PositionConfig
Fields:
baseAmount (series float)
leverage (series int)
maxLevel (series int)
dcaMode (series string)
selectionStep (series int)
useFee (series bool)
feePercent (series float)
PositionState
Fields:
level (series int)
signalCounter (series int)
avgPrice (series float)
lastEntryPrice (series float)
totalNotional (series float)
peakNotional (series float)
pctLeft (series float)
tpStage (series int)
tpStageDCA (series int)
accumulatedPnL (series float)
TradeStats
Fields:
slCountWin (series int)
slCountLoss (series int)
liqCount (series int)
maxDcaHit (series int)
maxVol (series float)
maxLoss (series float)
grossLoss (series float)
totalFees (series float)
totalVolume (series float)
tradeCount (series int)
peakEquity (series float)
maxDrawdown (series float)
maxDrawdownPct (series float)
currentDrawdownPct (series float)
approachSL (series int)
approachLiq (series int)
TPVisuals
Fields:
tp1 (series float)
tp2 (series float)
tp3 (series float)
SLState
Fields:
slFixed (series float)
slTrail (series float)
trailExtreme (series float)
ForexConfig
Fields:
pipValue (series float)
contractSize (series float)
baseLot (series float)
isForex (series bool) Library

VisualStructureToolsLibrary "VisualStructureTools"
MTF-safe drawing library (Unix-Time). Designed for high visual discrimination and efficient debugging of complex logic without cluttering the main script.
Optimized for Pine Script® v6 to prevent runtime errors in multi-timeframe environments.
setLine(price, startTime, labelText, labelPos, is_extend, l_width, l_col, l_style)
Draws a horizontal level or a segment with an optional label.
Parameters:
price (float) : Price level for the line.
startTime (int) : UNIX timestamp (ms) for the starting point.
labelText (string) : Text to display on the label. Use "none" to hide.
labelPos (string) : Position of the label relative to the price ('above' or 'below', 'none').
is_extend (bool) : If true, the line extends infinitely (extend.both).
l_width (int) : Width of the line in pixels.
l_col (color) : Color for the line and label text.
l_style (string) : Style of the line ('solid', 'dashed', 'dotted').
setBox(top, bottom, startTime, endTime, boxText, b_col, b_width, b_style, b_transp)
Draws a filled box with an optional synchronized text label.
Parameters:
top (float) : Price of the upper boundary.
bottom (float) : Price of the lower boundary.
startTime (int) : UNIX timestamp (ms) for the left side of the box.
endTime (int) : UNIX timestamp (ms) for the right side (defaults to current 'time').
boxText (string) : Optional text label for the box. Use "" to hide.
b_col (color) : Border and fill color.
b_width (int) : Border width.
b_style (string) : Border style ('solid', 'dashed', 'dotted').
b_transp (int) : Transparency for the background fill (0-100). Library

Trading_UI_ComponentsLibrary "Trading_UI_Components"
drawEntryLabel(isLong, barIdx, priceY, txt, bgCol, txtCol, sz)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
priceY (float) : Y axis price
txt (string) : Label text
bgCol (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('tiny', 'small', 'normal')
Returns: Created label
drawTPLabel(isLong, barIdx, price, tpNum, pnlStr, isDCA, col)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
price (float) : TP price
tpNum (int) : TP number (1, 2, 3)
pnlStr (string) : PnL formatted string
isDCA (bool) : Is DCA TP
col (color) : TP color
Returns: Created label
drawSLLabel(isLong, barIdx, price, pnlStr, isTrailing, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
isTrailing (bool)
col (color)
drawForceExitLabel(isLong, barIdx, price, pnlStr, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawSwingLabel(fromLong, barIdx, price, pnlStr, col)
Parameters:
fromLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawLiqLabel(isLong, barIdx, liqPrice, col)
Parameters:
isLong (bool)
barIdx (int)
liqPrice (float)
col (color)
drawMPLabel(isLong, barIdx, priceY, totalProfit)
Parameters:
isLong (bool) : Direction
barIdx (int) : Bar index for label
priceY (float) : Y-axis price (high for Long, low for Short)
totalProfit (float) : Accumulated trade PnL
Returns: Created label
persistLabel(lbl, latch, cleanup, barIdx, price, txt, isUp, col, txtCol, sz, yloc_mode)
Parameters:
lbl (label) : Current label reference (var label)
latch (bool) : Is the trigger active
cleanup (bool) : Delete label when latch goes off (Webhook=true, swpspace=false)
barIdx (int) : Bar index
price (float) : Y axis price
txt (string) : Label text
isUp (bool) : Label style up (true) or down (false)
col (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('small', 'normal', 'tiny')
yloc_mode (string) : Yloc mode: 'price', 'abovebar', 'belowbar', 'default'
Returns: Updated label reference
persistFELabel(lbl, latch, cleanup, blocked, showBlockedLbl, barIdx, price, txt, isUp, col)
Parameters:
lbl (label) : Current label reference
latch (bool) : Is trigger active
cleanup (bool) : Delete on latch off
blocked (bool) : Is the exit blocked
showBlockedLbl (bool) : Show full label when blocked
barIdx (int) : Bar index
price (float) : Y price
txt (string) : Label text
isUp (bool) : true=style_label_up, false=style_label_down
col (color) : Background color
Returns: Updated label reference
updateHLine(ln, barIdx, price, col, style, width)
Parameters:
ln (line) : Current line (if na, creates new)
barIdx (int) : Start bar index
price (float) : Price level
col (color) : Line color
style (string) : Line style
width (int) : Line width
Returns: Updated/Created line
drawHLine(ln, price, col, w, sty)
Parameters:
ln (line) : Current line reference (will be deleted if not na)
price (float) : Price level
col (color) : Line color
w (int) : Line width (default 1)
sty (string) : Style string: 'solid', 'dashed', 'dotted'
Returns: New line
deleteLines9(l1, l2, l3, l4, l5, l6, l7, l8, l9)
Parameters:
l1 (line) : Line 1 to delete
l2 (line) : Line 2 to delete
l3 (line) : Line 3 to delete
l4 (line) : Line 4 to delete
l5 (line) : Line 5 to delete
l6 (line) : Line 6 to delete
l7 (line) : Line 7 to delete
l8 (line) : Line 8 to delete
l9 (line) : Line 9 to delete
deleteLine(ln)
Parameters:
ln (line) : Line to delete
deleteAllLines(grp)
Parameters:
grp (LineGroup) : Line group
updateTPLines(grp, barIdx, tp1, tp2, tp3, colTP)
Parameters:
grp (LineGroup) : Current line group
barIdx (int) : Start bar index
tp1 (float) : TP1 price
tp2 (float) : TP2 price (na if not drawn)
tp3 (float) : TP3 price (na if not drawn)
colTP (color) : TP color
Returns: Updated line group
updateSLLine(grp, barIdx, slPrice, colSL)
Parameters:
grp (LineGroup)
barIdx (int)
slPrice (float)
colSL (color)
updateAvgLine(grp, barIdx, avgPrice, colAvg)
Parameters:
grp (LineGroup)
barIdx (int)
avgPrice (float)
colAvg (color)
panelCell(tbl, row, txt, txtCol, bgCol, tipTxt)
Parameters:
tbl (table) : Table reference
row (int) : Row number
txt (string) : Content
txtCol (color) : Text color
bgCol (color) : Background color (optional)
tipTxt (string) : Tooltip (optional)
panelCellSimple(tbl, row, txt, txtCol, bgCol)
Parameters:
tbl (table)
row (int)
txt (string)
txtCol (color)
bgCol (color)
pnlColor(pnl, posColor, negColor)
Parameters:
pnl (float) : PnL value
posColor (color) : Positive color
negColor (color) : Negative color
Returns: Appropriate color
sessionStatus(dateError, activeSession, sessionStarted)
Parameters:
dateError (bool) : Is there a date error
activeSession (bool) : Is session active
sessionStarted (bool) : Has session started
Returns:
drawPivotLines(pp, r1, r2, r3, s1, s2, s3, showPivots, colPP, colR, colS)
Parameters:
pp (float) : Pivot Point
r1 (float) : Resistance 1
r2 (float) : Resistance 2
r3 (float) : Resistance 3
s1 (float) : Support 1
s2 (float) : Support 2
s3 (float) : Support 3
showPivots (bool) : Show/Hide
colPP (color) : Pivot color
colR (color) : Resistance color
colS (color) : Support color
Returns: void (lines updated)
tpColor(tpNum, col1, col2, col3)
Parameters:
tpNum (int) : TP number (1, 2, 3)
col1 (color) : TP1 color
col2 (color) : TP2 color
col3 (color) : TP3 color
Returns: Selected color
fade(col, transp)
Parameters:
col (color) : Color
transp (int) : Transparency (0-100)
Returns: Faded color
stackY(stackCount, baseOffset)
Parameters:
stackCount (int) : Current stack count
baseOffset (float) : Base offset value (h-l or mintick*50)
Returns: Y axis offset
safeOffset()
VisualMarker
Fields:
txt (series string)
bgColor (series color)
txtColor (series color)
sz (series string)
LineGroup
Fields:
entryLine (series line)
avgLine (series line)
tp1Line (series line)
tp2Line (series line)
tp3Line (series line)
slLine (series line)
liqLine (series line)
tsLine (series line)
PanelTheme
Fields:
bgColor (series color)
borderColor (series color)
textPrimary (series color)
textGreen (series color)
textRed (series color)
textYellow (series color)
textBlue (series color)
textOrange (series color)
textCyan (series color) Library

Signal_Routing_EngineLibrary "Signal_Routing_Engine"
checkPivotCross_Anlik(sysEn, lvlEn, active, inPos, pVal)
Parameters:
sysEn (bool) : Pivot system active
lvlEn (bool) : This level active
active (bool) : This pivot active (reactivated)
inPos (bool) : Already entered from this pivot
pVal (float) : Pivot price value
Returns: Pivot triggered
checkPivotCross_MumKapanisi(sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
checkPivotReactivate(sysEn, pVal, isLong)
Parameters:
sysEn (bool)
pVal (float)
isLong (bool)
checkPivotCross(mode, sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
mode (string) : 'Instant' (Instant) or 'Bar Close' (Bar Close)
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
Returns: Pivot triggered
f_calcMACD(cfg, flagsL, flagsS)
Parameters:
cfg (MACDConfig) : MACD configuration
flagsL (MACDTrigFlags) : Long trigger flags
flagsS (MACDTrigFlags) : Short trigger flags
Returns:
allowSignal(enabled, src, lvl, rule)
Parameters:
enabled (bool) : Filter active
src (float) : Source value
lvl (float) : Comparison level
rule (string) : 'Altında Engelle' (Block Below) or 'Üstünde Engelle' (Block Above)
Returns: true = signal allowed
allowPriceSignal(enabled, line, rule)
Parameters:
enabled (bool)
line (float)
rule (string)
allowZoneSignal(enabled, zoneSrc)
Parameters:
enabled (bool)
zoneSrc (float) : >= 0.5 means zone is active (entry allowed)
Returns: true = signal allowed
allowLineRangeDual(enabled, lineLevel, pctAbove, pctBelow, modeAbove, modeBelow)
Parameters:
enabled (bool) : Filter active
lineLevel (float) : Line price level
pctAbove (float) : Above % threshold
pctBelow (float) : Below % threshold
modeAbove (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
modeBelow (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
Returns: true = signal allowed
blockPass(mode, e1, p1, e2, p2, e3, p3, eZ, pZ)
Parameters:
mode (string) : 'AND' or 'OR'
e1 (bool) : Blocker 1 enabled
p1 (bool) : Blocker 1 passed
e2 (bool) : Blocker 2 enabled
p2 (bool) : Blocker 2 passed
e3 (bool) : Blocker 3 enabled
p3 (bool) : Blocker 3 passed
eZ (bool) : Zone enabled
pZ (bool) : Zone passed
Returns: true = signal allowed
checkSignalInstant(use, src)
Parameters:
use (bool) : Source active
src (float) : Source value (0 = no signal)
Returns: true = signal exists
detectTick(use, currentVal, lastVal, prevBarVal)
Parameters:
use (bool) : Source active
currentVal (float) : Current source value
lastVal (float) : Last recorded value (held with varip)
prevBarVal (float) : Previous bar value (src )
Returns: true = new signal tick detected
zoneOrCombine(enableArray, passArray)
Parameters:
enableArray (array) : bool array: Active states
passArray (array) : bool array: Pass results
Returns: true = all filters passed (or none active)
ppZoneBlock(blockEnable, blockMode, inZone, checkSide)
Parameters:
blockEnable (bool) : Block active
blockMode (string) : 'Long', 'Short', 'Both' (Both)
inZone (bool) : Is in zone (src >= 0.5)
checkSide (string) : 'Long' or 'Short' - checked direction
Returns: true = signal BLOCKED
anySignalActive(signals)
Parameters:
signals (array) : array: 7 signal slots + pivot + MACD latch results
Returns: true = at least one signal active
finalTrigger(rawTrigger, blockPassResult, zoneCombined, pivotDistPass, ppZoneBlocked)
Parameters:
rawTrigger (bool) : Raw signal (before filters)
blockPassResult (bool) : BlockPass result
zoneCombined (bool) : Zone OR combination
pivotDistPass (bool) : Pivot distance filter
ppZoneBlocked (bool) : PP zone blocked
Returns: true = signal valid (all filters passed)
MACDConfig
Fields:
oscType (series string)
fast (series int)
slow (series int)
sig (series int)
sigType (series string)
l1 (series float)
l2 (series float)
l3 (series float)
l4 (series float)
l5 (series float)
MACDTrigFlags
Fields:
crossUP (series bool)
crossDN (series bool)
ml1U (series bool)
ml1D (series bool)
ml2U (series bool)
ml2D (series bool)
ml3U (series bool)
ml3D (series bool)
ml4U (series bool)
ml4D (series bool)
ml5U (series bool)
ml5D (series bool)
sl1U (series bool)
sl1D (series bool)
sl2U (series bool)
sl2D (series bool)
sl3U (series bool)
sl3D (series bool)
sl4U (series bool)
sl4D (series bool)
sl5U (series bool)
sl5D (series bool)
SignalSlot
Fields:
use (series bool)
src (series float)
srcPrice (series float)
BlockerConfig
Fields:
enable (series bool)
src (series float)
level (series float)
rule (series string)
LineBlockerConfig
Fields:
enable (series bool)
src (series float)
pctAbove (series float)
pctBelow (series float)
modeAbove (series string)
modeBelow (series string)
ZoneBlocker
Fields:
enable (series bool)
src (series float) Library

Chew Library Library "AssetCorrelationUtils"
detectIndicesFutures(ticker)
Detects Index Futures (NQ/ES/YM/RTY + micro variants)
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFutures(ticker)
Detects Metal Futures (GC/SI + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexFutures(ticker)
Detects Forex Futures (6E/6B + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectEnergyFutures(ticker)
Detects Energy Futures (CL/RB/HO + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectTreasuryFutures(ticker)
Detects Treasury Futures (ZB/ZF/ZN)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCryptoFutures(ticker)
Detects CME Crypto Futures (BTC/ETH + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCADFutures(ticker)
Detects CAD Forex Futures (6C + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexCFD(ticker, tickerId)
Detects Forex CFD pairs (EUR/GBP/DXY, USD/JPY/CHF triads)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID (syminfo.tickerid) for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectCrypto(ticker, tickerId)
Detects major Crypto assets (BTC, ETH, SOL, XRP, alts)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFD(ticker, tickerId)
Detects Metals CFD (XAU/XAG/Copper)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectIndicesCFD(ticker, tickerId)
Detects Indices CFD (NAS100/SP500/DJ30)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectEUStocks(ticker, tickerId)
Detects EU Stock Indices (GER40/EU50) - Dyad only
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary asset configured (tertiary empty for dyad)
getDefaultFallback(tickerId)
Returns default fallback assets (chart ticker only, no correlation)
Parameters:
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with chart ticker as primary, empty secondary/tertiary (no correlation)
applySessionModifierWithBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITH back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.on applied
applySessionModifierNoBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITHOUT back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.off applied
isTriadMode(pairing)
Checks if a pairing represents a valid triad (3 assets)
Parameters:
pairing (AssetPairing) : The AssetPairing to check
Returns: True if tertiary is non-empty (triad mode), false for dyad
getAssetTicker(tickerId)
Extracts clean ticker string from full ticker ID
Parameters:
tickerId (string) : The full ticker ID (e.g., "BITGET:BTCUSDT.P")
Returns: Clean ticker string (e.g., "BTCUSDT.P")
resolveTriad(chartTickerId, pairing)
Resolves triad asset assignments with proper inversion flags
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing
Returns: Tuple
resolveDyad(chartTickerId, pairing)
Resolves dyad asset assignment with proper inversion flag
Parameters:
chartTickerId (string) : The current chart's ticker ID
pairing (AssetPairing) : The detected AssetPairing (dyad: tertiary is empty)
Returns: Tuple
resolveAssets(ticker, tickerId, assetType, sessionType, useBackadjust)
Main auto-detection entry point. Detects asset category and returns fully resolved config.
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
tickerId (string) : The full ticker ID (typically syminfo.tickerid)
assetType (string) : The asset type (typically syminfo.type)
sessionType (string) : The session type for futures (typically syminfo.session)
useBackadjust (bool) : Whether to apply back adjustment for futures session alignment
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
resolveCurrentChart()
Simplified auto-detection using current chart's syminfo values
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
AssetPairing
Core asset pairing structure for triad/dyad configurations
Fields:
primary (series string) : The primary (chart) asset ticker ID
secondary (series string) : The secondary correlated asset ticker ID
tertiary (series string) : The tertiary correlated asset ticker ID (empty for dyad)
invertSecondary (series bool) : Whether secondary asset should be inverted for divergence calc
invertTertiary (series bool) : Whether tertiary asset should be inverted for divergence calc
AssetConfig
Full asset resolution result with mode detection and computed values
Fields:
detected (series bool) : Whether auto-detection succeeded
isTriadMode (series bool) : True if triad (3 assets), false if dyad (2 assets)
primary (series string) : The resolved primary asset ticker ID
secondary (series string) : The resolved secondary asset ticker ID
tertiary (series string) : The resolved tertiary asset ticker ID (empty for dyad)
invertSecondary (series bool) : Computed inversion flag for secondary asset
invertTertiary (series bool) : Computed inversion flag for tertiary asset
assetCategory (series string) : String describing the detected asset category Library
