Pine Script v4 · Strategy
Сalculation a position size based on risk
A Pine Script v4 strategy with no technical-analysis calculation. It has 3 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade is one contract and pays no commission. 3 settings; defaults include Stop Loss %% 10, Risk 2 and Risk Type % from equity.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does Сalculation a position size based on risk repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 1 of 1 trades.
- How did Сalculation a position size based on risk do on BTCUSDT 1D with default settings?
- −9.61%
- From 26 Jan 2024 to 21 Oct 2026, over 6 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Сalculation a position size based on risk be converted to Pine Script v5?
- No
- The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
- Does Сalculation a position size based on risk use a stop loss?
- Yes
- strategy.exit sets a stop on line 33.
- Does Сalculation a position size based on risk run in Zeal Terminal?
- Yes
- It compiles in 8 ms and runs 1,000 bars in 19 ms, in the browser.
BTCUSDT · 1D · default settings
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −9.61%
- −$9,607.93
- Buy and hold
- +102.5%
- same period
- Closed trades
- 6
- 0 won · 5 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- 0.00
- gross profit ÷ gross loss
- Max drawdown
- 9.61%
- −$9,607.93
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
1 setting has no label
In the settings dialog riskType (line 16) shows an empty name. The labels on this page come from the variable names.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
v4 → v5
DiffersTrades differ: 6 before, 6 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 7: //@version=4 → //@version=5
⋯// 2) leverage is 1:10 (this can be changed in the Settings dlg)-//@version=4+//@version=5strategy("Сalculation a position size based on risk", overlay=true, margin_long=10, margin_short=10, currency = currency.NONE)⋯Clean v5
VerifiedSame 6 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 14: input() → input.int()
- Line 15: input() → input.int()
- Line 16: input() → input.string()
⋯ -slPcnt = input(10, title = "Stop Loss %%")+slPcnt = input.int(10, title = "Stop Loss %%")-riskValue = input(2, title="Risk ", inline="risk", tooltip="Max risk for position")+riskValue = input.int(2, title="Risk ", inline="risk", tooltip="Max risk for position")-riskType = input("% from equity", title="", options=["% from equity", "$$"], inline="risk")+riskType = input.string("% from equity", title="", options=["% from equity", "$$"], inline="risk")calcPositionSize(entryPrice, slPercent) =>⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 6 before, 6 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// 2) leverage is 1:10 (this can be changed in the Settings dlg)-//@version=5+//@version=6strategy("Сalculation a position size based on risk", overlay=true, margin_long=10, margin_short=10, currency = currency.NONE)⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Stop Loss %% | 10 | int | qty slPts |
| Risk Max risk for position | 2 | int | risk |
| Risk Type (no label in the script) | % from equity | string · options ["% from equity", "$$"] | risk |
What it calculates
No technical-analysis calculation: the script works on prices and settings directly.
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open My Long Entry Id long | (longCondition) | On | 27 |
| Open My Short Entry Id short | (shortCondition) | On | 30 |
| Exit x stop | every bar | On | 33 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source, and the live replay matched history.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −9.6% | +102.5% | 6 | 0% | 0.00 | 9.6% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +5.5% | +5.5% | 5 | 60% | 3.60 | 3.1% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −9.6% | +9.8% | 6 | 0% | 0.00 | 9.6% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +7.5% | +8.4% | 5 | 60% | 4.46 | 3.1% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −9.6% | +16.7% | 6 | 0% | 0.00 | 9.6% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −1.7% | +21.5% | 5 | 20% | 0.62 | 6.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −9.6% | +148.3% | 6 | 0% | 0.00 | 9.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −1.6% | +17.1% | 5 | 40% | 0.59 | 4.2% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 0% | −$1,960.00 |
| Sideways market | 3 | 0% | −$3,844.74 |
| Falling market | 2 | 0% | −$3,803.19 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
9.6%
The 95th percentile of the worst drawdown when the same 6 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 9.6% to 9.6%; the tick is what actually happened, 9.6%. Order luck alone moves it this much.
All 6 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 27 Jan 2024 41,823.50 | 27 Jan 2024 41,823.50 | 0 | $0.00 |
| short | 27 Jan 2024 41,823.50 | 9 Feb 2024 46,005.90 | 13 | −$2,000.00 |
| long | 25 Dec 2024 98,663.60 | 25 Feb 2025 88,797.20 | 62 | −$1,960.00 |
| short | 15 Apr 2025 84,591.60 | 22 Apr 2025 93,050.70 | 7 | −$1,920.80 |
| long | 23 Nov 2025 84,739.80 | 31 Jan 2026 76,265.80 | 69 | −$1,882.39 |
| short | 3 Jul 2026 61,560.00 | 19 Aug 2026 67,716.00 | 47 | −$1,844.74 |
Similar scripts
No other indicator or strategy here shares enough of its calculations.
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 8 ms | Yes 1,000 bars in 19 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © adolgov//@description This strategy shows how calculate position size from risk (%% from equity or absolute money value) and stop loss level (%% from entry price)// Important notes:// 1) we suppose that account currency is same as symbol currency// 2) leverage is 1:10 (this can be changed in the Settings dlg)//@version=4strategy("Сalculation a position size based on risk", overlay=true, margin_long=10, margin_short=10, currency = currency.NONE)percent2points(percent) => strategy.position_size !=0 ? strategy.position_avg_price * percent / 100 / syminfo.mintick : napercent2money(price, percent) => price * percent / 100 * syminfo.pointvalue slPcnt = input(10, title = "Stop Loss %%")riskValue = input(2, title="Risk ", inline="risk", tooltip="Max risk for position")riskType = input("% from equity", title="", options=["% from equity", "$$"], inline="risk")calcPositionSize(entryPrice, slPercent) => risk = if riskType == "% from equity" strategy.equity * riskValue / 100 else riskValue risk / percent2money(entryPrice, slPercent)qty = calcPositionSize(close, slPcnt)// random entry longCondition = bar_index % 333 == 0if (longCondition) strategy.entry("My Long Entry Id", strategy.long, qty = qty)shortCondition = bar_index % 444 == 0if (shortCondition) strategy.entry("My Short Entry Id", strategy.short, qty = qty)// exit with stop lossslPts = percent2points(slPcnt)strategy.exit("x", loss = slPts)