Grid Engine
THE SOURCE FILE /code/grid-engine.pine
Read the file, copy it, or download the exact bytes served at this address. No performance figure is claimed on this page.
lines of source127
categoryFramework
paneoverlay
Pine versionv6
//@version=6
//@description Pure grid-entry CALCULATIONS for Pine v6 strategies. No strategy.* calls.
library("GridEngine")
// =============================================================================
// GRID ENGINE — extracted from HD Bar Breakout v8 (lines 53-56, 87-88, 98-99,
// 113-119, 122-128). This file ONLY CALCULATES. The importing strategy places
// the orders. Math is identical to the source strategy; nothing is invented.
//
// Pine library law: a library() script cannot call strategy.* functions.
// So these exports return numbers/arrays; the strategy does the order calls.
// Every exported body is pure arithmetic / array work — no strategy.*,
// no request.*, no input.*, no global state.
// =============================================================================
//@function Number of live grid levels. Grid OFF => 1 (plain single entry). Grid ON => requested levels (1..4).
//@param useGrid Enable the grid.
//@param levels Requested level count, 1..4.
//@returns activeLvls: 1 when the grid is off, else levels.
export gridActive(bool useGrid, int levels) =>
useGrid ? levels : 1
//@function Equal slice of the SAME total risk budget: totalQty / activeLvls.
//@param totalQty The original whole-budget quantity (before splitting).
//@param activeLvls Number of live levels.
//@returns Quantity per leg, or 0.0 if activeLvls is not positive.
export perLevelQty(float totalQty, int activeLvls) =>
activeLvls > 0 ? totalQty / activeLvls : 0.0
//@function Spacing between legs: stopDist / activeLvls (the stop is divided into N slices).
//@param stopDist Distance from entry to stop, in price units.
//@param activeLvls Number of live levels.
//@returns Grid step, or 0.0 if activeLvls is not positive.
export gridStepSize(float stopDist, int activeLvls) =>
activeLvls > 0 ? stopDist / activeLvls : 0.0
//@function Direction multiplier for added legs. Negative adds TOWARD price (average in); anything else adds AWAY (chase).
//@param addMode "Positive" or "Negative".
//@returns -1 for "Negative", else +1.
export addSign(string addMode) =>
addMode == "Negative" ? -1 : 1
//@function Long entry prices L1..Ln: buyStop, then +/- step per extra leg.
//@param buyStop The first (breakout) long stop price.
//@param step Grid spacing from gridStepSize().
//@param sign Direction multiplier from addSign().
//@param n Number of legs, 1..4 (values above 4 are clamped to 4).
//@returns array<float> of n prices: L1=buyStop, L2=buyStop+sign*step, L3=+2*step, L4=+3*step.
export longLevels(float buyStop, float step, int sign, int n) =>
array<float> out = array.new_float()
for i = 0 to 3
if i < n
array.push(out, buyStop + sign * step * i)
out
//@function Short entry prices S1..Sn: sellStop, then +/- step per extra leg.
//@param sellStop The first (breakout) short stop price.
//@param step Grid spacing from gridStepSize().
//@param sign Direction multiplier from addSign().
//@param n Number of legs, 1..4 (values above 4 are clamped to 4).
//@returns array<float> of n prices: S1=sellStop, S2=sellStop-sign*step, S3=-2*step, S4=-3*step.
export shortLevels(float sellStop, float step, int sign, int n) =>
array<float> out = array.new_float()
for i = 0 to 3
if i < n
array.push(out, sellStop - sign * step * i)
out
//@function One shared exit pair anchored at the POSITION AVERAGE PRICE, not at any single leg.
//@param avgPx strategy.position_avg_price of the open position.
//@param stopDist Original stop distance.
//@param tgtDist Original target distance; 0 (or na) means NO limit — return na.
//@param isLong true for a long position, false for a short.
//@returns array<float> [stop, limit]: long stop=avgPx-stopDist, limit=avgPx+tgtDist; short is mirrored.
export exitLevels(float avgPx, float stopDist, float tgtDist, bool isLong) =>
float stop = isLong ? avgPx - stopDist : avgPx + stopDist
float limit = tgtDist == 0 ? na : (isLong ? avgPx + tgtDist : avgPx - tgtDist)
array<float> out = array.new_float(2)
array.set(out, 0, stop)
array.set(out, 1, limit)
out
// =============================================================================
// COPY-PASTE FALLBACK (no import needed)
// -----------------------------------------------------------------------------
// Pine libraries are PRIVATE and do NOT auto-update scripts that import them:
// if you edit and republish GridEngine, subscribers must re-add it to get the
// new version. When you want a strategy that is 100% self-contained, copy THIS
// block into your strategy and call the ge_* names below. They are the same
// math as the exports above. The ge_ prefix only avoids a name clash inside
// this library file; rename freely in your own script. Paste ABOVE your
// strategy's first use of them, and DO NOT also import GridEngine in that script.
// =============================================================================
ge_gridActive(bool useGrid, int levels) =>
useGrid ? levels : 1
ge_perLevelQty(float totalQty, int activeLvls) =>
activeLvls > 0 ? totalQty / activeLvls : 0.0
ge_gridStepSize(float stopDist, int activeLvls) =>
activeLvls > 0 ? stopDist / activeLvls : 0.0
ge_addSign(string addMode) =>
addMode == "Negative" ? -1 : 1
ge_longLevels(float buyStop, float step, int sign, int n) =>
array<float> out = array.new_float()
for i = 0 to 3
if i < n
array.push(out, buyStop + sign * step * i)
out
ge_shortLevels(float sellStop, float step, int sign, int n) =>
array<float> out = array.new_float()
for i = 0 to 3
if i < n
array.push(out, sellStop - sign * step * i)
out
ge_exitLevels(float avgPx, float stopDist, float tgtDist, bool isLong) =>
float stop = isLong ? avgPx - stopDist : avgPx + stopDist
float limit = tgtDist == 0 ? na : (isLong ? avgPx + tgtDist : avgPx - tgtDist)
array<float> out = array.new_float(2)
array.set(out, 0, stop)
array.set(out, 1, limit)
out
#THE CLAIM
This framework lifts the math out into one shared file.
#SOURCE
Pine v6 · 127 lines · /code/grid-engine.pine · category Framework.
#NOTES FROM THE REPO
The operator already proved a grid-entry mechanism inside HD Bar Breakout v8.
Scripts are provided for research; publication is not a performance claim. No backtest result is implied by this file. Not financial advice.
Source is provided for research, not as a performance claim. Paste into a Pine editor before use. Not financial advice.