本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Position Size Calculator", overlay=true)
// ── Inputs ──
capital = input.float(3200000, "Capital", minval=0,
group="Position Sizing")
riskPct = input.float(0.5, "Risk per trade (%)",
minval=0, maxval=100, step=0.05,
group="Position Sizing")
stopPct = input.float(1.5, "Stop loss (%)",
minval=0.01, maxval=100, step=0.05,
group="Position Sizing")
entryInput = input.float(0, "Entry price (0 = current price)",
minval=0, group="Position Sizing")
placement = input.string("Top Left", "Position",
options=["Top Left", "Top Right", "Bottom Left", "Bottom Right"],
group="Display")
fontChoice = input.string("Small", "Text size",
options=["Tiny", "Small", "Normal"],
group="Display")
showCalc = input.bool(true, "Show calculator", group="Display")
tablePosition = switch placement
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.top_left
fontSize = switch fontChoice
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
// ── Calculations: whole shares ──
entryPrice = entryInput > 0 ? entryInput : close
riskBudget = capital * riskPct / 100
riskPerShare = entryPrice * stopPct / 100
shares = riskPerShare > 0 ? math.floor(riskBudget / riskPerShare) : 0
positionValue = shares * entryPrice
positionPct = capital > 0 ? positionValue / capital * 100 : 0
actualRisk = shares * riskPerShare
// ── Compact display ──
var table calculator = table.new(tablePosition, 2, 4,
bgcolor=color.new(color.black, 10),
frame_color=color.new(color.gray, 50),
frame_width=1)
if barstate.islast
if showCalc
table.cell(calculator, 0, 0,
"R " + str.tostring(riskPct, "0.##") +
"% | SL " + str.tostring(stopPct, "0.##") + "%",
text_color=color.white, text_size=fontSize,
text_halign=text.align_left)
table.cell(calculator, 1, 0,
"Risk " + str.tostring(actualRisk, "#,##0.00"),
text_color=color.orange, text_size=fontSize,
text_halign=text.align_right)
table.cell(calculator, 0, 1,
"Shares @ " + str.tostring(entryPrice, format.mintick),
text_color=color.white, text_size=fontSize,
text_halign=text.align_left)
table.cell(calculator, 1, 1,
str.tostring(shares, "#,##0"),
text_color=color.aqua, text_size=fontSize,
text_halign=text.align_right)
table.cell(calculator, 0, 2, "Position",
text_color=color.white, text_size=fontSize,
text_halign=text.align_left)
table.cell(calculator, 1, 2,
str.tostring(positionPct, "0.##") + "%",
text_color=positionPct > 100 ? color.orange : color.lime,
text_size=fontSize, text_halign=text.align_right)
table.cell(calculator, 0, 3, "Value",
text_color=color.white, text_size=fontSize,
text_halign=text.align_left)
table.cell(calculator, 1, 3,
str.tostring(positionValue, "#,##0.00"),
text_color=color.lime, text_size=fontSize,
text_halign=text.align_right)
else
table.clear(calculator, 0, 0, 1, 3)