OPEN-SOURCE SCRIPT
已更新 Leverage Strategy Shell [by Oberlunar]

Leverage Strategy Shell ★ by Oberlunar
A quantitative strategy shell that executes no logic of its own. It receives entry and exit signals from any external indicator through a standardised protocol, then sizes each position through a full risk engine, executes against TradingView's broker emulator, and produces a post-trade analytics suite that no native strategy tester can match. Think of it as a risk manager that sits between your signal generator and the market.
The core idea is the separation of concerns. Your indicator decides when to trade. This shell decides how much to trade, enforces margin constraints, tracks every position through intrabar LTF data, and decomposes your equity curve into R-multiple and time distributions so you can see exactly where your edge lives — and where it doesn't.
Signal Protocol
The shell reads three values from your indicator viaPine Script® . Your indicator must plot them with Pine Script® so they don't clutter the chart.
Pine Script®
Signal is the only mandatory source. It accepts five discrete values: +1 opens a long, -1 opens a short, +2 closes an open long, -2 closes an open short, and 0 means no action. The shell is edge-triggered — it fires only on the transition from one value to another, so holding +1 for multiple bars will not produce multiple entries.
Stop is optional. When your indicator provides a stop price, the shell uses it for the exit order and for computing the risk distance that drives position sizing. When the source reads zero or equals the bar's close, the shell falls back to its internal stop model (ATR × multiplier or percentage). This means any indicator, from a simple moving-average crossover to a complex volatility regime detector, can plug in and immediately inherit disciplined risk management.
TP is also optional. If provided, the shell places a limit exit at that price alongside the stop. If not, the position lives until a +2 or -2 signal closes it.
To connect: apply your signal indicator to the chart first, then apply the shell to the same chart. In the shell's settings, map eachPine Script® to the corresponding plot from your indicator. That is the entire integration. No code changes to your indicator beyond adding the three plot lines above.
Risk Engine
Position sizing is not a percentage of equity and not a fixed lot. It is derived from the actual risk per trade, defined as the monetary distance from entry to stop expressed in account currency.
The engine computes tick value asPine Script® , converts to account currency through Pine Script® , then calculates the cost of the stop being hit: Pine Script® . To this it adds a friction estimate (spread + entry slippage + exit slippage, all in ticks) and the round-trip commission cost. The budget available for the trade is Pine Script® . Raw quantity is Pine Script® , floored to the instrument's minimum contract step and capped by the margin constraint Pine Script® . The final quantity is the smaller of the risk-sized and margin-capped values.
The commission model supports three modes. Per Order subtracts a fixed dollar amount per order from the risk budget before dividing by the per-unit cost — this is the simplest to configure and is the default. Per Contract scales linearly with quantity. Percent scales with notional value. In all three cases, the engine accounts for the full round-trip cost before committing capital.
The strategy declaration at the top of the script uses compile-time constants forPine Script® , Pine Script® , Pine Script® , Pine Script® , and Pine Script® . These are the values TradingView's broker emulator actually uses during the backtest. The input panel exposes the same parameters for the dashboard and sizing engine. If the two diverge, a red DECL MISMATCH warning appears at the bottom of the table — edit the constants in the source (marked with ✏️) to match your inputs.
Trade Tracking
Once a position is filled, the shell begins monitoring it through lower-timeframe intrabar data viaPine Script® . For each open trade it checks, bar by bar, whether the price path has reached -1R, +1R, +2R, +3R, or +5R from the entry, using the stop distance frozen at signal time as the unit of R. It records whether each level was touched and how many minutes it took to get there.
Trade close detection usesPine Script® as an event counter, not Pine Script® . This is critical for robustness: when the strategy reverses from long to short in a single bar, Pine Script® never passes through zero, but Pine Script® still increments. The entry price for R-multiple calculation comes from Pine Script® — the real fill, not the close of the signal bar.
The stop distance follows a three-stage chain. At signal time, stop and distance are frozen into pending variables. At fill time, when the position actually exists, they transfer into active tracking variables. At trade close, whenPine Script® increments, the active stop distance is pushed into a closed-trade array that stays perfectly aligned with TradingView's internal trade index. This eliminates the fragile parallel-array problem that plagues most custom trade trackers.
Analytics Dashboard
The dashboard is a single unified table rendered on the last bar. It has three main blocks.
Left panel shows live strategy metrics computed from all closed trades: Profit Factor, Win Rate, Expectancy in account currency, average R-multiple at exit, average Win R and Loss R with trade counts, maximum drawdown, annualised Sortino ratio and Calmar ratio, and average trade duration. These are not approximations — they iterate over everyPine Script® , Pine Script® , Pine Script® , and Pine Script® on the final bar.
Right panel, upper block — R Distribution. Every closed trade is binned by its R-multiple at exit into eight buckets: below -1R, -1R to -0.5R, -0.5R to zero, zero to +0.5R, +0.5R to +1R, +1R to +2R, +2R to +3R, and above +3R. Each row shows the count of trades in that bin, the average P&L, the average duration, and the win percentage. The background colour shifts from red to green with the bin's average R. This is the distribution that tells you whether your strategy is a small-loss / big-win machine or something else entirely.
Right panel, lower block — Time Distribution. The same closed trades are binned by duration into six buckets: under 6 hours, 6–24 hours, 1–3 days, 3–7 days, 1–4 weeks, and over 4 weeks. Each row shows count, average R, average P&L, and win rate. This reveals the time structure of your edge. A well-functioning trend-following signal will show negative average R in the short buckets (quick stops) and strongly positive R in the long buckets (runners). If the pattern is flat or inverted, the signal has no time edge.
Below the distributions, a Trade R-Level HIT% row shows what fraction of completed trades touched each R-level during their lifetime, with the average time to reach it. This is a different question from exit R: a trade can touch +3R intrabar and then close at +1.5R. The HIT% row captures the maximum favourable excursion in R-space, which is useful for evaluating whether wider take-profit targets are viable.
A Multi-Risk Sizing table at the bottom shows what the position size, notional, margin, and risk dollar would be at seven different risk percentages from 0.25% to 10%, so you can instantly see the scaling profile of your current instrument without changing any input.
Setup checklist
The strategy declaration usesPine Script® and Pine Script® by default. Orders fill on the next bar's open, which is realistic for market orders. Bar magnifier uses lower-timeframe data to improve fill simulation on higher timeframes. Both settings can be changed in the source if your workflow requires it.
The very simple tested strategy is the following:
Pine Script®
Credits
Concept, architecture, and code: Oberlunar.
Built in Pine Script™ v6.
A quantitative strategy shell that executes no logic of its own. It receives entry and exit signals from any external indicator through a standardised protocol, then sizes each position through a full risk engine, executes against TradingView's broker emulator, and produces a post-trade analytics suite that no native strategy tester can match. Think of it as a risk manager that sits between your signal generator and the market.
The core idea is the separation of concerns. Your indicator decides when to trade. This shell decides how much to trade, enforces margin constraints, tracks every position through intrabar LTF data, and decomposes your equity curve into R-multiple and time distributions so you can see exactly where your edge lives — and where it doesn't.
Signal Protocol
The shell reads three values from your indicator via
Signal is the only mandatory source. It accepts five discrete values: +1 opens a long, -1 opens a short, +2 closes an open long, -2 closes an open short, and 0 means no action. The shell is edge-triggered — it fires only on the transition from one value to another, so holding +1 for multiple bars will not produce multiple entries.
Stop is optional. When your indicator provides a stop price, the shell uses it for the exit order and for computing the risk distance that drives position sizing. When the source reads zero or equals the bar's close, the shell falls back to its internal stop model (ATR × multiplier or percentage). This means any indicator, from a simple moving-average crossover to a complex volatility regime detector, can plug in and immediately inherit disciplined risk management.
TP is also optional. If provided, the shell places a limit exit at that price alongside the stop. If not, the position lives until a +2 or -2 signal closes it.
To connect: apply your signal indicator to the chart first, then apply the shell to the same chart. In the shell's settings, map each
Risk Engine
Position sizing is not a percentage of equity and not a fixed lot. It is derived from the actual risk per trade, defined as the monetary distance from entry to stop expressed in account currency.
The engine computes tick value as
The commission model supports three modes. Per Order subtracts a fixed dollar amount per order from the risk budget before dividing by the per-unit cost — this is the simplest to configure and is the default. Per Contract scales linearly with quantity. Percent scales with notional value. In all three cases, the engine accounts for the full round-trip cost before committing capital.
The strategy declaration at the top of the script uses compile-time constants for
Trade Tracking
Once a position is filled, the shell begins monitoring it through lower-timeframe intrabar data via
Trade close detection uses
The stop distance follows a three-stage chain. At signal time, stop and distance are frozen into pending variables. At fill time, when the position actually exists, they transfer into active tracking variables. At trade close, when
Analytics Dashboard
The dashboard is a single unified table rendered on the last bar. It has three main blocks.
Left panel shows live strategy metrics computed from all closed trades: Profit Factor, Win Rate, Expectancy in account currency, average R-multiple at exit, average Win R and Loss R with trade counts, maximum drawdown, annualised Sortino ratio and Calmar ratio, and average trade duration. These are not approximations — they iterate over every
Right panel, upper block — R Distribution. Every closed trade is binned by its R-multiple at exit into eight buckets: below -1R, -1R to -0.5R, -0.5R to zero, zero to +0.5R, +0.5R to +1R, +1R to +2R, +2R to +3R, and above +3R. Each row shows the count of trades in that bin, the average P&L, the average duration, and the win percentage. The background colour shifts from red to green with the bin's average R. This is the distribution that tells you whether your strategy is a small-loss / big-win machine or something else entirely.
Right panel, lower block — Time Distribution. The same closed trades are binned by duration into six buckets: under 6 hours, 6–24 hours, 1–3 days, 3–7 days, 1–4 weeks, and over 4 weeks. Each row shows count, average R, average P&L, and win rate. This reveals the time structure of your edge. A well-functioning trend-following signal will show negative average R in the short buckets (quick stops) and strongly positive R in the long buckets (runners). If the pattern is flat or inverted, the signal has no time edge.
Below the distributions, a Trade R-Level HIT% row shows what fraction of completed trades touched each R-level during their lifetime, with the average time to reach it. This is a different question from exit R: a trade can touch +3R intrabar and then close at +1.5R. The HIT% row captures the maximum favourable excursion in R-space, which is useful for evaluating whether wider take-profit targets are viable.
A Multi-Risk Sizing table at the bottom shows what the position size, notional, margin, and risk dollar would be at seven different risk percentages from 0.25% to 10%, so you can instantly see the scaling profile of your current instrument without changing any input.
Setup checklist
- Add three lines to your indicator (Signal, Stop (optional), TP(optional)) following the protocol above.
Pine Script® - Apply your indicator to the chart.
- Apply this strategy shell to the same chart.
- In the shell's settings, map the three fields to the corresponding plots from your indicator.
Pine Script® - Set Account Capital, Leverage, Commission Type and Value to match your broker. Then edit the ✏️ constants at the top of the script to the same values — these are compile-time and cannot follow input changes.
- Verify no DECL MISMATCH warning appears in the table.
- Run the backtest. Read the R and Time distributions. Decide whether your signal has edge.
The strategy declaration uses
The very simple tested strategy is the following:
Credits
Concept, architecture, and code: Oberlunar.
Built in Pine Script™ v6.
版本注释
Small color fix.版本注释
Small color fix.版本注释
mentalExpert19609, thank you — you found a real bug and your diagnosis was spot on.The crash on bar 0 had two root causes working together that now should be fixed.
版本注释
Fixed a bug in commission computation.开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Founder of UnconventionalTraders, a platform for 0DTE/ORB analysis:
unconventionaltraders.com
unconventionaltraders.com
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。
开源脚本
秉承TradingView的精神,该脚本的作者将其开源,以便交易者可以查看和验证其功能。向作者致敬!您可以免费使用该脚本,但请记住,重新发布代码须遵守我们的网站规则。
Founder of UnconventionalTraders, a platform for 0DTE/ORB analysis:
unconventionaltraders.com
unconventionaltraders.com
免责声明
这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。