本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("FCP | Money Management Indicator | Position Size & DCA Entries", overlay = true, max_lines_count = 30, max_labels_count = 30, max_boxes_count = 4)
// ───────────────────────────── Inputs ─────────────────────────────
GRP_PLAN = "Plan"
GRP_MAN = "Extra entries (optional)"
GRP_ACC = "Account"
GRP_BRK = "Broker"
GRP_DISP = "Display"
float e1Inp = input.price(0.0, "Entry 1", group = GRP_PLAN, confirm = true, tooltip = "Step 1 of 3: click your Entry price", display = display.none)
float stopInp = input.price(0.0, "Stop loss", group = GRP_PLAN, confirm = true, tooltip = "Step 2 of 3: click your STOP LOSS price", display = display.none)
float tpInp = input.price(0.0, "Take profit", group = GRP_PLAN, confirm = true, tooltip = "Step 3 of 3: click your TAKE PROFIT price", display = display.none)
int levelsIn = input.int(1, "Entries", minval = 1, maxval = 5, group = GRP_PLAN, tooltip = "Entries 2 to 5 split the distance from Entry 1 to the stop evenly, unless you set their prices below.", display = display.none)
string splitIn = input.string("Equal", "Size split", options = ["Equal", "1-2-3", "1-2-4"], group = GRP_PLAN, tooltip = "How the total size is spread from the first entry to fill (E1) to the last.\n\nEqual: 2 entries 50/50%, 3 entries 33/33/33%\n1-2-3: 2 entries 33/67%, 3 entries 17/33/50%\n1-2-4: 2 entries 33/67%, 3 entries 14/29/57%\n\nThe panel shows each entry's share.", display = display.none)
float e2Inp = input.price(0.0, "Entry 2", group = GRP_MAN, tooltip = "0 = automatic. Type a price to set this entry; its line then becomes draggable.", display = display.none)
float e3Inp = input.price(0.0, "Entry 3", group = GRP_MAN, tooltip = "0 = automatic. Type a price to set this entry; its line then becomes draggable.", display = display.none)
float e4Inp = input.price(0.0, "Entry 4", group = GRP_MAN, tooltip = "0 = automatic. Type a price to set this entry; its line then becomes draggable.", display = display.none)
float e5Inp = input.price(0.0, "Entry 5", group = GRP_MAN, tooltip = "0 = automatic. Type a price to set this entry; its line then becomes draggable.", display = display.none)
float balanceIn = input.float(1000.0, "Balance (USD)", minval = 0, group = GRP_ACC, display = display.none)
float riskPctIn = input.float(1.0, "Risk %", minval = 0.01, maxval = 100, step = 0.1, group = GRP_ACC, display = display.none)
float levIn = input.float(1.0, "Leverage", minval = 1, maxval = 500, group = GRP_ACC, tooltip = "Leverage does not change the size: the risk and the stop set it. It only changes the margin you need and the liquidation price, shown in the panel.", display = display.none)
string sizeInIn = input.string("USDT", "Crypto size in", options = ["USDT", "Coins"], group = GRP_ACC, tooltip = "How crypto and stock sizes are shown: their value in USDT, as most exchanges ask for it, or the number of coins. Forex pairs, and any symbol with Contract size set, are shown in lots.", display = display.none)
float contractIn = input.float(0.0, "Contract size", minval = 0, group = GRP_BRK, tooltip = "The contract size of 1 lot on this symbol, not your trade size. Forex pairs always use 100,000 and ignore this field. For gold, silver, indices, oil, broker crypto and other CFDs, type your broker's value: it differs between brokers (gold is 100 oz at most, 1 or 10 at some). 0 = sizes are shown in units, not lots. Inputs are kept when you change the symbol, so check this field on every new symbol. To find it in MT4/MT5: Market Watch > right-click the symbol > Specification > Contract size.", display = display.none)
float stepIn = 0.01
bool zonesIn = input.bool(false, "Risk and reward zones", group = GRP_DISP, tooltip = "Shades the distance from the last entry to the stop in red and from Entry 1 to the take profit in green, like the Long and Short position tools.", display = display.none)
string posIn = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GRP_DISP, display = display.none)
string sizeIn = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"], group = GRP_DISP, display = display.none)
color entryCol = input.color(#2FE3C6, "Entries", group = GRP_DISP, inline = "c", display = display.none)
color stopCol = input.color(#FF6152, "Stop", group = GRP_DISP, inline = "c", display = display.none)
color tpCol = input.color(#39FF55, "Target", group = GRP_DISP, inline = "c", display = display.none)
color brandCol = input.color(#22345F, "Panel", group = GRP_DISP, inline = "c", display = display.none)
// ───────────────────────────── Market and currency ─────────────────────────────
isMetalCode(string c) =>
c == "XAU" or c == "XAG" or c == "XPT" or c == "XPD"
bool isMetal = isMetalCode(syminfo.basecurrency) or (str.length(syminfo.ticker) >= 3 and isMetalCode(str.substring(syminfo.ticker, 0, 3))) or syminfo.ticker == "GOLD" or syminfo.ticker == "SILVER"
bool isFx = syminfo.type == "forex" and not isMetal
bool isLots = isFx or contractIn > 0
float lotUnits = isFx ? 100000.0 : contractIn > 0 ? contractIn : 1.0
bool needLot = not isLots and (isMetal or syminfo.type == "cfd" or syminfo.type == "commodity" or syminfo.type == "index")
float sizeStep = isLots ? stepIn : 0.0
string unitName = isLots ? "lots" : syminfo.type == "crypto" and syminfo.basecurrency != "" ? syminfo.basecurrency : isMetal ? "oz" : syminfo.type == "futures" ? "contracts" : syminfo.type == "stock" ? "shares" : "units"
normCcy(string c) =>
c == "USDT" or c == "USDC" or c == "BUSD" or c == "FDUSD" or c == "DAI" ? "USD" : c
string quoteCcy = normCcy(syminfo.currency)
float fxRaw = request.currency_rate(quoteCcy, "USD", ignore_invalid_currency = true)
bool fxMissing = quoteCcy != "USD" and na(fxRaw)
float pvUsd = syminfo.pointvalue * (quoteCcy == "USD" or na(fxRaw) ? 1.0 : fxRaw)
float pipSize = syminfo.mintick * (math.round(math.log10(1 / syminfo.mintick)) % 2 == 1 ? 10 : 1)
// ───────────────────────────── Plan ─────────────────────────────
float atr14 = ta.atr(14)
int N = levelsIn
bool autoPlan = e1Inp <= 0 or stopInp <= 0
float aStep = nz(atr14, close * 0.01)
float base1 = autoPlan ? math.round_to_mintick(close - aStep) : e1Inp
float stopPx = autoPlan ? math.round_to_mintick(close - 3 * aStep) : stopInp
float tpIn = autoPlan or tpInp <= 0 ? math.round_to_mintick(close + 3 * aStep) : tpInp
extraEntry(float inp, int k) =>
not autoPlan and inp > 0 ? inp : math.round_to_mintick(base1 + (k - 1) * (stopPx - base1) / N)
array<float> rawEntries = array.from(base1, extraEntry(e2Inp, 2), extraEntry(e3Inp, 3), extraEntry(e4Inp, 4), extraEntry(e5Inp, 5)).slice(0, N)
float zTop = rawEntries.max()
float zBot = rawEntries.min()
bool isLong = stopPx < zBot
bool validGeo = zBot > 0 and stopPx > 0 and (stopPx < zBot or stopPx > zTop)
float dir = isLong ? 1.0 : -1.0
// ───────────────────────────── Helpers ─────────────────────────────
string txtSize = switch sizeIn
"Small" => size.small
"Large" => size.large
=> size.normal
color C_BG = color.new(brandCol, 8)
color C_TXT = #F4F2EC
color C_DIM = #93A0C0
color C_ACC = #39FF55
color C_GOLD = #FFD84D
weightAt(int i) =>
switch splitIn
"1-2-3" => i + 1.0
"1-2-4" => math.pow(2.0, i)
=> 1.0
tablePos(string s) =>
switch s
"Top right" => position.top_right
"Top left" => position.top_left
"Bottom left" => position.bottom_left
=> position.bottom_right
fmtMoney(float x) =>
str.tostring(x, "#,##0.00") + " USD"
fmtPx(float p) =>
str.tostring(p, format.mintick)
fmtSize(float units) =>
float v = units / lotUnits
str.tostring(v, isLots ? "#,##0.00" : v >= 100 ? "#,##0" : v >= 1 ? "#,##0.##" : v >= 0.01 ? "0.####" : "0.########")
bool sizeInUsd = not isLots and sizeInIn == "USDT"
string usdLabel = syminfo.currency == "USDT" ? "USDT" : "USD"
fmtQtyNum(float units, float px) =>
sizeInUsd ? str.tostring(units * px * pvUsd, "#,##0.00") : fmtSize(units)
fmtShare(float q, float total) =>
total > 0 ? str.tostring(q / total * 100, "0") + "%" : "-"
fmtQty(float units, float px) =>
fmtQtyNum(units, px) + " " + (sizeInUsd ? usdLabel : unitName)
fmtDist(float a, float b) =>
isFx ? str.tostring(math.abs(a - b) / pipSize, "#,##0.0") + " pips" : str.tostring(math.abs(a - b) / a * 100, "0.00") + "%"
rowKV(table t, int r, int lastCol, string k, string v, color vc) =>
t.cell(0, r, k, text_color = C_DIM, bgcolor = C_BG, text_size = txtSize, text_halign = text.align_left)
t.cell(1, r, v, text_color = vc, bgcolor = C_BG, text_size = txtSize, text_halign = text.align_left)
t.merge_cells(1, r, lastCol, r)
// ───────────────────────────── Sizing, chart and panel ─────────────────────────────
var array<line> drawLines = array.new<line>()
var array<label> drawLabels = array.new<label>()
var box zoneBox = na
var box riskBox = na
var box rewardBox = na
var table tbl = na
levelLine(float y, color c, int w, int x1, int xl) =>
drawLines.push(line.new(x1, y, xl, y, color = color.new(c, 60), style = line.style_dotted, width = w))
drawLines.push(line.new(xl, y, xl + 1, y, color = c, style = line.style_solid, width = w, extend = extend.right))
if barstate.islast
for l in drawLines
l.delete()
drawLines.clear()
for lb in drawLabels
lb.delete()
drawLabels.clear()
if not na(zoneBox)
zoneBox.delete()
if not na(riskBox)
riskBox.delete()
if not na(rewardBox)
rewardBox.delete()
if not na(tbl)
tbl.delete()
array<float> lvl = rawEntries.copy()
lvl.sort(isLong ? order.descending : order.ascending)
array<float> w = array.new<float>()
for i = 0 to N - 1
w.push(weightAt(i))
float wSum = w.sum()
float riskAmt = balanceIn * riskPctIn / 100
float stepU = sizeStep * lotUnits
array<float> lossU = array.new<float>()
array<float> gainU = array.new<float>()
float denom = 0.0
for i = 0 to N - 1
float e = lvl.get(i)
float lu = math.abs(e - stopPx) * pvUsd
lossU.push(lu)
gainU.push(dir * (tpIn - e) * pvUsd)
denom += w.get(i) / wSum * lu
float qTotal = denom > 0 ? riskAmt / denom : 0.0
array<float> qty = array.new<float>()
bool zeroLevel = false
float sQ = 0.0
float sCost = 0.0
float sLoss = 0.0
float sGain = 0.0
for i = 0 to N - 1
float raw = qTotal * w.get(i) / wSum
float q = stepU > 0 ? math.floor(raw / stepU + 1e-9) * stepU : raw
zeroLevel := zeroLevel or q <= 0
qty.push(q)
sQ += q
sCost += q * lvl.get(i)
sLoss += q * lossU.get(i)
sGain += q * gainU.get(i)
float avgAll = sQ > 0 ? sCost / sQ : na
float margin = sCost * pvUsd / levIn
bool showLiq = not isLots and levIn > 1 and sQ > 0
float liqPx = showLiq ? avgAll * (1 - dir / levIn + dir * 0.005) : na
bool liqWarn = showLiq and (isLong ? liqPx >= stopPx : liqPx <= stopPx)
array<string> warns = array.new<string>()
if not validGeo
warns.push("The stop must be outside the entries")
else
if riskAmt <= 0
warns.push("Set your balance to size the plan")
else if zeroLevel and stepU > 0
float minRisk = 0.0
for i = 0 to N - 1
minRisk += stepU * w.get(i) / w.get(0) * lossU.get(i)
warns.push("Below the minimum size: needs " + fmtMoney(minRisk) + " risk")
if tpIn > 0 and sQ > 0
if isLong ? tpIn <= avgAll : tpIn >= avgAll
warns.push("Take profit is on the wrong side")
if liqWarn
warns.push("Liquidation before the stop")
if balanceIn > 0 and margin > balanceIn
warns.push("Margin exceeds the balance")
if needLot
warns.push("Set Contract size from your broker to see lots")
if fxMissing
warns.push("No " + quoteCcy + "/USD rate: 1:1 used")
int x1 = bar_index - 10
int xl = bar_index + 3
if validGeo
if N > 1
zoneBox := box.new(x1, zTop, bar_index, zBot, border_color = color.new(entryCol, 85), bgcolor = color.new(entryCol, 95), extend = extend.right)
if zonesIn
float lastE = lvl.get(N - 1)
float firstE = lvl.get(0)
riskBox := box.new(x1, math.max(lastE, stopPx), bar_index, math.min(lastE, stopPx), border_width = 0, bgcolor = color.new(stopCol, 88), extend = extend.right)
if tpIn > 0 and dir * (tpIn - firstE) > 0
rewardBox := box.new(x1, math.max(firstE, tpIn), bar_index, math.min(firstE, tpIn), border_width = 0, bgcolor = color.new(tpCol, 88), extend = extend.right)
int avgLvl = -1
if N > 1 and sQ > 0
for i = 0 to N - 1
if math.abs(lvl.get(i) - avgAll) <= (zTop - zBot) * 0.03
avgLvl := i
for i = 0 to N - 1
float e = lvl.get(i)
levelLine(e, entryCol, 1, x1, xl)
float rrE = tpIn > 0 and dir * (tpIn - e) > 0 ? (tpIn - e) / (e - stopPx) : na
drawLabels.push(label.new(xl, e, "E" + str.tostring(i + 1) + " " + fmtPx(e) + " " + fmtQty(qty.get(i), e) + (N > 1 ? " (" + fmtShare(qty.get(i), sQ) + ")" : "") + (na(rrE) ? "" : " R:R " + str.tostring(rrE, "0.00")) + (i == avgLvl ? " = AVG" : ""), style = label.style_label_left, color = brandCol, textcolor = entryCol, size = txtSize))
if N > 1 and sQ > 0
levelLine(avgAll, C_GOLD, 1, x1, xl)
if avgLvl < 0
drawLabels.push(label.new(xl, avgAll, "AVG " + fmtPx(avgAll), style = label.style_label_left, color = brandCol, textcolor = C_GOLD, size = txtSize))
levelLine(stopPx, stopCol, 2, x1, xl)
drawLabels.push(label.new(xl, stopPx, "SL " + fmtPx(stopPx) + " -" + fmtMoney(sLoss), style = label.style_label_left, color = brandCol, textcolor = stopCol, size = txtSize))
if tpIn > 0
levelLine(tpIn, tpCol, 2, x1, xl)
drawLabels.push(label.new(xl, tpIn, "TP " + fmtPx(tpIn) + " " + (sGain >= 0 ? "+" : "") + fmtMoney(sGain), style = label.style_label_left, color = brandCol, textcolor = tpCol, size = txtSize))
int lastCol = 2
tbl := table.new(tablePos(posIn), lastCol + 1, 30, frame_color = brandCol, frame_width = 1, border_color = brandCol, border_width = 1)
tbl.cell(0, 0, "FCP", text_color = C_ACC, bgcolor = brandCol, text_size = txtSize, text_halign = text.align_left)
tbl.cell(1, 0, "MONEY MANAGEMENT", text_color = C_TXT, bgcolor = brandCol, text_size = txtSize, text_halign = text.align_left)
tbl.cell(lastCol, 0, validGeo ? (isLong ? "LONG" : "SHORT") : "", text_color = isLong ? tpCol : stopCol, bgcolor = brandCol, text_size = txtSize, text_halign = text.align_right)
tbl.cell(0, 1, "", bgcolor = C_ACC, text_size = size.tiny, height = 0.4)
tbl.merge_cells(0, 1, lastCol, 1)
int r = 2
if autoPlan
tbl.cell(0, r, "Example plan: its lines cannot be dragged", text_color = C_GOLD, bgcolor = C_BG, text_size = txtSize, text_halign = text.align_left)
tbl.merge_cells(0, r, lastCol, r)
r += 1
tbl.cell(0, r, "Remove the indicator, add it again and click 3 prices", text_color = C_TXT, bgcolor = C_BG, text_size = txtSize, text_halign = text.align_left)
tbl.merge_cells(0, r, lastCol, r)
r += 1
if warns.size() > 0
for j = 0 to warns.size() - 1
tbl.cell(0, r, "! " + warns.get(j), text_color = stopCol, bgcolor = C_BG, text_size = txtSize, text_halign = text.align_left)
tbl.merge_cells(0, r, lastCol, r)
r += 1
if validGeo
rowKV(tbl, r, lastCol, "Risk", fmtMoney(sLoss) + (balanceIn > 0 ? " (" + str.tostring(sLoss / balanceIn * 100, "0.00") + "%)" : ""), C_TXT)
r += 1
rowKV(tbl, r, lastCol, "Size", sizeInUsd ? str.tostring(sCost * pvUsd, "#,##0.00") + " " + usdLabel : fmtSize(sQ) + " " + unitName, C_TXT)
r += 1
if sQ > 0
if N > 1
rowKV(tbl, r, lastCol, "Avg entry", fmtPx(avgAll), C_GOLD)
r += 1
rowKV(tbl, r, lastCol, "Stop", fmtPx(stopPx) + " (" + fmtDist(avgAll, stopPx) + ")", stopCol)
r += 1
if tpIn > 0
rowKV(tbl, r, lastCol, "Target", fmtPx(tpIn) + " (" + fmtDist(avgAll, tpIn) + ")", tpCol)
r += 1
rowKV(tbl, r, lastCol, "Profit", (sGain >= 0 ? "+" : "") + fmtMoney(sGain) + (sLoss > 0 ? " (R:R " + str.tostring(sGain / sLoss, "0.00") + ")" : ""), sGain >= 0 ? tpCol : stopCol)
r += 1
if isLots
rowKV(tbl, r, lastCol, "Lot size", "1 lot = " + str.tostring(lotUnits, "#,##0.####") + " units", C_DIM)
r += 1
rowKV(tbl, r, lastCol, "Margin", fmtMoney(margin) + " at " + str.tostring(levIn, "0.##") + "x", balanceIn > 0 and margin > balanceIn ? stopCol : C_TXT)
r += 1
if showLiq
rowKV(tbl, r, lastCol, "Liquidation", "~" + fmtPx(liqPx), liqWarn ? stopCol : C_TXT)
r += 1
string sizeHead = sizeInUsd ? "Size (" + usdLabel + ")" : "Size"
array<string> heads = array.from("Entry", "Price", sizeHead)
for c = 0 to lastCol
tbl.cell(c, r, heads.get(c), text_color = C_ACC, bgcolor = brandCol, text_size = txtSize)
r += 1
for i = 0 to N - 1
tbl.cell(0, r, "E" + str.tostring(i + 1), text_color = entryCol, bgcolor = C_BG, text_size = txtSize)
tbl.cell(1, r, fmtPx(lvl.get(i)), text_color = C_TXT, bgcolor = C_BG, text_size = txtSize)
tbl.cell(2, r, fmtQtyNum(qty.get(i), lvl.get(i)) + (N > 1 ? " (" + fmtShare(qty.get(i), sQ) + ")" : ""), text_color = C_TXT, bgcolor = C_BG, text_size = txtSize)
r += 1