本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jonathanalbrecht_trader — Albrecht Edge
//@version=6
indicator("Albrecht Edge - Position Size Calculator", shorttitle = "AE Position", overlay = true, behind_chart = false, max_boxes_count = 10, max_lines_count = 10, max_labels_count = 10)
// ════════════════════════════════════════════════════════════════════
// INPUTS
// ════════════════════════════════════════════════════════════════════
const string G_TRADE = "Trade"
const string G_RISK = "Risk"
const string G_COST = "Costs"
const string G_BROKER = "Broker & contract"
const string G_WARN = "Warnings"
const string G_CHART = "Chart"
const string G_CARD = "Card"
// Trade — entry is a time + price point, so the trade can be tracked from that bar on
entryTime = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Entry", inline = "entry", group = G_TRADE, confirm = true, display = display.none)
entryPrice = input.price(0.0, "", inline = "entry", group = G_TRADE, confirm = true, display = display.none, tooltip = "Click the bar and price of your entry. From that bar on the trade is tracked: pending → active → target or stop. Select the indicator to drag the levels.")
stopPrice = input.price(0.0, "Stop loss", group = G_TRADE, confirm = true, display = display.none)
targetIn = input.price(0.0, "Target", group = G_TRADE, confirm = true, display = display.none, tooltip = "Ignored when the target comes from an R multiple.")
targetMode = input.string("Price", "Target from", options = ["Price", "R multiple"], inline = "tm", group = G_TRADE, display = display.none)
targetR = input.float(2.0, "R", minval = 0.1, step = 0.1, inline = "tm", group = G_TRADE, display = display.none)
// Risk
accountCcy = input.string("USD", "Account currency", options = ["USD", "EUR", "GBP", "CHF", "JPY", "CAD", "AUD", "NZD", "SGD", "HKD", "SEK", "NOK", "PLN", "ZAR"], group = G_RISK, display = display.none)
accountSize = input.float(10000.0, "Account balance", minval = 0.0, step = 100.0, group = G_RISK, display = display.none)
riskPreset = input.string("1 %", "Risk per trade", options = ["0.5 %", "1 %", "2 %", "Custom %", "Fixed amount"], group = G_RISK, display = display.none)
riskCustom = input.float(1.5, "Custom %", minval = 0.01, step = 0.05, inline = "rc", group = G_RISK, display = display.none)
riskFixed = input.float(100.0, "Fixed", minval = 0.0, step = 10.0, inline = "rc", group = G_RISK, display = display.none, tooltip = "Used when Risk per trade is set to Custom % or Fixed amount. Fixed amount is in account currency.")
sizeSource = input.string("Risk-based", "Position size", options = ["Risk-based", "Manual"], inline = "ps", group = G_RISK, display = display.none)
manualSize = input.float(0.10, "", minval = 0.0, step = 0.01, inline = "ps", group = G_RISK, display = display.none, tooltip = "Manual: type your own size and the card shows the real risk it carries.")
// Costs
spreadIn = input.float(0.0, "Spread", minval = 0.0, step = 0.1, group = G_COST, display = display.none, tooltip = "Pips for forex, price points for everything else. Widens the stop and shortens the target, so the size stays honest.")
commission = input.float(0.0, "Commission per lot", minval = 0.0, step = 0.5, group = G_COST, display = display.none, tooltip = "Round turn, in account currency. Included in the risk: stop + costs = your risk.")
// Broker & contract
contractIn = input.float(0.0, "Units per lot", minval = 0.0, group = G_BROKER, display = display.none, tooltip = "0 = auto: forex 100,000 · gold 100 · silver 5,000 · crypto, indices, stocks 1 · futures use the exchange point value. Index and crypto CFDs differ between brokers, so check your contract specification.")
stepIn = input.float(0.0, "Size step", minval = 0.0, group = G_BROKER, display = display.none, tooltip = "0 = auto: 1 for stocks and futures, 0.0001 for crypto, 0.01 for everything else.")
minIn = input.float(0.0, "Min size", minval = 0.0, inline = "mm", group = G_BROKER, display = display.none)
maxIn = input.float(0.0, "Max", minval = 0.0, inline = "mm", group = G_BROKER, display = display.none, tooltip = "Min 0 = same as the size step. Max 0 = no limit.")
rounding = input.string("Down (safe)", "Rounding", options = ["Down (safe)", "Nearest"], group = G_BROKER, display = display.none)
leverage = input.float(30.0, "Leverage 1 :", minval = 1.0, step = 1.0, group = G_BROKER, display = display.none, tooltip = "Only used for the margin estimate.")
// Warnings
warnRisk = input.float(2.0, "High risk above %", minval = 0.1, step = 0.1, group = G_WARN, display = display.none)
warnRR = input.float(1.5, "Low R:R below", minval = 0.1, step = 0.1, group = G_WARN, display = display.none)
// Chart
showBoxes = input.bool(true, "Position box", inline = "box", group = G_CHART, display = display.none)
boxBorder = input.bool(true, "Border", inline = "box", group = G_CHART, display = display.none, tooltip = "Position box off: plain stop and target lines instead of zones. Border off: zones without an outline.")
extendBars = input.int(10, "Length (bars to the right)", minval = 1, maxval = 300, group = G_CHART, display = display.none)
labelMode = input.string("Full", "Level labels", options = ["Full", "Minimal", "Off"], inline = "lb", group = G_CHART, display = display.none)
labelSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "lb", group = G_CHART, display = display.none)
labelSide = input.string("Left of entry", "Label side", options = ["Left of entry", "Right of box"], group = G_CHART, display = display.none, tooltip = "Left of entry: labels sit before the trade. Right of box: labels sit in the empty space after the box, so no candles are covered. Give the chart some right margin (drag the time scale) so they fit.")
profitCol = input.color(color.rgb(16, 185, 129), "Target", inline = "col", group = G_CHART, display = display.none)
lossCol = input.color(color.rgb(239, 68, 68), "Stop", inline = "col", group = G_CHART, display = display.none)
entryCol = input.color(color.rgb(245, 158, 11), "Entry", inline = "col", group = G_CHART, display = display.none)
boxTransp = input.int(85, "Zone transparency", minval = 0, maxval = 100, group = G_CHART, display = display.none)
// Card
cardMode = input.string("Compact", "Card", options = ["Compact", "Full", "Off"], group = G_CARD, display = display.none)
cardPosIn = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], inline = "cp", group = G_CARD, display = display.none)
cardSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "cp", group = G_CARD, display = display.none, tooltip = "On a phone, Bottom right keeps the card clear of TradingView's legend.")
// ════════════════════════════════════════════════════════════════════
// MARKET DETECTION
// ════════════════════════════════════════════════════════════════════
const string FIATS = "USD,EUR,GBP,JPY,CHF,CAD,AUD,NZD,SEK,NOK,DKK,PLN,HUF,CZK,TRY,ZAR,MXN,SGD,HKD,CNH,ILS"
const string STABLES = "USDT,USDC,BUSD,FDUSD,TUSD,USDP,DAI"
isFiat(string c) =>
str.length(c) == 3 and str.contains("," + FIATS + ",", "," + c + ",")
string symType = syminfo.type
string tkr = str.upper(syminfo.ticker)
string quoteRaw = syminfo.currency
string baseCcy = syminfo.basecurrency
bool isFutures = symType == "futures"
bool isShares = symType == "stock" or symType == "fund" or symType == "dr"
bool isCrypto = symType == "crypto"
bool canMetal = not isFutures and not isShares and not isCrypto
bool isGold = canMetal and (str.contains(tkr, "XAU") or str.contains(tkr, "GOLD"))
bool isSilver = canMetal and (str.contains(tkr, "XAG") or str.contains(tkr, "SILVER"))
bool isPGM = canMetal and (str.contains(tkr, "XPT") or str.contains(tkr, "XPD"))
bool isMetal = isGold or isSilver or isPGM
bool isForex = not isMetal and not isFutures and not isShares and not isCrypto and (symType == "forex" or (isFiat(baseCcy) and isFiat(quoteRaw)))
bool isStable = str.contains("," + STABLES + ",", "," + quoteRaw + ",")
string quoteCcy = isStable ? "USD" : quoteRaw
float autoUnits = isFutures ? 1.0 : isGold ? 100.0 : isSilver ? 5000.0 : isPGM ? 100.0 : isForex ? 100000.0 : 1.0
float unitsPerLot = contractIn > 0 ? contractIn : autoUnits
float pointValue = nz(syminfo.pointvalue, 1.0)
float sizeStep = stepIn > 0 ? stepIn : isFutures or isShares ? 1.0 : isCrypto ? 0.0001 : 0.01
float minSize = minIn > 0 ? minIn : sizeStep
int sizeDec = sizeStep >= 1 ? 0 : sizeStep >= 0.1 ? 1 : sizeStep >= 0.01 ? 2 : sizeStep >= 0.001 ? 3 : 4
bool coinUnits = isCrypto and contractIn <= 0 and baseCcy != ""
string unitOne = isFutures ? "contract" : isShares ? "share" : coinUnits ? baseCcy : "lot"
string unitMany = isFutures ? "contracts" : isShares ? "shares" : coinUnits ? baseCcy : "lots"
float pipSize = quoteCcy == "JPY" or quoteCcy == "HUF" ? 0.01 : 0.0001
int moneyDec = accountCcy == "JPY" ? 0 : 2
float maxDev = isForex ? 0.08 : isMetal ? 0.2 : 0.5
// Quote currency → account currency, as live as possible:
// 1) the chart pair itself when it is the conversion (e.g. USDJPY on a USD account)
// 2) the live FX_IDC cross (e.g. JPYUSD for GBPJPY on a USD account)
// 3) TradingView's daily conversion rate as a fallback
float fxLive = request.security("FX_IDC:" + quoteCcy + accountCcy, timeframe.period, close, ignore_invalid_symbol = true)
float fxRaw = request.currency_rate(quoteCcy, accountCcy, true)
float fxRate = quoteCcy == accountCcy ? 1.0 : isForex and baseCcy == accountCcy and close > 0 ? 1.0 / close : not na(fxLive) and fxLive > 0 ? fxLive : fxRaw
// ════════════════════════════════════════════════════════════════════
// TRADE GEOMETRY & SIZE
// ════════════════════════════════════════════════════════════════════
float riskPct = switch riskPreset
"0.5 %" => 0.5
"1 %" => 1.0
"2 %" => 2.0
"Custom %" => riskCustom
=> na
float riskBudget = riskPreset == "Fixed amount" ? riskFixed : accountSize * riskPct / 100.0
bool isLong = stopPrice < entryPrice
bool isShort = stopPrice > entryPrice
float dir = isLong ? 1.0 : -1.0
float stopDist = math.abs(entryPrice - stopPrice)
float targetPrice = targetMode == "R multiple" ? entryPrice + dir * targetR * stopDist : targetIn
float targetDist = math.abs(targetPrice - entryPrice)
bool setupValid = stopDist > 0 and ((isLong and targetPrice > entryPrice) or (isShort and targetPrice < entryPrice))
float rr = stopDist > 0 ? targetDist / stopDist : na
bool levelsFar = setupValid and close > 0 and math.abs(entryPrice - close) / close > maxDev
// Money per 1.0 price move per lot, in account currency
float spreadPx = isForex ? spreadIn * pipSize : spreadIn
float valuePerPx = unitsPerLot * pointValue * fxRate
float lossPerLot = (stopDist + spreadPx) * valuePerPx + commission
float gainPerLot = math.max(targetDist - spreadPx, 0.0) * valuePerPx - commission
roundToStep(float v, float st) =>
float q = v / st
float n = rounding == "Nearest" ? math.round(q) : math.floor(q + 1e-9)
n * st
float exactSize = setupValid and not na(lossPerLot) and lossPerLot > 0 ? riskBudget / lossPerLot : na
float riskSize = na(exactSize) ? na : roundToStep(exactSize, sizeStep)
float rawSize = sizeSource == "Manual" ? manualSize : riskSize
bool capped = maxIn > 0 and not na(rawSize) and rawSize > maxIn
float usedSize = capped ? maxIn : rawSize
bool belowMin = sizeSource == "Risk-based" and not na(riskSize) and riskSize < minSize - 1e-9
// Net R:R — what the target pays relative to what the stop really costs, spread and commission included
float netRR = not na(lossPerLot) and lossPerLot > 0 ? gainPerLot / lossPerLot : na
bool hasCosts = spreadIn > 0 or commission > 0
float lossMoney = usedSize * lossPerLot
float gainMoney = usedSize * gainPerLot
float costMoney = usedSize * (spreadPx * valuePerPx + commission)
float effRiskPct = accountSize > 0 ? lossMoney / accountSize * 100.0 : na
float exposure = usedSize * unitsPerLot * math.abs(entryPrice) * pointValue * fxRate
float margin = exposure / leverage
float minRiskPct = accountSize > 0 ? minSize * lossPerLot / accountSize * 100.0 : na
// ════════════════════════════════════════════════════════════════════
// TRADE TRACKING (0 waiting · 1 pending · 2 active · 3 target hit · 4 stop hit)
// ════════════════════════════════════════════════════════════════════
var int state = 0
var int startBar = na
var int fillBar = na
var int exitBar = na
bool evFill = false
bool evTarget = false
bool evStop = false
float prevClose = nz(close[1], open)
bool afterEntry = na(time_close) ? time >= entryTime : time_close > entryTime
if setupValid and afterEntry
if state == 0
state := 1
startBar := bar_index
if state == 1
// Gaps count: the range from the previous close to this bar must reach the entry
if math.min(low, prevClose) <= entryPrice and math.max(high, prevClose) >= entryPrice
state := 2
fillBar := bar_index
evFill := true
if state == 2
bool hitStop = isLong ? low <= stopPrice : high >= stopPrice
// Conservative: on the fill bar only the stop counts, and stop wins same-bar conflicts
bool hitTarget = bar_index > fillBar and (isLong ? high >= targetPrice : low <= targetPrice)
if hitStop
state := 4
exitBar := bar_index
evStop := true
else if hitTarget
state := 3
exitBar := bar_index
evTarget := true
// R is the real risk in money: the stop costs exactly −1R, costs included
float moveDist = dir * (close - entryPrice)
float livePnl = usedSize * ((moveDist - spreadPx) * valuePerPx - commission)
float liveR = not na(lossMoney) and lossMoney > 0 ? livePnl / lossMoney : na
float resultR = state == 3 ? netRR : state == 4 ? -1.0 : na
float resultPnl = state == 3 ? gainMoney : state == 4 ? -lossMoney : na
// ════════════════════════════════════════════════════════════════════
// FORMATTING
// ════════════════════════════════════════════════════════════════════
fmtNum(float v, int d) =>
na(v) ? "–" : str.tostring(v, d <= 0 ? "0" : "0." + str.repeat("0", d))
fmtMoney(float v) =>
fmtNum(v, moneyDec) + " " + accountCcy
fmtSigned(float v) =>
na(v) ? "–" : math.abs(v) < 0.5 * math.pow(10, -moneyDec) ? fmtNum(0.0, moneyDec) + " " + accountCcy : (v > 0 ? "+" : "−") + fmtNum(math.abs(v), moneyDec) + " " + accountCcy
fmtPrice(float v) =>
na(v) ? "–" : str.tostring(v, format.mintick)
fmtDist(float d) =>
na(d) ? "–" : isForex ? fmtNum(d / pipSize, 1) + " pips" : str.tostring(d, format.mintick) + " pts"
fmtSize(float v) =>
na(v) ? "–" : fmtNum(v, sizeDec) + " " + (v == 1.0 ? unitOne : unitMany)
fmtR(float v) =>
na(v) ? "–" : math.abs(v) < 0.005 ? "0.00R" : (v > 0 ? "+" : "−") + fmtNum(math.abs(v), 2) + "R"
fmtPct(float v) =>
fmtNum(v, 2) + "%"
textOn(color c) =>
(color.r(c) * 299 + color.g(c) * 587 + color.b(c) * 114) / 1000 > 150 ? color.rgb(11, 14, 19) : color.white
// ════════════════════════════════════════════════════════════════════
// ALERTS
// ════════════════════════════════════════════════════════════════════
alertcondition(evFill, "Entry filled", "AE Position: entry filled on {{ticker}} at {{close}}")
alertcondition(evTarget, "Target hit", "AE Position: target hit on {{ticker}} at {{close}}")
alertcondition(evStop, "Stop hit", "AE Position: stop hit on {{ticker}} at {{close}}")
alertcondition(evFill or evTarget or evStop, "Any trade event", "AE Position: trade event on {{ticker}} at {{close}}")
if evFill
alert("AE Position · " + syminfo.ticker + " · Entry filled @ " + fmtPrice(entryPrice) + " · " + fmtSize(usedSize), alert.freq_once_per_bar)
if evTarget
alert("AE Position · " + syminfo.ticker + " · Target hit · " + fmtR(netRR) + " · " + fmtSigned(gainMoney), alert.freq_once_per_bar)
if evStop
alert("AE Position · " + syminfo.ticker + " · Stop hit · −1.00R · " + fmtSigned(-lossMoney), alert.freq_once_per_bar)
// ════════════════════════════════════════════════════════════════════
// POSITION ON THE CHART
// ════════════════════════════════════════════════════════════════════
string labelSize = switch labelSizeIn
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
=> size.large
var box riskBox = na
var box rewardBox = na
var line entryLn = na
var line stopLn = na
var line targetLn = na
var line pathLn = na
var label targetLbl = na
var label stopLbl = na
var label entryLbl = na
if barstate.islast
box.delete(riskBox)
box.delete(rewardBox)
line.delete(entryLn)
line.delete(stopLn)
line.delete(targetLn)
line.delete(pathLn)
label.delete(targetLbl)
label.delete(stopLbl)
label.delete(entryLbl)
if setupValid and not levelsFar
bool closed = state >= 3
int oldest = bar_index - 9000
int leftX = math.max(na(startBar) ? bar_index : startBar, oldest)
int rightX = closed ? math.max(exitBar, oldest) : bar_index + extendBars
rightX := math.max(rightX, leftX + 1)
int fadeT = math.min(boxTransp + 10, 97)
if showBoxes
int bw = boxBorder ? 1 : 0
riskBox := box.new(leftX, math.max(entryPrice, stopPrice), rightX, math.min(entryPrice, stopPrice), border_color = boxBorder ? color.new(lossCol, 65) : na, border_width = bw, bgcolor = color.new(lossCol, state == 3 ? fadeT : boxTransp))
rewardBox := box.new(leftX, math.max(entryPrice, targetPrice), rightX, math.min(entryPrice, targetPrice), border_color = boxBorder ? color.new(profitCol, 65) : na, border_width = bw, bgcolor = color.new(profitCol, state == 4 ? fadeT : boxTransp))
else
stopLn := line.new(leftX, stopPrice, rightX, stopPrice, color = lossCol, width = 2)
targetLn := line.new(leftX, targetPrice, rightX, targetPrice, color = profitCol, width = 2)
// Dashed entry while pending, solid once filled
entryLn := line.new(leftX, entryPrice, rightX, entryPrice, color = entryCol, width = 2, style = state <= 1 ? line.style_dashed : line.style_solid)
if state == 2
pathLn := line.new(math.max(fillBar, oldest), entryPrice, bar_index, close, color = moveDist >= 0 ? profitCol : lossCol, width = 1, style = line.style_dotted)
if labelMode != "Off"
bool full = labelMode == "Full"
string tTxt = full ? "TP " + fmtPrice(targetPrice) + " " + fmtR(netRR) + " " + fmtSigned(gainMoney) : "TP " + fmtR(netRR)
string sTxt = full ? "SL " + fmtPrice(stopPrice) + " −1.00R " + fmtSigned(-lossMoney) : "SL −1.00R"
string stateTxt = state == 2 ? " LIVE " + fmtR(liveR) : state == 3 ? " TP HIT" : state == 4 ? " SL HIT" : state == 1 ? " PENDING" : ""
string eTxt = fmtSize(usedSize) + (full ? " @ " + fmtPrice(entryPrice) : "") + stateTxt
// Left: labels end at the entry bar. Right: labels start at the end of the box.
bool onRight = labelSide == "Right of box"
int lx = onRight ? rightX : leftX
string ls = onRight ? label.style_label_left : label.style_label_right
targetLbl := label.new(lx, targetPrice, tTxt, color = profitCol, textcolor = textOn(profitCol), style = ls, size = labelSize)
stopLbl := label.new(lx, stopPrice, sTxt, color = lossCol, textcolor = textOn(lossCol), style = ls, size = labelSize)
entryLbl := label.new(lx, entryPrice, eTxt, color = entryCol, textcolor = textOn(entryCol), style = ls, size = labelSize)
// ════════════════════════════════════════════════════════════════════
// CARD
// ════════════════════════════════════════════════════════════════════
string cardPos = switch cardPosIn
"Top right" => position.top_right
"Bottom right" => position.bottom_right
"Top left" => position.top_left
=> position.bottom_left
string cBase = switch cardSizeIn
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
=> size.large
string cHero = switch cardSizeIn
"Tiny" => size.small
"Small" => size.normal
"Normal" => size.large
=> size.huge
var table card = table.new(cardPos, 2, 8, frame_color = color.rgb(38, 45, 58), frame_width = 1, border_color = color.rgb(11, 14, 19), border_width = 1)
cardCell(int c, int r, string txt, color bg, color fg, string sz, string tip) =>
table.cell(card, c, r, txt, text_color = fg, bgcolor = bg, text_size = sz, text_halign = text.align_left, tooltip = tip)
if barstate.islast and cardMode != "Off"
table.clear(card, 0, 0, 1, 7)
color bgHead = color.rgb(11, 14, 19)
color bgCell = color.rgb(20, 25, 34)
color bgHero = color.rgb(28, 35, 47)
color fg = color.rgb(226, 232, 240)
color cWarn = color.rgb(234, 179, 8)
color cLive = color.rgb(59, 130, 246)
color cIdle = color.rgb(100, 116, 139)
// Status — errors first, then trade state, then warnings
string sTxt = "READY"
color sCol = profitCol
string sTip = "Setup valid. The size matches your risk."
if not setupValid
sTxt := "CHECK LEVELS"
sCol := lossCol
sTip := "Stop and target must be on opposite sides of the entry."
else if levelsFar
sTxt := "RE-PLACE LEVELS"
sCol := lossCol
sTip := "The entry is far from the current price, probably left over from another symbol. Open the settings and pick new levels."
else if na(fxRate)
sTxt := "NO FX RATE"
sCol := lossCol
sTip := "No conversion rate from " + quoteCcy + " to " + accountCcy + " available."
else if belowMin
sTxt := "BELOW MIN SIZE"
sCol := lossCol
sTip := "Your risk is too small for the minimum size. " + fmtSize(minSize) + " would risk " + fmtPct(minRiskPct) + "."
else if state == 3
sTxt := "TARGET HIT"
sCol := profitCol
sTip := "The target was reached after the entry filled."
else if state == 4
sTxt := "STOP HIT"
sCol := lossCol
sTip := "The stop was reached after the entry filled. When stop and target fall in the same bar, the stop counts."
else if state == 2
sTxt := "ACTIVE"
sCol := cLive
sTip := "Entry filled. Tracking live."
else if capped
sTxt := "SIZE CAPPED"
sCol := cWarn
sTip := "Size limited by your max size, so the risk is lower than planned."
else if not na(effRiskPct) and effRiskPct > warnRisk
sTxt := "HIGH RISK"
sCol := cWarn
sTip := "Risk is above your " + fmtPct(warnRisk) + " limit."
else if not isFutures and not na(margin) and margin > accountSize
sTxt := "MARGIN > BALANCE"
sCol := cWarn
sTip := "Estimated margin at 1:" + fmtNum(leverage, 0) + " is larger than your balance."
else if not na(netRR) and netRR < warnRR
sTxt := "LOW R:R"
sCol := cWarn
sTip := "Reward after costs is below " + fmtNum(warnRR, 1) + "R."
else if state == 1
sTxt := "PENDING"
sCol := cIdle
sTip := "Waiting for price to reach the entry."
string dirTxt = isLong ? "LONG" : isShort ? "SHORT" : "—"
string riskTxt = na(lossMoney) ? "–" : lossMoney > 0 ? "−" + fmtMoney(lossMoney) : fmtMoney(0.0)
color rrCol = not na(netRR) and netRR < warnRR ? cWarn : fg
cardCell(0, 0, "Æ " + syminfo.ticker + " " + dirTxt, bgHead, fg, cBase, "Albrecht Edge · Position Size Calculator")
cardCell(1, 0, sTxt, sCol, textOn(sCol), cBase, sTip)
// No numbers while the setup can't be trusted — say what to fix instead
if not setupValid or levelsFar or na(fxRate)
string hint = not setupValid ? "Stop and target must sit on\nopposite sides of the entry." : levelsFar ? "These levels belong to another price.\nOpen the settings and pick new ones." : "No " + quoteCcy + " → " + accountCcy + " rate available."
cardCell(0, 1, hint, bgCell, fg, cBase, "")
cardCell(1, 1, "", bgCell, fg, cBase, "")
else
cardCell(0, 1, "SIZE\n" + fmtSize(usedSize), bgHero, fg, cHero, (sizeSource == "Manual" ? "Risk-based size: " : "Exact: ") + fmtNum(exactSize, 4) + (unitsPerLot != 1 ? " · " + fmtNum(usedSize * unitsPerLot, 0) + " units" : ""))
cardCell(1, 1, "RISK " + fmtPct(effRiskPct) + "\n" + riskTxt, bgCell, lossCol, cBase, "Stop distance plus spread and commission.")
cardCell(0, 2, (hasCosts ? "R:R NET" : "R:R") + "\n1 : " + fmtNum(netRR, 2), bgCell, rrCol, cBase, hasCosts ? "After spread and commission. Before costs: 1 : " + fmtNum(rr, 2) : "")
cardCell(1, 2, "REWARD\n" + fmtSigned(gainMoney), bgCell, profitCol, cBase, "Target distance minus spread and commission.")
int row = 3
if cardMode == "Full"
cardCell(0, row, "STOP\n" + fmtDist(stopDist), bgCell, fg, cBase, "")
cardCell(1, row, "TARGET\n" + fmtDist(targetDist), bgCell, fg, cBase, "")
row += 1
cardCell(0, row, "COSTS\n" + fmtMoney(costMoney), bgCell, fg, cBase, "Spread + commission, already included in risk and reward.")
cardCell(1, row, "MARGIN 1:" + fmtNum(leverage, 0) + "\n" + (isFutures ? "exchange" : fmtMoney(margin)), bgCell, fg, cBase, "Estimate: position value ÷ leverage.")
row += 1
cardCell(0, row, "BALANCE\n" + fmtMoney(accountSize), bgCell, fg, cBase, "")
cardCell(1, row, "EXPOSURE\n" + fmtMoney(exposure), bgCell, fg, cBase, "Position value in account currency.")
row += 1
if state >= 2
bool isLive = state == 2
float rVal = isLive ? liveR : resultR
float pVal = isLive ? livePnl : resultPnl
color pCol = na(pVal) ? cIdle : pVal >= 0 ? profitCol : lossCol
cardCell(0, row, (isLive ? "LIVE\n" : "RESULT\n") + fmtR(rVal), pCol, textOn(pCol), cBase, "")
cardCell(1, row, "P/L\n" + fmtSigned(pVal), pCol, textOn(pCol), cBase, "")