Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (3)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$90,392$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. The script plots nothing itself; the lines and the lower pane are its own calculations, drawn for reference.
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

Differs

Trades 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

Verified

Same 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.

SettingDefaultType and rangeFeeds
Stop Loss %%10intqty slPts
Risk Max risk for position2intrisk
Risk Type (no label in the script)% from equitystring · 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.

closecloseprice dataslPcntStop Loss %%setting · 10riskTypeRisk Typesetting · % from equityriskValueRisk setting · 2qtyqtyvalueslPtsslPtsvaluelongConditionlongConditionconditionshortConditionshortConditionconditionriskriskconditionentry:My Long Entry IdOpen My Long Entry Idstrategy.entryentry:My Short Entry IdOpen My Short Entry Idstrategy.entryexit:xexit xstrategy.exit

Order rules

OrderFires whenBy defaultLine
Open My Long Entry Id long(longCondition)On27
Open My Short Entry Id short(shortCondition)On30
Exit x stopevery barOn33

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.

1/1trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−9.6%+102.5%60%0.009.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+5.5%+5.5%560%3.603.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−9.6%+9.8%60%0.009.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+7.5%+8.4%560%4.463.1%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−9.6%+16.7%60%0.009.6%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−1.7%+21.5%520%0.626.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−9.6%+148.3%60%0.009.6%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−1.6%+17.1%540%0.594.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 barsTradesWonP&L
Rising market10%−$1,960.00
Sideways market30%−$3,844.74
Falling market20%−$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.

0%11%
All 6 trades
SideEntryExitBarsP&L
long27 Jan 2024 41,823.5027 Jan 2024 41,823.500$0.00
short27 Jan 2024 41,823.509 Feb 2024 46,005.9013−$2,000.00
long25 Dec 2024 98,663.6025 Feb 2025 88,797.2062−$1,960.00
short15 Apr 2025 84,591.6022 Apr 2025 93,050.707−$1,920.80
long23 Nov 2025 84,739.8031 Jan 2026 76,265.8069−$1,882.39
short3 Jul 2026 61,560.0019 Aug 2026 67,716.0047−$1,844.74

Similar scripts

No other indicator or strategy here shares enough of its calculations.

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 8 msYes 1,000 bars in 19 msNot measured
PineTSNo 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)