本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title = "Position Tool", shorttitle = "Trade", overlay = true,
max_boxes_count = 10, max_lines_count = 30, max_labels_count = 30, max_polylines_count = 100)
// Discretionary visual position aid; this indicator places no orders.
// Fixed References retains the modeled event tracking of the original tool.
// Anchored VWAP is chart-only: no band events, alerts, table or Data Window fields.
// In AVWAP mode the fixed stop and target remain planning references; readings stay live.
// Anchor: the first loaded chart bar opening at or after the entry timestamp.
// A timestamp before loaded history is unavailable, rather than silently re-anchored.
color PROFIT_C = #089981
color LOSS_C = #F23645
color PARTIAL_C = #FBC02D
color TRAIL_C = #DBB84D
color ENTRY_C = #E8E8E8
color TEXT_C = #F5F5F5
color LEMON_C = #FAF3B2
color PANEL_C = #161616
color BORDER_C = #3A3A3A
string MODE_MARKET = "Market / Manual"
string MODE_LIMIT = "Limit / Price Arrival"
string DISPLAY_CLEAN = "Clean Geometry"
string DISPLAY_HUD = "Box HUD"
string DISPLAY_AUDIT = "Audit Table"
string TABLE_COMPACT = "Compact"
string TABLE_FULL = "Full"
string G_GEOMETRY = "Primary Geometry"
string G_ENTRY = "Entry & Activation"
string G_MANAGE = "Management References"
string G_AVWAP = "Anchored VWAP — Chart Only"
string G_ALERTS = "Alerts"
string G_SIZE = "Risk & Leverage Sizing"
string G_TIME = "Planning Clock & Memory"
string G_VIEW = "Display Mode"
string G_FILLS = "Zone Fills"
string G_LINES = "Horizontal Lines"
string G_LABELS = "Right-Edge Labels"
string G_MARKS = "Vertical Markers & Tracker"
string G_TABLE = "Audit Table"
float entryPriceInput = input.price(0.0, "Entry", inline = "entry", confirm = true, group = G_GEOMETRY,
tooltip = "First click: set entry price and time. Do not move this point after an active trade begins.")
int entryTimeInput = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Time", inline = "entry", confirm = true, group = G_GEOMETRY)
int estimatedEndTimeInput = input.time(timestamp("03 Jan 2026 00:00 +0000"), "Estimated End", confirm = true, group = G_GEOMETRY,
tooltip = "Second click: set the right edge. This timestamp remains fixed when the chart timeframe changes.")
float stopPriceInput = input.price(0.0, "Stop", confirm = true, group = G_GEOMETRY,
tooltip = "Third click: initial invalidation below entry selects LONG; above entry selects SHORT. Keep this original risk boundary separate from the trailing reference.")
float targetPriceInput = input.price(0.0, "Target", confirm = true, group = G_GEOMETRY,
tooltip = "Fourth click: set the objective on the profit side of entry. A conflicting target refuses geometry; it never changes direction.")
string entryModeInput = input.string(MODE_MARKET, "Entry Mode", options = [MODE_MARKET, MODE_LIMIT], group = G_ENTRY)
bool marketActiveInput = input.bool(false, "Trade Active", group = G_ENTRY,
tooltip = "Market mode only. Turn on after entry. Limit mode activates from price arrival.")
string managementModeInput = input.string("Fixed References", "Management Mode",
options = ["Fixed References", "Anchored VWAP"], group = G_MANAGE,
tooltip = "Choose references to suit your intention. Fixed References enables the optional partial/trail guides and modeled event tracking. Anchored VWAP shows a live envelope from the entry-time anchor; fixed stop/target remain planning references and do not freeze the readout. Neither mode places orders.")
bool useAvwap = managementModeInput == "Anchored VWAP"
bool partialEnabledInput = input.bool(false, "Show Partial Profit", group = G_MANAGE, active = not useAvwap)
float partialRInput = input.float(1.7, "Partial Profit (R)", minval = 0.1, maxval = 100.0, step = 0.1, group = G_MANAGE, active = not useAvwap)
float partialManualPriceInput = input.float(0.0, "Partial Price Override (0 = R)", step = 0.00000001, group = G_MANAGE, active = not useAvwap,
tooltip = "Type a discretionary chart price. Leave at 0 to derive the partial from Partial Profit (R).")
float partialExitPctInput = input.float(50.0, "Partial Size (%)", minval = 0.0, maxval = 100.0, step = 1.0, group = G_MANAGE, active = not useAvwap)
bool trailEnabledInput = input.bool(false, "Show Trailing Reference", group = G_MANAGE, active = not useAvwap)
float trailRInput = input.float(0.75, "Trailing Reference (R)", minval = -10.0, maxval = 100.0, step = 0.05, group = G_MANAGE, active = not useAvwap)
float trailManualPriceInput = input.float(0.0, "Trail Price Override (0 = R)", step = 0.00000001, group = G_MANAGE, active = not useAvwap,
tooltip = "Type a discretionary chart price. Leave at 0 to derive the trailing reference from Trailing Reference (R).")
// Effective gates apply everywhere, including geometry checks, modeled events and readouts.
bool showPartialInput = not useAvwap and partialEnabledInput
bool showTrailInput = not useAvwap and trailEnabledInput
float avwapSourceInput = input.source(hlc3, "Source", group = G_AVWAP,
tooltip = "Volume-weighted source from the entry-time anchor. HLC3 matches the supplied reference settings.")
int avwapWidthInput = input.int(1, "Line Width", minval = 1, maxval = 5, group = G_AVWAP, active = useAvwap)
bool avwapMeanVisible = input.bool(true, "Mean", inline = "av0", group = G_AVWAP, active = useAvwap)
color avwapMeanColor = input.color(#CE93D8, "", inline = "av0", group = G_AVWAP, active = useAvwap)
bool avwapFirstVisible = input.bool(true, "Favorable 1 (σ)", inline = "av1", group = G_AVWAP, active = useAvwap)
float avwapFirstMultiple = input.float(1.0, "", minval = 0.0, step = 0.1, inline = "av1", group = G_AVWAP, active = useAvwap)
color avwapFirstColor = input.color(#A5D6A7, "", inline = "av1", group = G_AVWAP, active = useAvwap)
bool avwapSecondVisible = input.bool(true, "Favorable 2 (σ)", inline = "av2", group = G_AVWAP, active = useAvwap)
float avwapSecondMultiple = input.float(1.5, "", minval = 0.0, step = 0.1, inline = "av2", group = G_AVWAP, active = useAvwap)
color avwapSecondColor = input.color(#4DD0E1, "", inline = "av2", group = G_AVWAP, active = useAvwap)
bool avwapOuterVisible = input.bool(true, "Favorable 3 (σ)", inline = "av3", group = G_AVWAP, active = useAvwap)
float avwapOuterMultiple = input.float(2.0, "", minval = 0.0, step = 0.1, inline = "av3", group = G_AVWAP, active = useAvwap)
color avwapOuterColor = input.color(#FFB74D, "", inline = "av3", group = G_AVWAP, active = useAvwap)
bool avwapOpposingVisible = input.bool(true, "Opposing Reference (σ)", inline = "avr", group = G_AVWAP, active = useAvwap)
float avwapOpposingMultiple = input.float(1.0, "", minval = 0.0, step = 0.1, inline = "avr", group = G_AVWAP, active = useAvwap)
color avwapOpposingColor = input.color(#F77C80, "", inline = "avr", group = G_AVWAP, active = useAvwap)
bool alertsEnabledInput = input.bool(false, "Enable Alerts", group = G_ALERTS)
bool alertEntryInput = input.bool(true, "Entry / Price Arrival", group = G_ALERTS)
bool alertPartialInput = input.bool(true, "Partial Profit", group = G_ALERTS)
bool alertTrailInput = input.bool(true, "Trailing Reference", group = G_ALERTS)
bool alertTargetInput = input.bool(true, "Take Profit", group = G_ALERTS)
bool alertStopInput = input.bool(true, "Stop Loss", group = G_ALERTS)
bool alertAmbiguousInput = input.bool(true, "Ambiguous Bar", group = G_ALERTS)
bool sizingEnabledInput = input.bool(false, "Enable Sizing Estimate", group = G_SIZE)
float modelCapitalInput = input.float(0.0, "Model Capital (0 = unset)", minval = 0.0, step = 100.0, group = G_SIZE)
float riskPctInput = input.float(1.0, "Risk per Trade (%)", minval = 0.01, maxval = 100.0, step = 0.05, group = G_SIZE)
float leverageInput = input.float(1.0, "Leverage", minval = 1.0, maxval = 10000.0, step = 0.5, group = G_SIZE,
tooltip = "Caps notional exposure. This estimates initial margin only; it does not calculate liquidation or maintenance margin.")
float lotSizeInput = input.float(1.0, "Lot Size", minval = 0.00000001, step = 1.0, group = G_SIZE)
float pointValueInput = input.float(1.0, "Point Value", minval = 0.00000001, step = 0.01, group = G_SIZE)
float quantityStepInput = input.float(1.0, "Quantity Increment", minval = 0.00000001, step = 0.00000001, group = G_SIZE)
float halfLifeBarsInput = input.float(0.0, "Empirical Half-Life (bars, 0 = off)", minval = 0.0, maxval = 10000.0, step = 0.5, group = G_TIME,
tooltip = "Optional journal-derived setup half-life. Retention describes unusual age under a constant-hazard model; it is not a next-bar failure probability.")
string displayModeInput = input.string(DISPLAY_AUDIT, "Display Mode", options = [DISPLAY_CLEAN, DISPLAY_HUD, DISPLAY_AUDIT], group = G_VIEW)
bool showRightLabelsInput = input.bool(true, "Show Right-Edge Labels", group = G_VIEW)
color upperFillColorInput = input.color(#0B5D1E, "Beyond Partial", inline = "fu", group = G_FILLS)
int upperFillTransparencyInput = input.int(50, "Transparency", minval = 0, maxval = 100, inline = "fu", group = G_FILLS)
color lowerFillColorInput = input.color(#147629, "Entry to Partial", inline = "fl", group = G_FILLS)
int lowerFillTransparencyInput = input.int(33, "Transparency", minval = 0, maxval = 100, inline = "fl", group = G_FILLS)
color lossFillColorInput = input.color(LOSS_C, "Risk", inline = "fr", group = G_FILLS)
int lossFillTransparencyInput = input.int(50, "Transparency", minval = 0, maxval = 100, inline = "fr", group = G_FILLS)
int zoneBorderTransparencyInput = input.int(40, "Zone Border Transparency", minval = 0, maxval = 100, group = G_FILLS)
color targetLineColorInput = input.color(PROFIT_C, "Target", inline = "ln1", group = G_LINES)
string targetLineStyleInput = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln1", group = G_LINES)
int targetLineWidthInput = input.int(1, "Width", minval = 1, maxval = 5, inline = "ln1", group = G_LINES)
int targetLineTransparencyInput = input.int(0, "T", minval = 0, maxval = 100, inline = "ln1", group = G_LINES)
color partialLineColorInput = input.color(PARTIAL_C, "Partial", inline = "ln2", group = G_LINES)
string partialLineStyleInput = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln2", group = G_LINES)
int partialLineWidthInput = input.int(2, "Width", minval = 1, maxval = 5, inline = "ln2", group = G_LINES)
int partialLineTransparencyInput = input.int(0, "T", minval = 0, maxval = 100, inline = "ln2", group = G_LINES)
color trailLineColorInput = input.color(#F7525F, "Trail", inline = "ln3", group = G_LINES)
string trailLineStyleInput = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln3", group = G_LINES)
int trailLineWidthInput = input.int(3, "Width", minval = 1, maxval = 5, inline = "ln3", group = G_LINES)
int trailLineTransparencyInput = input.int(0, "T", minval = 0, maxval = 100, inline = "ln3", group = G_LINES)
color entryLineColorInput = input.color(#FFF59D, "Entry", inline = "ln4", group = G_LINES)
string entryLineStyleInput = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln4", group = G_LINES)
int entryLineWidthInput = input.int(2, "Width", minval = 1, maxval = 5, inline = "ln4", group = G_LINES)
int entryLineTransparencyInput = input.int(0, "T", minval = 0, maxval = 100, inline = "ln4", group = G_LINES)
color stopLineColorInput = input.color(LOSS_C, "Stop", inline = "ln5", group = G_LINES)
string stopLineStyleInput = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln5", group = G_LINES)
int stopLineWidthInput = input.int(1, "Width", minval = 1, maxval = 5, inline = "ln5", group = G_LINES)
int stopLineTransparencyInput = input.int(0, "T", minval = 0, maxval = 100, inline = "ln5", group = G_LINES)
string labelStyleInput = input.string("Plain Text", "Type", options = ["Tag", "Plain Text"], inline = "lab0", group = G_LABELS)
string labelSizeInput = input.string("Small", "Size", options = ["Tiny", "Small", "Normal", "Large"], inline = "lab0", group = G_LABELS)
int labelTransparencyInput = input.int(50, "Opacity T", minval = 0, maxval = 100, inline = "lab0", group = G_LABELS)
color targetLabelColorInput = input.color(PROFIT_C, "Target", inline = "lab1", group = G_LABELS)
color targetLabelTextInput = input.color(#A5D6A7, "Text", inline = "lab1", group = G_LABELS)
color partialLabelColorInput = input.color(PARTIAL_C, "Partial", inline = "lab2", group = G_LABELS)
color partialLabelTextInput = input.color(#FFCC80, "Text", inline = "lab2", group = G_LABELS)
color trailLabelColorInput = input.color(TRAIL_C, "Trail", inline = "lab3", group = G_LABELS)
color trailLabelTextInput = input.color(#F8717D, "Text", inline = "lab3", group = G_LABELS)
color entryLabelColorInput = input.color(ENTRY_C, "Entry", inline = "lab4", group = G_LABELS)
color entryLabelTextInput = input.color(#A5D6A7, "Text", inline = "lab4", group = G_LABELS)
color stopLabelColorInput = input.color(LOSS_C, "Stop", inline = "lab5", group = G_LABELS)
color stopLabelTextInput = input.color(#FFCC80, "Text", inline = "lab5", group = G_LABELS)
color markerColorInput = input.color(#80CBC4, "Entry Marker", inline = "mk1", group = G_MARKS)
color estimateColorInput = input.color(#FFF59D, "Estimate Marker", inline = "mk1", group = G_MARKS)
string markerLineStyleInput = input.string("Dotted", "Style", options = ["Solid", "Dashed", "Dotted"], inline = "mk2", group = G_MARKS)
int markerLineWidthInput = input.int(2, "Width", minval = 1, maxval = 5, inline = "mk2", group = G_MARKS)
int markerTransparencyInput = input.int(55, "T", minval = 0, maxval = 100, inline = "mk2", group = G_MARKS)
bool showTrackerInput = input.bool(true, "Show Entry-to-Price Tracker", group = G_MARKS)
color trackerColorInput = input.color(#A5D6A7, "Tracker", inline = "trk1", group = G_MARKS)
string trackerLineStyleInput = input.string("Dotted", "Style", options = ["Solid", "Dashed", "Dotted"], inline = "trk1", group = G_MARKS)
int trackerLineWidthInput = input.int(2, "Width", minval = 1, maxval = 5, inline = "trk2", group = G_MARKS)
int trackerTransparencyInput = input.int(3, "T", minval = 0, maxval = 100, inline = "trk2", group = G_MARKS)
string tableModeInput = input.string(TABLE_FULL, "Rows", options = [TABLE_COMPACT, TABLE_FULL], inline = "tb1", group = G_TABLE)
string tablePositionInput = input.string("Auto", "Position", options = ["Auto", "Top Left", "Top Right", "Bottom Left", "Bottom Right"], inline = "tb1", group = G_TABLE)
string tableSizeInput = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal", "Large"], inline = "tb2", group = G_TABLE)
bool autoTableThemeInput = input.bool(true, "Automatic Direction Theme", group = G_TABLE)
color tableBgInput = input.color(#0B5D1E, "Background", inline = "tb2", group = G_TABLE)
int tableTransparencyInput = input.int(80, "T", minval = 0, maxval = 100, inline = "tb2", group = G_TABLE)
color tableBorderInput = input.color(#5C5848, "Border", inline = "tb3", group = G_TABLE)
color tableLabelInput = input.color(#E0E0E0, "Pane labels", inline = "tb3", group = G_TABLE)
// Direction belongs to INITIAL invalidation, never to the target, current quote or trail.
bool directionValid = math.abs(entryPriceInput - stopPriceInput) >= syminfo.mintick
bool IS_LONG = stopPriceInput < entryPriceInput
string directionText = not directionValid ? "UNDEFINED" : IS_LONG ? "LONG" : "SHORT"
string resolvedTablePosition = tablePositionInput == "Auto" ? (IS_LONG ? "Top Right" : "Bottom Right") : tablePositionInput
color resolvedTableBg = autoTableThemeInput ? (IS_LONG ? #0B5D1E : #B32635) : tableBgInput
int resolvedTableTransparency = autoTableThemeInput ? (IS_LONG ? 80 : 85) : tableTransparencyInput
float stopPrice = stopPriceInput
float targetPrice = targetPriceInput
float riskDistance = math.abs(entryPriceInput - stopPrice)
bool partialManual = partialManualPriceInput != 0.0
bool trailManual = trailManualPriceInput != 0.0
float partialPrice = partialManual ? partialManualPriceInput : (IS_LONG ? entryPriceInput + partialRInput * riskDistance : entryPriceInput - partialRInput * riskDistance)
float trailPrice = trailManual ? trailManualPriceInput : (IS_LONG ? entryPriceInput + trailRInput * riskDistance : entryPriceInput - trailRInput * riskDistance)
float targetR = riskDistance > 0.0 ? (IS_LONG ? targetPrice - entryPriceInput : entryPriceInput - targetPrice) / riskDistance : na
float partialR = riskDistance > 0.0 ? (IS_LONG ? partialPrice - entryPriceInput : entryPriceInput - partialPrice) / riskDistance : na
float trailR = riskDistance > 0.0 ? (IS_LONG ? trailPrice - entryPriceInput : entryPriceInput - trailPrice) / riskDistance : na
bool primaryGeometryValid = directionValid and (IS_LONG ?
stopPrice < entryPriceInput and targetPrice > entryPriceInput :
stopPrice > entryPriceInput and targetPrice < entryPriceInput)
bool partialGeometryValid = not showPartialInput or (IS_LONG ?
targetPrice > partialPrice and partialPrice > entryPriceInput :
targetPrice < partialPrice and partialPrice < entryPriceInput)
float trailBoundary = showPartialInput ? partialPrice : targetPrice
bool trailGeometryValid = not showTrailInput or (IS_LONG ?
trailPrice > stopPrice and trailPrice < trailBoundary :
trailPrice < stopPrice and trailPrice > trailBoundary)
bool geometryValid = primaryGeometryValid and partialGeometryValid and trailGeometryValid
bool anchorHere = time >= entryTimeInput and nz(time[1], 0) < entryTimeInput
int anchorBar = ta.valuewhen(anchorHere, bar_index, 0)
// Calculate on every bar; only the chart plots are conditional. Never reset by session.
var int firstLoadedTime = time
bool avwapAnchorAvailable = entryTimeInput >= firstLoadedTime
bool avwapReset = anchorHere and avwapAnchorAvailable
[anchoredMean, anchoredUpperOne, anchoredLowerOne] = ta.vwap(avwapSourceInput, avwapReset, 1.0)
float anchoredSigma = math.max(anchoredUpperOne - anchoredMean, 0.0)
float avwapDirection = IS_LONG ? 1.0 : -1.0
bool avwapDrawable = useAvwap and directionValid and avwapAnchorAvailable and time >= entryTimeInput and not na(volume) and not na(anchoredMean)
// Curves are drawings above linefill shading. Transparent boxes retain borders/HUD.
// Each written call owns a separate path. Completed 10,000-point chunks retain
// the anchor history; only the current chunk is recreated on live updates.
// No curve values enter plots, the Data Window, price scale, table or alerts.
avwapPath(float value, color pathColor, int pathWidth) =>
var array<chart.point> points = array.new<chart.point>()
var polyline livePath = na
if not na(value)
array.push(points, chart.point.from_time(time, value))
bool fullChunk = array.size(points) >= 10000
bool gap = na(value) and array.size(points) > 0
if fullChunk or gap
polyline.delete(livePath)
livePath := na
if array.size(points) >= 2
polyline.new(points, curved = false, closed = false, xloc = xloc.bar_time,
line_color = pathColor, line_width = pathWidth)
chart.point lastPoint = array.last(points)
array.clear(points)
if fullChunk and not gap
array.push(points, lastPoint)
if barstate.islast
polyline.delete(livePath)
livePath := na
if array.size(points) >= 2
livePath := polyline.new(points, curved = false, closed = false, xloc = xloc.bar_time,
line_color = pathColor, line_width = pathWidth)
avwapPath(avwapDrawable and avwapMeanVisible ? anchoredMean : na, avwapMeanColor, avwapWidthInput)
avwapPath(avwapDrawable and avwapFirstVisible ? anchoredMean + avwapDirection * avwapFirstMultiple * anchoredSigma : na,
avwapFirstColor, avwapWidthInput)
avwapPath(avwapDrawable and avwapSecondVisible ? anchoredMean + avwapDirection * avwapSecondMultiple * anchoredSigma : na,
avwapSecondColor, avwapWidthInput)
avwapPath(avwapDrawable and avwapOuterVisible ? anchoredMean + avwapDirection * avwapOuterMultiple * anchoredSigma : na,
avwapOuterColor, avwapWidthInput)
avwapPath(avwapDrawable and avwapOpposingVisible ? anchoredMean - avwapDirection * avwapOpposingMultiple * anchoredSigma : na,
avwapOpposingColor, avwapWidthInput)
var bool limitFilled = false
var int limitFillBar = na
var int limitFillTime = na
bool limitEligible = geometryValid and entryModeInput == MODE_LIMIT and time >= entryTimeInput
bool limitArrival = limitEligible and (IS_LONG ? low <= entryPriceInput : high >= entryPriceInput)
if not limitFilled and limitArrival
limitFilled := true
limitFillBar := bar_index
limitFillTime := time
bool marketActive = geometryValid and entryModeInput == MODE_MARKET and marketActiveInput and time >= entryTimeInput
bool limitActive = entryModeInput == MODE_LIMIT and limitFilled
bool tradeActive = marketActive or limitActive
int activationBar = entryModeInput == MODE_MARKET ? anchorBar : limitFillBar
bool justActivated = tradeActive and not tradeActive[1]
var bool partialTouched = false
var bool tradeClosed = false
var string outcome = ""
var int exitTime = na
var float exitPrice = na
var float favorableExtremePrice = na
if justActivated
partialTouched := false
tradeClosed := false
outcome := ""
exitTime := na
exitPrice := na
favorableExtremePrice := IS_LONG ? high : low
else if tradeActive and not tradeClosed
favorableExtremePrice := IS_LONG ? math.max(nz(favorableExtremePrice, high), high) : math.min(nz(favorableExtremePrice, low), low)
bool trailArmedBeforeBar = tradeActive and showTrailInput and (not showPartialInput or partialTouched)
bool eventEligible = not useAvwap and tradeActive and geometryValid and not tradeClosed and not na(activationBar) and bar_index > activationBar
bool hitStop = eventEligible and (IS_LONG ? low <= stopPrice : high >= stopPrice)
bool hitTarget = eventEligible and (IS_LONG ? high >= targetPrice : low <= targetPrice)
bool hitPartial = eventEligible and showPartialInput and not partialTouched and (IS_LONG ? high >= partialPrice : low <= partialPrice)
bool hitTrail = eventEligible and showTrailInput and trailArmedBeforeBar and (IS_LONG ? low <= trailPrice : high >= trailPrice)
bool ambiguousBar = eventEligible and ((hitStop and (hitPartial or hitTarget)) or (hitTrail and hitTarget))
fireEvent(string eventName, float eventLevel) =>
string message = "Position Tool " + directionText + " | " + syminfo.tickerid + " | " + eventName + " | " + str.tostring(eventLevel, format.mintick)
alert(message, alert.freq_once_per_bar)
if alertsEnabledInput and geometryValid and justActivated and alertEntryInput
fireEvent(entryModeInput == MODE_LIMIT ? "LIMIT ENTRY FILLED" : "MARKET TRADE ACTIVE", entryPriceInput)
if eventEligible
if ambiguousBar
tradeClosed := true
outcome := "AMBIGUOUS"
exitTime := time
exitPrice := close
if alertsEnabledInput and alertAmbiguousInput
fireEvent("AMBIGUOUS BAR", close)
else if hitTarget
partialTouched := partialTouched or hitPartial
tradeClosed := true
outcome := "TARGET"
exitTime := time
exitPrice := targetPrice
if alertsEnabledInput and alertTargetInput
fireEvent("TAKE PROFIT", targetPrice)
else if hitStop
tradeClosed := true
outcome := "STOP"
exitTime := time
exitPrice := stopPrice
if alertsEnabledInput and alertStopInput
fireEvent("STOP LOSS", stopPrice)
else if hitTrail
tradeClosed := true
outcome := "TRAIL"
exitTime := time
exitPrice := trailPrice
if alertsEnabledInput and alertTrailInput
fireEvent("TRAILING REFERENCE", trailPrice)
else if hitPartial
partialTouched := true
if alertsEnabledInput and alertPartialInput
fireEvent("PARTIAL PROFIT", partialPrice)
bool trailArmed = tradeActive and not tradeClosed and showTrailInput and (not showPartialInput or partialTouched)
float riskBudget = modelCapitalInput * riskPctInput / 100.0
float riskPerQuantity = riskDistance * pointValueInput * lotSizeInput
float notionalPerQuantity = entryPriceInput * pointValueInput * lotSizeInput
float riskQuantity = sizingEnabledInput and modelCapitalInput > 0.0 and riskPerQuantity > 0.0 ? riskBudget / riskPerQuantity : na
float leverageQuantity = sizingEnabledInput and modelCapitalInput > 0.0 and notionalPerQuantity > 0.0 ? modelCapitalInput * leverageInput / notionalPerQuantity : na
float rawQuantity = not na(riskQuantity) and not na(leverageQuantity) ? math.min(riskQuantity, leverageQuantity) : na
float roundedQuantity = not na(rawQuantity) ? math.floor(rawQuantity / quantityStepInput) * quantityStepInput : na
float positionUnits = not na(roundedQuantity) ? roundedQuantity * lotSizeInput : na
float estimatedInitialRisk = not na(roundedQuantity) ? roundedQuantity * riskPerQuantity : na
float notionalExposure = not na(roundedQuantity) ? roundedQuantity * notionalPerQuantity : na
float effectiveLeverage = not na(notionalExposure) and modelCapitalInput > 0.0 ? notionalExposure / modelCapitalInput : na
float initialMargin = not na(notionalExposure) ? notionalExposure / leverageInput : na
float marginUsePct = not na(initialMargin) and modelCapitalInput > 0.0 ? initialMargin / modelCapitalInput * 100.0 : na
float performancePrice = tradeClosed and not na(exitPrice) ? exitPrice : close
float priceMovePct = entryPriceInput > 0.0 ? (IS_LONG ? performancePrice - entryPriceInput : entryPriceInput - performancePrice) / entryPriceInput * 100.0 : na
float drawdownFromExtremePct = not na(favorableExtremePrice) and favorableExtremePrice > 0.0 ?
(IS_LONG ? performancePrice - favorableExtremePrice : favorableExtremePrice - performancePrice) / favorableExtremePrice * 100.0 : na
float stopDistancePct = performancePrice > 0.0 ? (IS_LONG ? performancePrice - stopPrice : stopPrice - performancePrice) / performancePrice * 100.0 : na
float partialDistancePct = showPartialInput and performancePrice > 0.0 ? (IS_LONG ? partialPrice - performancePrice : performancePrice - partialPrice) / performancePrice * 100.0 : na
float targetDistancePct = performancePrice > 0.0 ? (IS_LONG ? targetPrice - performancePrice : performancePrice - targetPrice) / performancePrice * 100.0 : na
float openPnl = not na(roundedQuantity) ? (IS_LONG ? performancePrice - entryPriceInput : entryPriceInput - performancePrice) * roundedQuantity * pointValueInput * lotSizeInput : na
float openPnlPct = not na(openPnl) and modelCapitalInput > 0.0 ? openPnl / modelCapitalInput * 100.0 : na
float stopPnl = not na(roundedQuantity) ? (IS_LONG ? stopPrice - entryPriceInput : entryPriceInput - stopPrice) * roundedQuantity * pointValueInput * lotSizeInput : na
float partialPnl = showPartialInput and not na(roundedQuantity) ? (IS_LONG ? partialPrice - entryPriceInput : entryPriceInput - partialPrice) * roundedQuantity * pointValueInput * lotSizeInput * partialExitPctInput / 100.0 : na
float targetPnl = not na(roundedQuantity) ? (IS_LONG ? targetPrice - entryPriceInput : entryPriceInput - targetPrice) * roundedQuantity * pointValueInput * lotSizeInput : na
float stopBalance = not na(stopPnl) ? modelCapitalInput + stopPnl : na
float partialBalance = not na(partialPnl) ? modelCapitalInput + partialPnl : na
float targetBalance = not na(targetPnl) ? modelCapitalInput + targetPnl : na
int drawStartTime = entryModeInput == MODE_LIMIT and limitFilled ? limitFillTime : entryTimeInput
int drawEndTime = estimatedEndTimeInput
bool timeGeometryValid = drawEndTime > drawStartTime
bool drawable = timeGeometryValid
int clockTime = tradeClosed and not na(exitTime) ? exitTime : time
float tfMilliseconds = timeframe.in_seconds() * 1000.0
float plannedMilliseconds = float(drawEndTime - drawStartTime)
float elapsedMilliseconds = drawable ? math.max(float(clockTime - drawStartTime), 0.0) : na
float remainingMilliseconds = drawable ? math.max(float(drawEndTime - clockTime), 0.0) : na
float overtimeMilliseconds = drawable ? math.max(float(clockTime - drawEndTime), 0.0) : na
float plannedBars = drawable ? plannedMilliseconds / tfMilliseconds : na
float elapsedBars = drawable ? elapsedMilliseconds / tfMilliseconds : na
float remainingBars = drawable ? remainingMilliseconds / tfMilliseconds : na
float overtimeBars = drawable ? overtimeMilliseconds / tfMilliseconds : na
float timeUsedPct = drawable and plannedMilliseconds > 0.0 ? elapsedMilliseconds / plannedMilliseconds * 100.0 : na
float currentR = riskDistance > 0.0 ? (IS_LONG ? performancePrice - entryPriceInput : entryPriceInput - performancePrice) / riskDistance : na
float currentRPerBar = not na(currentR) and elapsedBars > 0 ? currentR / elapsedBars : na
float partialRPerRemainingBar = showPartialInput and remainingBars > 0 and not na(currentR) ? (partialR - currentR) / remainingBars : na
float targetRPerRemainingBar = remainingBars > 0 and not na(currentR) ? (targetR - currentR) / remainingBars : na
float targetProgressPct = targetPrice != entryPriceInput ? (IS_LONG ? performancePrice - entryPriceInput : entryPriceInput - performancePrice) /
(IS_LONG ? targetPrice - entryPriceInput : entryPriceInput - targetPrice) * 100.0 : na
float paceRatio = not na(targetProgressPct) and timeUsedPct > 0.0 ? targetProgressPct / timeUsedPct : na
float ageHalfLives = halfLifeBarsInput > 0.0 and not na(elapsedBars) ? elapsedBars / halfLifeBarsInput : na
float modelRetainedPct = not na(ageHalfLives) ? math.pow(0.5, ageHalfLives) * 100.0 : na
int trackerEndTime = tradeClosed and not na(exitTime) ? exitTime : time
float trackerEndPrice = performancePrice
lineStyle(string choice) =>
switch choice
"Solid" => line.style_solid
"Dashed" => line.style_dashed
=> line.style_dotted
textSize(string choice) =>
switch choice
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
labelStyle(string choice) => choice == "Plain Text" ? label.style_none : label.style_label_left
tablePosition(string choice) =>
switch choice
"Top Left" => position.top_left
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.top_right
fmt(float value, string pattern) => na(value) ? "—" : str.tostring(value, pattern)
signed(float value, string pattern) => na(value) ? "—" : (value >= 0.0 ? "+" : "") + str.tostring(value, pattern)
money(float value) => na(value) ? "—" : (value >= 0.0 ? "+" : "") + str.tostring(value, "#.##")
signedColor(float value) => na(value) ? tableLabelInput : value > 0.0 ? PROFIT_C : value < 0.0 ? LOSS_C : LEMON_C
barsText(float value) => na(value) ? "—" : math.round(value) == 1 ? "1 bar" : str.tostring(math.round(value), "#") + " bars"
timeText(int value) => str.format_time(value, "yyyy-MM-dd HH:mm")
durationText(float milliseconds) =>
string result = "—"
if not na(milliseconds)
float minutes = math.round(milliseconds / 60000.0)
float hours = math.floor(minutes / 60.0)
float mins = minutes - hours * 60.0
result := hours >= 1.0 ? "≈ " + str.tostring(hours, "#") + " h " + str.tostring(mins, "#") + " min elapsed" : "≈ " + str.tostring(math.max(mins, 1.0), "#") + " min elapsed"
result
float rewardSplitPrice = showPartialInput ? partialPrice : targetPrice
float upperRewardTop = IS_LONG ? targetPrice : rewardSplitPrice
float upperRewardBottom = IS_LONG ? rewardSplitPrice : targetPrice
float lowerRewardTop = IS_LONG ? rewardSplitPrice : entryPriceInput
float lowerRewardBottom = IS_LONG ? entryPriceInput : rewardSplitPrice
float lossTop = IS_LONG ? entryPriceInput : stopPrice
float lossBottom = IS_LONG ? stopPrice : entryPriceInput
float markerY = math.min(targetPrice, stopPrice) - riskDistance * 0.20
var box upperRewardBox = na
var box lowerRewardBox = na
var box lossBox = na
var line targetLine = na
var line partialLine = na
var line trailLine = na
var line entryLine = na
var line stopLine = na
var line enterVertical = na
var line estimateVertical = na
var line trackerLine = na
var linefill avwapRewardFill = na
var linefill avwapRiskFill = na
var label targetLabel = na
var label partialLabel = na
var label trailLabel = na
var label entryLabel = na
var label stopLabel = na
var label enterLabel = na
var label estimateLabel = na
priceText(float value) => str.tostring(value, format.mintick)
rText(float value) => str.tostring(value, "#.##") + "R"
pctText(float value) => str.tostring(math.abs(value - entryPriceInput) / entryPriceInput * 100.0, "#.##") + "%"
bool showHud = displayModeInput == DISPLAY_HUD
string clockSummary = barsText(elapsedBars) + " / " + barsText(plannedBars) + " · " + fmt(timeUsedPct, "#.0") + "% used"
string upperHud = "TARGET " + priceText(targetPrice) + " · " + rText(targetR) +
"\nAway " + signed(targetDistancePct, "#.00") + "% · Pace " + fmt(paceRatio, "#.00") + "x" +
"\nNeed " + signed(targetRPerRemainingBar, "#.000") + " R/bar"
string partialHud = showPartialInput ? "\nPARTIAL " + priceText(partialPrice) + " · " + signed(partialDistancePct, "#.00") + "% away" : ""
string lowerHud = "CURRENT " + priceText(performancePrice) + " · " + signed(currentR, "#.00") + "R / " + signed(priceMovePct, "#.00") + "%" +
partialHud +
"\n" + clockSummary
string riskHud = "STOP " + priceText(stopPrice) + " · " + signed(currentR + 1.0, "#.00") + "R room" +
"\nFrom stop " + signed(stopDistancePct, "#.00") + "% · Drawdown " + signed(drawdownFromExtremePct, "#.00") + "%" +
(sizingEnabledInput ? "\nRisk " + money(estimatedInitialRisk) + " · Margin " + fmt(initialMargin, "#.##") +
"\nNotional " + fmt(notionalExposure, "#.##") + " · " + fmt(effectiveLeverage, "#.00") + "x" : "")
if barstate.islast and drawable
if na(upperRewardBox)
upperRewardBox := box.new(left = drawStartTime, top = upperRewardTop, right = drawEndTime, bottom = upperRewardBottom,
xloc = xloc.bar_time, border_color = color.new(upperFillColorInput, zoneBorderTransparencyInput), bgcolor = (useAvwap ? na : color.new(upperFillColorInput, upperFillTransparencyInput)))
lowerRewardBox := box.new(left = drawStartTime, top = lowerRewardTop, right = drawEndTime, bottom = lowerRewardBottom,
xloc = xloc.bar_time, border_color = color.new(lowerFillColorInput, zoneBorderTransparencyInput), bgcolor = (useAvwap ? na : color.new(lowerFillColorInput, lowerFillTransparencyInput)))
lossBox := box.new(left = drawStartTime, top = lossTop, right = drawEndTime, bottom = lossBottom,
xloc = xloc.bar_time, border_color = color.new(lossFillColorInput, zoneBorderTransparencyInput), bgcolor = (useAvwap ? na : color.new(lossFillColorInput, lossFillTransparencyInput)))
targetLine := line.new(drawStartTime, targetPrice, drawEndTime, targetPrice, xloc = xloc.bar_time)
partialLine := line.new(drawStartTime, partialPrice, drawEndTime, partialPrice, xloc = xloc.bar_time)
trailLine := line.new(drawStartTime, trailPrice, drawEndTime, trailPrice, xloc = xloc.bar_time)
entryLine := line.new(drawStartTime, entryPriceInput, drawEndTime, entryPriceInput, xloc = xloc.bar_time)
stopLine := line.new(drawStartTime, stopPrice, drawEndTime, stopPrice, xloc = xloc.bar_time)
enterVertical := line.new(drawStartTime, markerY, drawStartTime, math.max(targetPrice, stopPrice), xloc = xloc.bar_time)
estimateVertical := line.new(drawEndTime, markerY, drawEndTime, math.max(targetPrice, stopPrice), xloc = xloc.bar_time)
trackerLine := line.new(drawStartTime, entryPriceInput, trackerEndTime, trackerEndPrice, xloc = xloc.bar_time)
// Linefill shading sits below curve drawings; box backgrounds are transparent.
if useAvwap
avwapRewardFill := linefill.new(targetLine, entryLine, color.new(lowerFillColorInput, lowerFillTransparencyInput))
avwapRiskFill := linefill.new(entryLine, stopLine, color.new(lossFillColorInput, lossFillTransparencyInput))
targetLabel := label.new(drawEndTime, targetPrice, "", xloc = xloc.bar_time)
partialLabel := label.new(drawEndTime, partialPrice, "", xloc = xloc.bar_time)
trailLabel := label.new(drawEndTime, trailPrice, "", xloc = xloc.bar_time)
entryLabel := label.new(drawEndTime, entryPriceInput, "", xloc = xloc.bar_time)
stopLabel := label.new(drawEndTime, stopPrice, "", xloc = xloc.bar_time)
enterLabel := label.new(drawStartTime, markerY, "", xloc = xloc.bar_time, style = label.style_none, textcolor = markerColorInput, size = size.tiny)
estimateLabel := label.new(drawEndTime, markerY, "ESTIMATED", xloc = xloc.bar_time, style = label.style_none, textcolor = estimateColorInput, size = size.tiny)
box.set_left(upperRewardBox, drawStartTime)
box.set_right(upperRewardBox, drawEndTime)
box.set_top(upperRewardBox, upperRewardTop)
box.set_bottom(upperRewardBox, upperRewardBottom)
box.set_bgcolor(upperRewardBox, (useAvwap ? na : color.new(upperFillColorInput, upperFillTransparencyInput)))
box.set_border_color(upperRewardBox, color.new(upperFillColorInput, zoneBorderTransparencyInput))
box.set_text(upperRewardBox, showHud and showPartialInput ? upperHud : "")
box.set_text_color(upperRewardBox, LEMON_C)
box.set_text_size(upperRewardBox, textSize(labelSizeInput))
box.set_text_halign(upperRewardBox, text.align_left)
box.set_text_valign(upperRewardBox, text.align_center)
box.set_left(lowerRewardBox, drawStartTime)
box.set_right(lowerRewardBox, drawEndTime)
box.set_top(lowerRewardBox, lowerRewardTop)
box.set_bottom(lowerRewardBox, lowerRewardBottom)
box.set_bgcolor(lowerRewardBox, (useAvwap ? na : color.new(lowerFillColorInput, lowerFillTransparencyInput)))
box.set_border_color(lowerRewardBox, color.new(lowerFillColorInput, zoneBorderTransparencyInput))
box.set_text(lowerRewardBox, showHud ? (showPartialInput ? lowerHud : upperHud + "\n" + lowerHud) : "")
box.set_text_color(lowerRewardBox, LEMON_C)
box.set_text_size(lowerRewardBox, textSize(labelSizeInput))
box.set_text_halign(lowerRewardBox, text.align_left)
box.set_text_valign(lowerRewardBox, text.align_center)
box.set_left(lossBox, drawStartTime)
box.set_right(lossBox, drawEndTime)
box.set_top(lossBox, lossTop)
box.set_bottom(lossBox, lossBottom)
box.set_bgcolor(lossBox, (useAvwap ? na : color.new(lossFillColorInput, lossFillTransparencyInput)))
box.set_border_color(lossBox, color.new(lossFillColorInput, zoneBorderTransparencyInput))
box.set_text(lossBox, showHud ? riskHud : "")
box.set_text_color(lossBox, LEMON_C)
box.set_text_size(lossBox, textSize(labelSizeInput))
box.set_text_halign(lossBox, text.align_left)
box.set_text_valign(lossBox, text.align_center)
line.set_xy1(targetLine, drawStartTime, targetPrice)
line.set_xy2(targetLine, drawEndTime, targetPrice)
line.set_color(targetLine, color.new(targetLineColorInput, targetLineTransparencyInput))
line.set_style(targetLine, lineStyle(targetLineStyleInput))
line.set_width(targetLine, targetLineWidthInput)
line.set_xy1(partialLine, drawStartTime, partialPrice)
line.set_xy2(partialLine, drawEndTime, partialPrice)
line.set_color(partialLine, showPartialInput ? color.new(partialLineColorInput, partialLineTransparencyInput) : color.new(partialLineColorInput, 100))
line.set_style(partialLine, lineStyle(partialLineStyleInput))
line.set_width(partialLine, partialLineWidthInput)
line.set_xy1(trailLine, drawStartTime, trailPrice)
line.set_xy2(trailLine, drawEndTime, trailPrice)
line.set_color(trailLine, showTrailInput ? color.new(trailLineColorInput, trailLineTransparencyInput) : color.new(trailLineColorInput, 100))
line.set_style(trailLine, lineStyle(trailLineStyleInput))
line.set_width(trailLine, trailLineWidthInput)
line.set_xy1(entryLine, drawStartTime, entryPriceInput)
line.set_xy2(entryLine, drawEndTime, entryPriceInput)
line.set_color(entryLine, color.new(entryLineColorInput, entryLineTransparencyInput))
line.set_style(entryLine, lineStyle(entryLineStyleInput))
line.set_width(entryLine, entryLineWidthInput)
line.set_xy1(stopLine, drawStartTime, stopPrice)
line.set_xy2(stopLine, drawEndTime, stopPrice)
line.set_color(stopLine, color.new(stopLineColorInput, stopLineTransparencyInput))
line.set_style(stopLine, lineStyle(stopLineStyleInput))
line.set_width(stopLine, stopLineWidthInput)
line.set_xy1(enterVertical, drawStartTime, markerY)
line.set_xy2(enterVertical, drawStartTime, math.max(targetPrice, stopPrice))
line.set_color(enterVertical, color.new(markerColorInput, markerTransparencyInput))
line.set_style(enterVertical, lineStyle(markerLineStyleInput))
line.set_width(enterVertical, markerLineWidthInput)
line.set_xy1(estimateVertical, drawEndTime, markerY)
line.set_xy2(estimateVertical, drawEndTime, math.max(targetPrice, stopPrice))
line.set_color(estimateVertical, color.new(estimateColorInput, markerTransparencyInput))
line.set_style(estimateVertical, lineStyle(markerLineStyleInput))
line.set_width(estimateVertical, markerLineWidthInput)
line.set_xy1(trackerLine, drawStartTime, entryPriceInput)
line.set_xy2(trackerLine, trackerEndTime, trackerEndPrice)
line.set_color(trackerLine, showTrackerInput ? color.new(trackerColorInput, trackerTransparencyInput) : color.new(trackerColorInput, 100))
line.set_style(trackerLine, lineStyle(trackerLineStyleInput))
line.set_width(trackerLine, trackerLineWidthInput)
label.set_xy(targetLabel, drawEndTime, targetPrice)
label.set_text(targetLabel, showRightLabelsInput ? "TAKE PROFIT " + priceText(targetPrice) + " " + rText(targetR) + " " + pctText(targetPrice) : "")
label.set_xy(partialLabel, drawEndTime, partialPrice)
label.set_text(partialLabel, showRightLabelsInput and showPartialInput ? "PARTIAL PROFIT " + priceText(partialPrice) + " " + rText(partialR) + " " + pctText(partialPrice) + " " + str.tostring(partialExitPctInput, "#") + "% OFF" : "")
label.set_xy(trailLabel, drawEndTime, trailPrice)
label.set_text(trailLabel, showRightLabelsInput and showTrailInput ? "TRAILING STOP " + priceText(trailPrice) + " " + rText(trailR) + " " + pctText(trailPrice) : "")
label.set_xy(entryLabel, drawEndTime, entryPriceInput)
label.set_text(entryLabel, showRightLabelsInput ? "ENTER " + priceText(entryPriceInput) : "")
label.set_xy(stopLabel, drawEndTime, stopPrice)
label.set_text(stopLabel, showRightLabelsInput ? "STOP LOSS " + priceText(stopPrice) + " -1R " + pctText(stopPrice) : "")
label.set_style(targetLabel, labelStyle(labelStyleInput))
label.set_style(partialLabel, labelStyle(labelStyleInput))
label.set_style(trailLabel, labelStyle(labelStyleInput))
label.set_style(entryLabel, labelStyle(labelStyleInput))
label.set_style(stopLabel, labelStyle(labelStyleInput))
label.set_size(targetLabel, textSize(labelSizeInput))
label.set_size(partialLabel, textSize(labelSizeInput))
label.set_size(trailLabel, textSize(labelSizeInput))
label.set_size(entryLabel, textSize(labelSizeInput))
label.set_size(stopLabel, textSize(labelSizeInput))
label.set_color(targetLabel, color.new(targetLabelColorInput, labelTransparencyInput))
label.set_color(partialLabel, color.new(partialLabelColorInput, labelTransparencyInput))
label.set_color(trailLabel, color.new(trailLabelColorInput, labelTransparencyInput))
label.set_color(entryLabel, color.new(entryLabelColorInput, labelTransparencyInput))
label.set_color(stopLabel, color.new(stopLabelColorInput, labelTransparencyInput))
label.set_textcolor(targetLabel, targetLabelTextInput)
label.set_textcolor(partialLabel, partialLabelTextInput)
label.set_textcolor(trailLabel, trailLabelTextInput)
label.set_textcolor(entryLabel, entryLabelTextInput)
label.set_textcolor(stopLabel, stopLabelTextInput)
label.set_xy(enterLabel, drawStartTime, markerY)
label.set_text(enterLabel, entryModeInput == MODE_LIMIT and not limitFilled ? "ORDER" : "ENTER")
label.set_textcolor(enterLabel, markerColorInput)
label.set_xy(estimateLabel, drawEndTime, markerY)
label.set_textcolor(estimateLabel, estimateColorInput)
string status = not geometryValid ? "INVALID GEOMETRY" : not timeGeometryValid ? "INVALID ESTIMATE" : tradeClosed ? outcome : tradeActive ? (trailArmed ? "ACTIVE / TRAIL ARMED" : "ACTIVE") : entryModeInput == MODE_LIMIT ? "WAITING FOR LIMIT" : "PLAN"
color statusColor = not geometryValid or not timeGeometryValid or outcome == "STOP" ? LOSS_C : outcome == "TARGET" ? PROFIT_C : outcome == "AMBIGUOUS" ? PARTIAL_C : tradeActive ? PROFIT_C : ENTRY_C
var table statusTable = table.new(tablePosition(resolvedTablePosition), 2, 24, bgcolor = color.new(resolvedTableBg, resolvedTableTransparency),
frame_color = tableBorderInput, frame_width = 1, border_color = tableBorderInput, border_width = 1)
tableCell(int column, int row, string value, color valueColor) =>
table.cell(statusTable, column, row, value, text_color = valueColor, text_size = textSize(tableSizeInput),
text_halign = text.align_left, bgcolor = color.new(resolvedTableBg, resolvedTableTransparency))
tableRow(int row, string labelText, string valueText, color valueColor) =>
tableCell(0, row, labelText, tableLabelInput)
tableCell(1, row, valueText, valueColor)
if barstate.islast
table.clear(statusTable, 0, 0, 1, 23)
if displayModeInput == DISPLAY_AUDIT
bool fullTable = tableModeInput == TABLE_FULL
tableCell(0, 0, "POSITION " + directionText, ENTRY_C)
tableCell(1, 0, syminfo.ticker + " · " + timeframe.period, TEXT_C)
int row = 1
tableRow(row, "Status", status, statusColor)
row += 1
if fullTable
tableRow(row, "Mode", entryModeInput, TEXT_C)
row += 1
tableRow(row, "Alerts", alertsEnabledInput ? "ON" : "OFF", alertsEnabledInput ? PARTIAL_C : tableLabelInput)
row += 1
tableRow(row, "Levels", "E " + priceText(entryPriceInput) + " · S " + priceText(stopPrice), TEXT_C)
row += 1
tableRow(row, "Objectives", (showPartialInput ? "P " + priceText(partialPrice) + " · " : "") + "T " + priceText(targetPrice), PROFIT_C)
row += 1
if fullTable
tableRow(row, "Distances", "Stop " + signed(stopDistancePct, "#.00") + "% · " + (showPartialInput ? "Partial " + signed(partialDistancePct, "#.00") + "% · " : "") + "Target " + signed(targetDistancePct, "#.00") + "%", signedColor(targetDistancePct))
row += 1
tableRow(row, "Current", priceText(performancePrice) + " · " + signed(currentR, "#.00") + "R" +
" · " + signed(priceMovePct, "#.00") + "%" + (sizingEnabledInput ? " · P&L " + money(openPnl) + " (" + signed(openPnlPct, "#.00") + "%)" : ""), signedColor(currentR))
row += 1
if fullTable
tableRow(row, "Drawdown", signed(drawdownFromExtremePct, "#.00") + "% from favorable extreme " + (na(favorableExtremePrice) ? "—" : priceText(favorableExtremePrice)), signedColor(drawdownFromExtremePct))
row += 1
if showPartialInput or showTrailInput
tableRow(row, "Management", (showPartialInput ? (partialTouched ? "Partial touched" : "Partial open") : "") + (showPartialInput and showTrailInput ? " · " : "") + (showTrailInput ? "Trail " + (trailArmed ? "armed" : "waiting") : ""), partialTouched ? PARTIAL_C : TEXT_C)
row += 1
tableRow(row, "Clock", clockSummary + " · " + durationText(elapsedMilliseconds), timeUsedPct > 100.0 ? LOSS_C : TEXT_C)
row += 1
tableRow(row, "Schedule", overtimeBars > 0 ? barsText(overtimeBars) + " overtime" : barsText(remainingBars) + " remaining", overtimeBars > 0 ? LOSS_C : PARTIAL_C)
row += 1
if fullTable
tableRow(row, "Pace", signed(targetProgressPct, "#.0") + "% price / " + fmt(timeUsedPct, "#.0") + "% time · " + fmt(paceRatio, "#.00") + "x", signedColor(targetProgressPct))
row += 1
tableRow(row, "Required", (showPartialInput ? "Partial " + signed(partialRPerRemainingBar, "#.000") + " · " : "") + "Target " + signed(targetRPerRemainingBar, "#.000") + " R/bar", signedColor(targetRPerRemainingBar))
row += 1
tableRow(row, "Quantity", sizingEnabledInput ? fmt(roundedQuantity, "#.########") + " qty · " + fmt(positionUnits, "#.########") + " units" : "OFF", TEXT_C)
row += 1
if fullTable
tableRow(row, "Constraints", sizingEnabledInput ? "Risk " + fmt(riskQuantity, "#.####") + " · Leverage " + fmt(leverageQuantity, "#.####") : "OFF", TEXT_C)
row += 1
tableRow(row, "Risk", sizingEnabledInput ? fmt(estimatedInitialRisk, "#.##") + " / " + fmt(riskBudget, "#.##") + " budget" : "OFF", LOSS_C)
row += 1
tableRow(row, "Exposure", sizingEnabledInput ? fmt(notionalExposure, "#.##") + " · " + fmt(effectiveLeverage, "#.00") + "x effective" : "OFF", TEXT_C)
row += 1
if fullTable
tableRow(row, "Margin", sizingEnabledInput ? fmt(initialMargin, "#.##") + " · " + fmt(marginUsePct, "#.0") + "% capital" : "OFF", TEXT_C)
row += 1
tableRow(row, "Stop Balance", sizingEnabledInput ? fmt(stopBalance, "#.##") + " · P&L " + money(stopPnl) : "OFF", LOSS_C)
row += 1
if showPartialInput
tableRow(row, "Partial Balance", sizingEnabledInput ? fmt(partialBalance, "#.##") + " · realized " + money(partialPnl) : "OFF", PARTIAL_C)
row += 1
tableRow(row, "Target Balance", sizingEnabledInput ? fmt(targetBalance, "#.##") + " · P&L " + money(targetPnl) : "OFF", PROFIT_C)
row += 1
if halfLifeBarsInput > 0.0
tableRow(row, "Memory", fmt(modelRetainedPct, "#.0") + "% retained · " + fmt(ageHalfLives, "#.00") + " half-lives", ageHalfLives >= 2.0 ? PARTIAL_C : #9575CD)
row += 1
if fullTable
tableRow(row, "Settings", "End " + timeText(drawEndTime) + " · Half-life " + (halfLifeBarsInput > 0.0 ? fmt(halfLifeBarsInput, "#.0") : "OFF") + " · Leverage " + fmt(leverageInput, "#.0") + "x", tableLabelInput)
plot(directionValid ? (IS_LONG ? 1 : -1) : 0, "Direction (+1 Long / -1 Short / 0 Undefined)", color = ENTRY_C, display = display.data_window, editable = false)
plot(entryPriceInput, "Entry Price", color = ENTRY_C, display = display.data_window, editable = false)
plot(stopPrice, "Initial Stop", color = LOSS_C, display = display.data_window, editable = false)
plot(showPartialInput ? partialPrice : na, "Partial Profit", color = PARTIAL_C, display = display.data_window, editable = false)
plot(showTrailInput ? trailPrice : na, "Trailing Reference", color = TRAIL_C, display = display.data_window, editable = false)
plot(targetPrice, "Take Profit", color = PROFIT_C, display = display.data_window, editable = false)
plot(targetR, "Target R", color = PROFIT_C, display = display.data_window, editable = false)
plot(showPartialInput ? partialR : na, "Partial R", color = PARTIAL_C, display = display.data_window, editable = false)
plot(showPartialInput ? partialExitPctInput : na, "Partial Size %", color = PARTIAL_C, display = display.data_window, editable = false)
plot(showTrailInput ? trailR : na, "Trail R", color = TRAIL_C, display = display.data_window, editable = false)
plot(tradeActive ? 1 : 0, "Trade Active (1/0)", color = ENTRY_C, display = display.data_window, editable = false)
plot(showPartialInput ? (partialTouched ? 1 : 0) : na, "Partial Touched (1/0)", color = PARTIAL_C, display = display.data_window, editable = false)
plot(showTrailInput ? (trailArmed ? 1 : 0) : na, "Trail Armed (1/0)", color = TRAIL_C, display = display.data_window, editable = false)
plot(tradeClosed ? 1 : 0, "Trade Closed (1/0)", color = LOSS_C, display = display.data_window, editable = false)
plot(roundedQuantity, "Estimated Quantity", color = ENTRY_C, display = display.data_window, editable = false)
plot(positionUnits, "Estimated Units", color = ENTRY_C, display = display.data_window, editable = false)
plot(riskQuantity, "Risk-Constrained Quantity", color = ENTRY_C, display = display.data_window, editable = false)
plot(leverageQuantity, "Leverage-Constrained Quantity", color = ENTRY_C, display = display.data_window, editable = false)
plot(estimatedInitialRisk, "Estimated Initial Risk", color = ENTRY_C, display = display.data_window, editable = false)
plot(notionalExposure, "Notional Exposure", color = ENTRY_C, display = display.data_window, editable = false)
plot(effectiveLeverage, "Effective Leverage", color = ENTRY_C, display = display.data_window, editable = false)
plot(initialMargin, "Estimated Initial Margin", color = ENTRY_C, display = display.data_window, editable = false)
plot(marginUsePct, "Margin Use % of Capital", color = ENTRY_C, display = display.data_window, editable = false)
plot(openPnl, "Open or Final P&L", color = currentR >= 0.0 ? PROFIT_C : LOSS_C, display = display.data_window, editable = false)
plot(openPnlPct, "Open or Final P&L % of Capital", color = currentR >= 0.0 ? PROFIT_C : LOSS_C, display = display.data_window, editable = false)
plot(priceMovePct, "Price Move % from Entry", color = currentR >= 0.0 ? PROFIT_C : LOSS_C, display = display.data_window, editable = false)
plot(drawdownFromExtremePct, "Drawdown % from Favorable Extreme", color = drawdownFromExtremePct >= 0.0 ? PROFIT_C : LOSS_C, display = display.data_window, editable = false)
plot(stopDistancePct, "Distance % from Stop", color = LOSS_C, display = display.data_window, editable = false)
plot(partialDistancePct, "Distance % to Partial", color = PARTIAL_C, display = display.data_window, editable = false)
plot(targetDistancePct, "Distance % to Target", color = PROFIT_C, display = display.data_window, editable = false)
plot(currentR, "Current or Final R", color = currentR >= 0.0 ? PROFIT_C : LOSS_C, display = display.data_window, editable = false)
plot(elapsedBars, "Elapsed Bars", color = ENTRY_C, display = display.data_window, editable = false)
plot(remainingBars, "Remaining Planned Bars", color = PARTIAL_C, display = display.data_window, editable = false)
plot(overtimeBars, "Overtime Bars", color = LOSS_C, display = display.data_window, editable = false)
plot(timeUsedPct, "Planned Time Used %", color = PARTIAL_C, display = display.data_window, editable = false)
plot(currentRPerBar, "Current R per Elapsed Bar", color = ENTRY_C, display = display.data_window, editable = false)
plot(partialRPerRemainingBar, "Required R per Bar to Partial", color = PARTIAL_C, display = display.data_window, editable = false)
plot(targetRPerRemainingBar, "Required R per Bar to Target", color = PROFIT_C, display = display.data_window, editable = false)
plot(targetProgressPct, "Target Progress %", color = PROFIT_C, display = display.data_window, editable = false)
plot(paceRatio, "Price Progress / Time Progress", color = PARTIAL_C, display = display.data_window, editable = false)
plot(ageHalfLives, "Age in Empirical Half-Lives", color = #9575CD, display = display.data_window, editable = false)
plot(modelRetainedPct, "Model Retained %", color = #9575CD, display = display.data_window, editable = false)