OPEN-SOURCE SCRIPT
TURKS Engine - Tiered Unit Risk Kernel

Most position-sizing tools tell you what to hold after the move. This one tells you the price at which it changes, before price gets there.
TURKS Engine decides how much of a long position to hold. Exposure is a graded function of where the close sits against four moving averages, so it moves in rungs rather than switching on and off. That function is monotone in price, which means it inverts: every rung has exactly one price. The panel solves for those prices and prints them today — a ladder of levels at which the position gets larger or smaller, readable now.
Long only, 0 to 1. No shorting, no leverage, nothing resting at a broker.
This is the indicator build of TURKS. Same engine, no orders — it sizes, you execute.
📊 WHAT THE LADDER DID
Twelve symbols, shipped defaults, 4-hour charts, full available history. Commission $1.50 per order, slippage 0.01xATR per side, idle cash credited nothing. b&h is buy-and-hold over the identical bars, charged nothing at all. The comparison is deliberately rigged against the engine.
Pine Script®
Pine Script®
CAGR / maxDD is the column that settles it — return earned per unit of drawdown suffered. On that measure the engine wins on 7 of 12. It cut maximum drawdown on 12 of 12, and beat buy-and-hold on raw return on 3.
▸ ETH — 117.3% against 71.9%, at −54.4% drawdown against −94.1%. Nearly double the return on barely half the pain.
▸ BTC — 70.0% against 54.2%, at −62.3% against −83.9%.
▸ AMD — 20.2% against 17.3%, turning a −96.1% hole into −69.3% across 21.4 years.
These are assets that spent their entire sample inside a historic bull market, measured against a benchmark paying no commission and no slippage. Halving a drawdown is ordinary. Halving it and finishing ahead is not.
Every one of those numbers comes from the BOOK panel in this script. There is no separate research harness behind them and no second, gross set of figures anywhere in the build. Load it on your own symbol and the whole table regenerates for that instrument in one bar, net of the costs you typed in.
The table was measured on 16 August 2026. A live chart keeps adding bars, so the panel will not read exactly these numbers — at the time of writing ETH has drifted to 122.3% against 76.1%. Read the panel, not the table, for what the engine is doing on your instrument today.
📖 HOW TO USE IT
1 — Set your costs first. Commission ($ per order) and Typical position size ($) are the only two numbers the cost model needs; every other cost figure is a rate derived from them. A flat $1.50 is 1.9bp on an $8,000 position and 7.5bp on a $2,000 one. Leave these wrong and the panel lies to you.
2 — Pick the instrument. Single names and crypto whose drawdowns are violent relative to their drift. The table above is the guide, including the four rows that say don't.
3 — Read the ladder, not the arrows. The SELL / BUY ENGINE block prints three live numbers:
▸ Sell next above — the price at which the next rung comes off
▸ Buy back below — the price at which it goes back on
▸ Rungs sold — how much the envelope has already taken off, e.g. *12 of 20*
Both prices exist now, before the move. They are not marks that appeared after one.
4 — Read the dial. THE RULE prints Target weight — what the rule says you should be holding at this instant — and Dial c / f. POSITION prints the modelled book: weight held, average cost, open return, and the round-trip cost that position is carrying, so the gap between intention and position is always visible.
5 — Size it with c and f, not by fighting the rungs. c scales the whole position down. f is the floor you keep while the rule is off; raising it walks the book continuously toward buy-and-hold. Both tooltips print the measured frontier — the whole curve of what each step costs in return and buys in drawdown, including the region where the rule loses to simply holding less.
6 — Check it on your own symbol before trusting any of it. BOOK prints Sample, CAGR against b&h, Max drawdown against b&h, CAGR/maxDD, Sharpe, Exposure and Turnover. BOOK LEDGER, bottom right, prints the same book in money: book value against buy-and-hold from the same start, spells closed, profit factor, worst run, open position.
🔔 ALERTS
Five named conditions in the alert dialog — Target weight changed, Weight added, Weight cut, Gate on, Gate off — plus a rich alert() message carrying the weight it moved from, the weight it moved to, and both envelope prices. Flip one checkbox and the same payload arrives as JSON for a webhook.
🪜 HOW THE EXPOSURE IS SET
Exposure Shape picks the weighting rule. *Ensemble 20/50/100/200 (graded)* is the default. Each of the four SMAs contributes its own 0-to-1 ramp as price clears it, scaled in ATR and widened for the longer means so a 200-day cross is not treated like a 20-day one. The four ramps are averaged, then rounded to the nearest third:
Pine Script®
Four reachable weights, three thresholds, and the panel prints the price of all three. *Graded (continuous)* uses one mean with an ATR ramp instead. *Binary gate (legacy)* is the original all-or-nothing rule, kept so the graded version has something to be measured against.
Risk dial c scales the entire position down. Risk dial f is how much you keep while the rule is off. These two are the real levers, and nothing about their trade-off is hidden — the full measured frontier is printed in the settings dialog, the losing region included.
Quantise Steps rounds the target to N reachable weights and requires price to clear 75% of a step before acting, so the weight does not twitch every bar. Ramp Width (xATR) sets how far above the mean price must travel to earn full size.
✂️ THE NADARAYA-WATSON SELL ENGINE
A trend weight cuts into weakness by construction, so it sells low: 59% of every unit the dial sells goes out below its own average cost, at 12.4 round trips a year. That is the flaw this block exists to fix. It replaces or constrains the sell side with a Gaussian kernel-regression envelope that only sells into genuine extension.
Sell Engine Mode — *Dial, NWE-gated* (default) keeps the dial's targets but forbids cutting while price sits below the smoother; it may still add. *NWE band only* turns the dial's sells off entirely. *Dial + NWE (both cut)* lets either one sell. *Dial only* leaves the envelope drawn but inert.
Sell Rungs is how much leaves on each upper-band cross: 1/N of the position. Going from 3 to 10 halved turnover, cut the share sold below basis from 16.7% to 8.9%, and pulled out-of-sample drawdown from −32.6% to −18.3%. It ships at 20, one step further along the same gradient; 10 is the last value with a formal table behind it.
Band Multiplier (3.0) and Buy-back Multiplier (2.5) set the upper and lower halfwidths in mean-absolute-deviation units. The asymmetry is the point: buying back nearer the mean than you sold restores the position before price has fully round-tripped, which is what keeps the overlay from bleeding in a chop. Bandwidth h widens and slows the smoother; it ships at 5.
🔬 HOW THIS WAS BUILT
Nine candidate signal families were tested against a matched-exposure control across 140 markets and 8,793 sessions: moving-average and momentum structure, cross-sectional relative strength, short-horizon mean reversion, volatility-of-volatility and regime transitions, drawdown state, volume, range compression, multi-timeframe agreement, and calendar seasonality. Not one was positive both in and out of sample. All nine were deleted from the codebase rather than left in as decoration.
The cleanest demonstration: take the original engine's own weight path and fire it 60 trading days late — same trades, same sizes, same turnover, same average exposure, only the dates broken. It scores better late than on time. Block-shuffling the path also beats it. A rule whose dates carry information cannot survive having them destroyed, so that engine was removed and what remains is geometry.
The stretch-proportional alternative to fixed rungs was then built and measured across 44 configurations. None beat rungs = 10. The project's pre-registered five-clause acceptance test passed all 20 graded cells — but a constant weight of 1.0 also passes three of five clauses, exactly one cell of twenty reaches p < 0.05 uncorrected (the null expectation for twenty tests), that p fails Bonferroni, and the cells are 0.985-correlated. It was reported as a failed test.
Everything left in this script survived a process designed to kill it. What remains is a sizing rule with no forecast in it: it does not predict the retest, it tells you at a price you can read now exactly what happens when one arrives.
⚙️ COSTS, AND THE SETTINGS THAT DECIDE THEM
Sell Engine Mode *Dial, NWE-gated*, Exposure Shape *Ensemble 20/50/100/200 (graded)*, c = 1.00, f = 0.00, Quantise Steps 3, Ramp 1.0 ATR, Trend Mean 200, Cash Yield 0.00%. Envelope: bandwidth 5, multiplier 3.0, buy-back 2.5, MAE window 499, Sell Rungs 20. Book notional 150,000, commission $1.50 cash per order, slippage 0.01xATR per side.
Slippage is charged in ATR units rather than ticks, because a tick is an absolute price and one tick count cannot be simultaneously correct for a $20 stock and a $1,600 one, nor for the same stock at $0.21 and at $224. A fraction of the instrument's own range travels between symbols; a tick count does not.
Cash Yield ships at 0.00%. The rule spends much of its life partly in cash, so any yield credited lands straight on the CAGR, and one constant cannot represent a twenty-year sample where real cash paid about 0.1% for eight years and about 5% for two. Every figure in the table above was measured with it at zero.
Exits are close-only by construction. The printed ladder is the memoryless level; the live quantiser is hysteretic, so the executed switch can sit up to 0.75 steps from the printed one.
🔁 THE STRATEGY BUILD
The same engine with orders attached is published separately as TURKS — Tiered Unit Risk Kernel Strategy, for anyone who wants the Strategy Tester's own accounting as a second opinion on the panel. Both builds compute the ladder, the envelope and the BOOK ledger from identical code.
© CREDIT
The envelope is a port of "Nadaraya-Watson Envelope [LuxAlgo]" by LuxAlgo (tradingview.com/u/LuxAlgo/), published open source under CC BY-NC-SA 4.0. The kernel, the MAE band construction and the crossover logic are theirs. This script is published under the same licence.
Only the non-repainting, one-sided causal branch was ported. LuxAlgo's script defaults to the repainting branch, which rebuilds its curve inside barstate.islast with a two-sided kernel, so the value at bar i averages bars on both sides of i — including bars that had not happened when i closed. That branch is deliberately absent here. The measured gap between the two is about 21% of the band halfwidth, which is why the repainting version's arrows look cleaner than any live rule can be. The sizing, the rung logic and the position accounting are new.
Open source, Pine v6.
TURKS Engine decides how much of a long position to hold. Exposure is a graded function of where the close sits against four moving averages, so it moves in rungs rather than switching on and off. That function is monotone in price, which means it inverts: every rung has exactly one price. The panel solves for those prices and prints them today — a ladder of levels at which the position gets larger or smaller, readable now.
Long only, 0 to 1. No shorting, no leverage, nothing resting at a broker.
This is the indicator build of TURKS. Same engine, no orders — it sizes, you execute.
📊 WHAT THE LADDER DID
Twelve symbols, shipped defaults, 4-hour charts, full available history. Commission $1.50 per order, slippage 0.01xATR per side, idle cash credited nothing. b&h is buy-and-hold over the identical bars, charged nothing at all. The comparison is deliberately rigged against the engine.
CAGR / maxDD is the column that settles it — return earned per unit of drawdown suffered. On that measure the engine wins on 7 of 12. It cut maximum drawdown on 12 of 12, and beat buy-and-hold on raw return on 3.
▸ ETH — 117.3% against 71.9%, at −54.4% drawdown against −94.1%. Nearly double the return on barely half the pain.
▸ BTC — 70.0% against 54.2%, at −62.3% against −83.9%.
▸ AMD — 20.2% against 17.3%, turning a −96.1% hole into −69.3% across 21.4 years.
These are assets that spent their entire sample inside a historic bull market, measured against a benchmark paying no commission and no slippage. Halving a drawdown is ordinary. Halving it and finishing ahead is not.
Every one of those numbers comes from the BOOK panel in this script. There is no separate research harness behind them and no second, gross set of figures anywhere in the build. Load it on your own symbol and the whole table regenerates for that instrument in one bar, net of the costs you typed in.
The table was measured on 16 August 2026. A live chart keeps adding bars, so the panel will not read exactly these numbers — at the time of writing ETH has drifted to 122.3% against 76.1%. Read the panel, not the table, for what the engine is doing on your instrument today.
📖 HOW TO USE IT
1 — Set your costs first. Commission ($ per order) and Typical position size ($) are the only two numbers the cost model needs; every other cost figure is a rate derived from them. A flat $1.50 is 1.9bp on an $8,000 position and 7.5bp on a $2,000 one. Leave these wrong and the panel lies to you.
2 — Pick the instrument. Single names and crypto whose drawdowns are violent relative to their drift. The table above is the guide, including the four rows that say don't.
3 — Read the ladder, not the arrows. The SELL / BUY ENGINE block prints three live numbers:
▸ Sell next above — the price at which the next rung comes off
▸ Buy back below — the price at which it goes back on
▸ Rungs sold — how much the envelope has already taken off, e.g. *12 of 20*
Both prices exist now, before the move. They are not marks that appeared after one.
4 — Read the dial. THE RULE prints Target weight — what the rule says you should be holding at this instant — and Dial c / f. POSITION prints the modelled book: weight held, average cost, open return, and the round-trip cost that position is carrying, so the gap between intention and position is always visible.
5 — Size it with c and f, not by fighting the rungs. c scales the whole position down. f is the floor you keep while the rule is off; raising it walks the book continuously toward buy-and-hold. Both tooltips print the measured frontier — the whole curve of what each step costs in return and buys in drawdown, including the region where the rule loses to simply holding less.
6 — Check it on your own symbol before trusting any of it. BOOK prints Sample, CAGR against b&h, Max drawdown against b&h, CAGR/maxDD, Sharpe, Exposure and Turnover. BOOK LEDGER, bottom right, prints the same book in money: book value against buy-and-hold from the same start, spells closed, profit factor, worst run, open position.
🔔 ALERTS
Five named conditions in the alert dialog — Target weight changed, Weight added, Weight cut, Gate on, Gate off — plus a rich alert() message carrying the weight it moved from, the weight it moved to, and both envelope prices. Flip one checkbox and the same payload arrives as JSON for a webhook.
🪜 HOW THE EXPOSURE IS SET
Exposure Shape picks the weighting rule. *Ensemble 20/50/100/200 (graded)* is the default. Each of the four SMAs contributes its own 0-to-1 ramp as price clears it, scaled in ATR and widened for the longer means so a 200-day cross is not treated like a 20-day one. The four ramps are averaged, then rounded to the nearest third:
Four reachable weights, three thresholds, and the panel prints the price of all three. *Graded (continuous)* uses one mean with an ATR ramp instead. *Binary gate (legacy)* is the original all-or-nothing rule, kept so the graded version has something to be measured against.
Risk dial c scales the entire position down. Risk dial f is how much you keep while the rule is off. These two are the real levers, and nothing about their trade-off is hidden — the full measured frontier is printed in the settings dialog, the losing region included.
Quantise Steps rounds the target to N reachable weights and requires price to clear 75% of a step before acting, so the weight does not twitch every bar. Ramp Width (xATR) sets how far above the mean price must travel to earn full size.
✂️ THE NADARAYA-WATSON SELL ENGINE
A trend weight cuts into weakness by construction, so it sells low: 59% of every unit the dial sells goes out below its own average cost, at 12.4 round trips a year. That is the flaw this block exists to fix. It replaces or constrains the sell side with a Gaussian kernel-regression envelope that only sells into genuine extension.
Sell Engine Mode — *Dial, NWE-gated* (default) keeps the dial's targets but forbids cutting while price sits below the smoother; it may still add. *NWE band only* turns the dial's sells off entirely. *Dial + NWE (both cut)* lets either one sell. *Dial only* leaves the envelope drawn but inert.
Sell Rungs is how much leaves on each upper-band cross: 1/N of the position. Going from 3 to 10 halved turnover, cut the share sold below basis from 16.7% to 8.9%, and pulled out-of-sample drawdown from −32.6% to −18.3%. It ships at 20, one step further along the same gradient; 10 is the last value with a formal table behind it.
Band Multiplier (3.0) and Buy-back Multiplier (2.5) set the upper and lower halfwidths in mean-absolute-deviation units. The asymmetry is the point: buying back nearer the mean than you sold restores the position before price has fully round-tripped, which is what keeps the overlay from bleeding in a chop. Bandwidth h widens and slows the smoother; it ships at 5.
🔬 HOW THIS WAS BUILT
Nine candidate signal families were tested against a matched-exposure control across 140 markets and 8,793 sessions: moving-average and momentum structure, cross-sectional relative strength, short-horizon mean reversion, volatility-of-volatility and regime transitions, drawdown state, volume, range compression, multi-timeframe agreement, and calendar seasonality. Not one was positive both in and out of sample. All nine were deleted from the codebase rather than left in as decoration.
The cleanest demonstration: take the original engine's own weight path and fire it 60 trading days late — same trades, same sizes, same turnover, same average exposure, only the dates broken. It scores better late than on time. Block-shuffling the path also beats it. A rule whose dates carry information cannot survive having them destroyed, so that engine was removed and what remains is geometry.
The stretch-proportional alternative to fixed rungs was then built and measured across 44 configurations. None beat rungs = 10. The project's pre-registered five-clause acceptance test passed all 20 graded cells — but a constant weight of 1.0 also passes three of five clauses, exactly one cell of twenty reaches p < 0.05 uncorrected (the null expectation for twenty tests), that p fails Bonferroni, and the cells are 0.985-correlated. It was reported as a failed test.
Everything left in this script survived a process designed to kill it. What remains is a sizing rule with no forecast in it: it does not predict the retest, it tells you at a price you can read now exactly what happens when one arrives.
⚙️ COSTS, AND THE SETTINGS THAT DECIDE THEM
Sell Engine Mode *Dial, NWE-gated*, Exposure Shape *Ensemble 20/50/100/200 (graded)*, c = 1.00, f = 0.00, Quantise Steps 3, Ramp 1.0 ATR, Trend Mean 200, Cash Yield 0.00%. Envelope: bandwidth 5, multiplier 3.0, buy-back 2.5, MAE window 499, Sell Rungs 20. Book notional 150,000, commission $1.50 cash per order, slippage 0.01xATR per side.
Slippage is charged in ATR units rather than ticks, because a tick is an absolute price and one tick count cannot be simultaneously correct for a $20 stock and a $1,600 one, nor for the same stock at $0.21 and at $224. A fraction of the instrument's own range travels between symbols; a tick count does not.
Cash Yield ships at 0.00%. The rule spends much of its life partly in cash, so any yield credited lands straight on the CAGR, and one constant cannot represent a twenty-year sample where real cash paid about 0.1% for eight years and about 5% for two. Every figure in the table above was measured with it at zero.
Exits are close-only by construction. The printed ladder is the memoryless level; the live quantiser is hysteretic, so the executed switch can sit up to 0.75 steps from the printed one.
🔁 THE STRATEGY BUILD
The same engine with orders attached is published separately as TURKS — Tiered Unit Risk Kernel Strategy, for anyone who wants the Strategy Tester's own accounting as a second opinion on the panel. Both builds compute the ladder, the envelope and the BOOK ledger from identical code.
© CREDIT
The envelope is a port of "Nadaraya-Watson Envelope [LuxAlgo]" by LuxAlgo (tradingview.com/u/LuxAlgo/), published open source under CC BY-NC-SA 4.0. The kernel, the MAE band construction and the crossover logic are theirs. This script is published under the same licence.
Only the non-repainting, one-sided causal branch was ported. LuxAlgo's script defaults to the repainting branch, which rebuilds its curve inside barstate.islast with a two-sided kernel, so the value at bar i averages bars on both sides of i — including bars that had not happened when i closed. That branch is deliberately absent here. The measured gap between the two is about 21% of the band halfwidth, which is why the repainting version's arrows look cleaner than any live rule can be. The sizing, the rung logic and the position accounting are new.
Open source, Pine v6.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.