本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ══════════════════════════════════════════════════════════
// 1. VERSION, DECLARATION & CHANGELOG
// ══════════════════════════════════════════════════════════
// Author: Willy | WillyAlgoTrader
// Version: 1.3.1
indicator("Manual Wedge Setup [WillyAlgoTrader]", shorttitle = "MWedge", overlay = true, max_lines_count = 20, max_labels_count = 20, max_polylines_count = 1)
max_bars_back(time, 2)
// ══════════════════════════════════════════════════════════
// 2. CONSTANTS
// ══════════════════════════════════════════════════════════
const string INDICATOR_VERSION = "1.3.1"
const int LABEL_OFFSET_BARS = 1
const int N = 4
const int HISTORY = 10000
const string GRP_MAIN = "⚙ Main Settings"
const string GRP_VISUAL = "🎨 Visual Settings"
const string GRP_FILTER = "🔍 Filters"
const string GRP_RISK = "🛡 Risk Management"
const string GRP_DASH = "📊 Dashboard"
const string GRP_ALERT = "🔔 Alerts"
const string GRP_COLORS = "🎨 Colors"
const string GRP_ADV = "🔧 Advanced"
// ══════════════════════════════════════════════════════════
// 3. INPUTS
// ══════════════════════════════════════════════════════════
int t1Input = input.time(0, "Candle 1", confirm = true, group = GRP_MAIN, tooltip = "Manually select all FOUR anchor candles on the chart. The script does not find these candles automatically. Select the first anchor candle. Use four distinct candles within 9999 bars. Anchors are sorted by time.")
int t2Input = input.time(0, "Candle 2", confirm = true, group = GRP_MAIN, tooltip = "Select a second distinct candle. H is the absolute price difference between the first two assigned anchors in time order.")
int t3Input = input.time(0, "Candle 3", confirm = true, group = GRP_MAIN, tooltip = "Select a third distinct candle. The indicator assigns its High or Low to a boundary automatically.")
int t4Input = input.time(0, "Candle 4", confirm = true, group = GRP_MAIN, tooltip = "Select a fourth distinct candle. A breakout must close after the last anchor and before the apex.")
string themeInput = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = GRP_VISUAL, tooltip = "Auto detects the chart background. Select Dark or Light manually for custom chart backgrounds.")
bool showWedgeInput = input.bool(true, "Show Wedge Boundaries", group = GRP_VISUAL, tooltip = "Show the fitted upper and lower boundaries. Disable to focus on trade levels; calculations continue.")
bool showFillInput = input.bool(true, "Show Wedge Fill", group = GRP_VISUAL, tooltip = "Show a translucent green fill for falling wedges and red for rising wedges. Requires Show Wedge Boundaries; transparency adapts to the theme.")
bool showApexInput = input.bool(true, "Extend Boundaries to Apex", group = GRP_VISUAL, tooltip = "Extend both boundaries to their intersection using dashed lines. Requires Show Wedge Boundaries. Future timestamps are estimated on session charts.")
bool showParallelInput = input.bool(false, "Show Mirrored Upper Parallel", group = GRP_VISUAL, tooltip = "Reflect a parallel through the earliest lower contact across the upper boundary. Optional; disabled by default.")
bool showLabelsInput = input.bool(true, "Show Anchor Labels", group = GRP_VISUAL, tooltip = "Show point numbers and assigned High/Low contacts. Anchor numbers follow chronological order.")
bool showSignalLabelsInput = input.bool(true, "Show Entry Signal Marker", group = GRP_VISUAL, tooltip = "Show BUY below or SELL above the confirmed breakout candle. Independent of level-label visibility.")
bool showTradeLabelsInput = input.bool(true, "Show Price-Level Labels", group = GRP_VISUAL, tooltip = "Show solid-background Entry/SL/TP price labels one bar after the common line endpoint. Confirmed target touches are marked with a checkmark.")
bool showTargetInput = input.bool(true, "Show Target Zone", group = GRP_VISUAL, tooltip = "Show the transparent yellow 90–100% H zone after breakout. TP3 is the near 90% boundary.")
bool showVwapInput = input.bool(true, "Show Extreme-Anchored VWAP", group = GRP_VISUAL, tooltip = "Anchor at the lowest assigned Low of a falling wedge or the highest assigned High of a rising wedge. The average ends at the same confirmed TP3, SL, or BE-stop exit as the trade; monitoring begins after entry.")
bool showWatermarkInput = input.bool(true, "Show Watermark", group = GRP_VISUAL, tooltip = "Show a subtle WillyAlgoTrader watermark at the bottom center. Disable for a cleaner chart.")
string signalSizeInput = input.string("Small", "Signal Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_VISUAL, tooltip = "Size of BUY/SELL markers. Small is recommended; larger sizes improve visibility on high-resolution displays.")
string levelSizeInput = input.string("Small", "Price Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_VISUAL, tooltip = "Size of anchor, apex, entry, SL, TP, and VWAP labels. Small keeps the chart compact.")
string modeInput = input.string("Any", "Contact Order", options = ["Alternating", "Any"], group = GRP_FILTER, tooltip = "Any allows all valid High/Low assignments. Alternating requires upper/lower contacts to alternate. Recommended: Any.")
float tolerancePctInput = input.float(5.0, "Tolerance (% of Selected Candle Range)", minval = 0.0, maxval = 25.0, step = 0.5, group = GRP_FILTER, tooltip = "Allowed fit error relative to the selected High–Low range. Higher values accept looser formations. Default: 5%.")
bool strictWedgeInput = input.bool(true, "Require Same-Direction Boundaries", group = GRP_FILTER, tooltip = "Enable for rising/falling wedges. Disable to allow converging triangles. Parallel and diverging boundaries remain invalid.")
bool showStopInput = input.bool(true, "Show Stop Line", group = GRP_RISK, tooltip = "Show the fixed selected-anchor stop from entry until the first SL or near-target touch. Falling: below lowest Low. Rising: below highest High.")
int stopOffsetTicksInput = input.int(2, "Stop Offset (Ticks)", minval = 1, maxval = 10000, step = 1, group = GRP_RISK, tooltip = "Offset below the selected stop anchor in minimum price ticks. Larger values move the stop lower. Default: 2 ticks.")
bool showTradeLevelsInput = input.bool(true, "Show Entry and Three Targets", group = GRP_RISK, tooltip = "Show entry and TP1/TP2/TP3 levels with a common SL/TP3 endpoint. TP3 coincides with the near target-zone boundary.")
float tp1PctInput = input.float(100.0 / 3.0, "TP1 (% of Entry-to-TP3 Distance)", minval = 0.1, maxval = 99.9, step = 0.1, group = GRP_RISK, tooltip = "Position TP1 along the entry-to-TP3 path. Higher percentages move it farther from entry. Must be below TP2. Default: one third.")
float tp2PctInput = input.float(200.0 / 3.0, "TP2 (% of Entry-to-TP3 Distance)", minval = 0.1, maxval = 99.9, step = 0.1, group = GRP_RISK, tooltip = "Position TP2 along the entry-to-TP3 path. Must be above TP1 and below 100%. Default: two thirds.")
float marginAmountInput = input.float(100.0, "Margin (Quote Currency)", minval = 0.01, maxval = 1000000000.0, step = 10.0, group = GRP_RISK, tooltip = "Initial margin in the chart's quote currency. Notional = margin × leverage. Higher margin scales all cash P&L estimates. Default: 100.")
float leverageInput = input.float(5.0, "Leverage", minval = 1.0, maxval = 1000.0, step = 0.5, group = GRP_RISK, tooltip = "Multiplier applied once to position notional. Higher leverage scales estimated profit and loss. No liquidation model. Default: 5×.")
float tp1ClosePctInput = input.float(33.0, "TP1 Close (% of Initial Position)", minval = 0.0, maxval = 100.0, step = 1.0, group = GRP_RISK, tooltip = "Share of the initial position closed at TP1. Higher values realize more profit earlier. TP1 + TP2 must remain below 100%. Default: 33%.")
float tp2ClosePctInput = input.float(33.0, "TP2 Close (% of Initial Position)", minval = 0.0, maxval = 100.0, step = 1.0, group = GRP_RISK, tooltip = "Share of the initial position closed at TP2. TP3 closes the remainder: 100% minus TP1 and TP2 shares. Default: 33%, leaving 34% for TP3.")
string entryLineStyleInput = input.string("Dotted", "Entry Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Entry is a reference level. Dotted is recommended to keep it visually subtle.")
string slLineStyleInput = input.string("Solid", "SL Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Style of the stop line. Solid with width 2 emphasizes the risk boundary.")
string tpLineStyleInput = input.string("Dashed", "TP Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_RISK, tooltip = "Style for TP1/TP2/TP3. Confirmed touches turn the trade line solid teal and add a checkmark; the yellow target zone remains visible.")
bool showPctOnLabelsInput = input.bool(true, "Show % Distance on Labels", group = GRP_RISK, tooltip = "Append signed price change from entry to SL/TP labels, matching the Reactive Trail System layout. Disable for price-only labels.")
bool moveToBEInput = input.bool(true, "Break-Even After TP1", group = GRP_RISK, tooltip = "After the first confirmed TP1 touch, move the remaining position's stop to entry. The BE stop is active from the next candle. TP1/TP2 only close their configured fractions; only TP3, SL, or BE-stop finish the trade. New TP touches have optimistic priority over SL on the same candle.")
bool showDashInput = input.bool(true, "Show Dashboard", group = GRP_DASH, tooltip = "Show the sectioned information panel. Disable to use chart drawings only.")
string dashPositionInput = input.string("Top Right", "Dashboard Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = GRP_DASH, tooltip = "Choose the corner for the dashboard. Top Right is recommended; use another corner if it covers candles.")
string dashSizeInput = input.string("Small", "Dashboard Font Size", options = ["Small", "Normal", "Large", "Huge"], group = GRP_DASH, tooltip = "Size of all data rows. Small is the minimum readable size; choose Normal, Large, or Huge for larger displays.")
bool dashMarketInput = input.bool(true, " Market", group = GRP_DASH, tooltip = "Show expected wedge bias (falling: Bullish; rising: Bearish), confirmed breakout state, chart timeframe, and assignment confidence.")
bool dashGeometryInput = input.bool(true, " Formation", group = GRP_DASH, tooltip = "Show geometry diagnostics, target zone, and VWAP status. Assignment confidence is not a win probability.")
bool dashTradeInput = input.bool(true, " Trade Levels", group = GRP_DASH, tooltip = "Show entry, fixed SL, three TP levels, SL distance %, and RR to TP3. Before entry the section collapses to a waiting row.")
bool dashMathInput = input.bool(true, " Position Plan", group = GRP_DASH, tooltip = "Show margin, leverage, theoretical size, partial-exit P&L, and SL scenarios. These are estimates, not execution statistics.")
bool showAlertsInput = input.bool(true, "Enable Event Alerts", group = GRP_ALERT, tooltip = "Allow confirmed BUY/SELL and level-event alerts. Create a TradingView alert using Any alert() function call. No alerts are created automatically.")
bool webhookInput = input.bool(false, "Webhook JSON Format", group = GRP_ALERT, tooltip = "Format event messages as JSON for integrations. Default: readable text. All events on a candle are bundled into one message.")
bool alertEntryInput = input.bool(true, "Alert on Entry", group = GRP_ALERT, tooltip = "Notify at the confirmed breakout close with entry, SL, TP1–3, and RR. Historical drawings never produce alerts.")
bool alertExitInput = input.bool(true, "Alert on SL / TP / BE Events", group = GRP_ALERT, tooltip = "Notify on confirmed TP touches, BE activation, and TP3/SL/BE-stop exits. The OHLC management model gives new TP touches priority over SL on the same candle.")
color upperColorInput = input.color(#F59E0B, "Upper Boundary", group = GRP_COLORS, tooltip = "Color of the upper boundary and mirrored parallel. Orange is recommended to distinguish it from the lower boundary.")
color lowerColorInput = input.color(#00ACC1, "Lower Boundary", group = GRP_COLORS, tooltip = "Color of the lower boundary. Teal is recommended for contrast with the upper boundary.")
color targetColorInput = input.color(#FBC02D, "Target Boundary", group = GRP_COLORS, tooltip = "Color of the 90–100% H zone boundaries. The translucent zone fill remains yellow.")
color vwapColorInput = input.color(#AB47BC, "VWAP", group = GRP_COLORS, tooltip = "Color of the anchored volume-weighted or unweighted average. Purple distinguishes it from trade levels.")
color bullColorInput = input.color(#00E676, "BUY Marker", inline = "signal", group = GRP_COLORS, tooltip = "Background color of BUY markers. Text stays dark for contrast on the default bright-green background.")
color bearColorInput = input.color(#FF5252, "SELL Marker", inline = "signal", group = GRP_COLORS, tooltip = "Background color of SELL markers. Text stays white on the default red background.")
string vwapVolumeModeInput = input.string("Auto", "VWAP Weighting / Forex", options = ["Auto", "Volume Only", "Unweighted"], group = GRP_ADV, tooltip = "Auto falls back to an unweighted average if volumes are missing. Volume Only hides unavailable VWAP; Unweighted always uses equal candle weights.")
if barstate.isfirst
if tp1PctInput >= tp2PctInput
runtime.error("TP1 distance percentage must be less than TP2. Adjust Risk Management settings.")
if tp1ClosePctInput + tp2ClosePctInput >= 100.0
runtime.error("TP1 + TP2 closing shares must total less than 100%; TP3 closes the remainder.")
// ══════════════════════════════════════════════════════════
// 4. THEME DETECTION & COLORS
// ══════════════════════════════════════════════════════════
bool isDark = themeInput == "Dark" or (themeInput == "Auto" and color.r(chart.bg_color) < 128)
color TEXT_COLOR = isDark ? #E0E0E0 : #1A1A1A
color TEXT_MUTED = isDark ? #9E9E9E : #757575
color BULL_TEXT = isDark ? #00E676 : #00A152
color BEAR_TEXT = isDark ? #FF5252 : #D32F2F
color NEUTRAL_TEXT = isDark ? #FFEB3B : #F57F17
color TABLE_BG = color.new(isDark ? #131722 : #FFFFFF, 5)
color TABLE_BORDER = isDark ? #2A2E39 : #D0D0D0
color TABLE_ROW_ALT = isDark ? #1C2030 : #F0F4F8
color HEADER_BG = isDark ? #0D47A1 : #1565C0
color HEADER_BG_BULL = #0F6E56
color HEADER_BG_BEAR = #A32D2D
color HEADER_TEXT = #FFFFFF
color LINE_SUBTLE = isDark ? #9E9E9E : #616161
color SL_COLOR = isDark ? #E57373 : #B71C1C
color TP1_COLOR = isDark ? color.new(#66BB6A, 30) : color.new(#388E3C, 30)
color TP2_COLOR = isDark ? color.new(#66BB6A, 40) : color.new(#388E3C, 40)
color TP3_COLOR = isDark ? #66BB6A : #388E3C
color ENTRY_COLOR = isDark ? #5C8AAE : #34495E
color TP_LABEL_COLOR = isDark ? #66BB6A : #388E3C
color TP_HIT_COLOR = isDark ? #4DB6AC : #00695C
color BE_COLOR = isDark ? #FFA726 : #E65100
color LABEL_TEXT = isDark ? #1A1A1A : #FFFFFF
color BULL_LABEL_TEXT = #004D25
color BEAR_LABEL_TEXT = #FFFFFF
color WM_COLOR = color.new(isDark ? #FFFFFF : #000000, 80)
int FILL_TRANSP = isDark ? 88 : 82
string dashPosition = dashPositionInput == "Top Left" ? position.top_left : dashPositionInput == "Bottom Left" ? position.bottom_left : dashPositionInput == "Bottom Right" ? position.bottom_right : position.top_right
string signalSize = signalSizeInput == "Huge" ? size.huge : signalSizeInput == "Tiny" ? size.tiny : signalSizeInput == "Large" ? size.large : signalSizeInput == "Normal" ? size.normal : size.small
string levelSize = levelSizeInput == "Huge" ? size.huge : levelSizeInput == "Tiny" ? size.tiny : levelSizeInput == "Large" ? size.large : levelSizeInput == "Normal" ? size.normal : size.small
string dashSize = dashSizeInput == "Huge" ? size.huge : dashSizeInput == "Large" ? size.large : dashSizeInput == "Normal" ? size.normal : size.small
string dashSizeSub = dashSizeInput == "Huge" ? size.large : dashSizeInput == "Large" ? size.normal : dashSizeInput == "Normal" ? size.small : size.tiny
// ══════════════════════════════════════════════════════════
// 5. STATE & BOUNDED HISTORY
// ══════════════════════════════════════════════════════════
var array<int> targets = array.from(t1Input, t2Input, t3Input, t4Input)
var array<int> bars = array.new_int(N, na)
var array<float> highs = array.new_float(N, na)
var array<float> lows = array.new_float(N, na)
var array<bool> closed = array.new_bool(N, false)
var array<line> drawnLines = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var linefill shading = na
var linefill targetShading = na
var polyline vwapCurve = na
var table panel = na
var int panelRows = 0
var table watermark = table.new(position.bottom_center, 1, 1, border_width = 0)
// Bounded history supports a selected formation up to 9999 bars back.
var array<int> historyTime = array.new_int(HISTORY, na)
var array<float> historyClose = array.new_float(HISTORY, na)
var array<float> historyHigh = array.new_float(HISTORY, na)
var array<float> historyLow = array.new_float(HISTORY, na)
var array<float> historyVolume = array.new_float(HISTORY, na)
array.set(historyTime, bar_index % HISTORY, time)
array.set(historyClose, bar_index % HISTORY, close)
array.set(historyHigh, bar_index % HISTORY, high)
array.set(historyLow, bar_index % HISTORY, low)
array.set(historyVolume, bar_index % HISTORY, volume)
// Evaluate the one-bar reference on every bar, not just inside last-bar drawing.
int barDuration = math.max(1, nz(time_close - time, nz(time - time[1], 60000)))
// Fractional apex positions need timestamps. Future time is an estimate on
// session-based/irregular charts; historical positions use actual bar times.
// ══════════════════════════════════════════════════════════
// 6. FUNCTIONS
// ══════════════════════════════════════════════════════════
barTime(float position) =>
int left = int(math.floor(position))
float fraction = position - left
int result = na
if left >= bar_index
result := time + int(math.round((position - bar_index) * barDuration))
else
int a = array.get(historyTime, left % HISTORY)
int b = array.get(historyTime, (left + 1) % HISTORY)
result := a + int(math.round(fraction * (b - a)))
result
// Exact bar open, or a timestamp inside a time-based candle. Never snap gaps.
for i = 0 to N - 1
int target = array.get(targets, i)
bool selected = target > 0 and (time == target or (not na(time_close) and time <= target and target < time_close))
if selected
array.set(bars, i, bar_index)
array.set(highs, i, high)
array.set(lows, i, low)
array.set(closed, i, barstate.isconfirmed)
isUpper(int mask, int i) =>
int(math.floor(mask / math.pow(2, i))) % 2 == 1
// Linear-contract estimates. Fractions always refer to the INITIAL position.
tradeMath(float margin, float lev, float entry, float pv, int dir, float stop, float tOne, float tTwo, float tThree, float shareOne, float shareTwo) =>
float qty = margin * lev / (entry * pv)
float qOne = qty * shareOne / 100.0
float qTwo = qty * shareTwo / 100.0
float qThree = qty - qOne - qTwo
float pOne = dir * (tOne - entry) * qOne * pv
float pTwo = dir * (tTwo - entry) * qTwo * pv
float pThree = dir * (tThree - entry) * qThree * pv
float stopUnit = dir * (stop - entry) * pv
float stopBefore = stopUnit * qty
float stopAfterOne = pOne + stopUnit * (qty - qOne)
float stopAfterTwo = pOne + pTwo + stopUnit * qThree
float riskDistance = dir * (entry - stop)
float rewardDistance = dir * (tThree - entry)
[qty, qOne, qTwo, qThree, pOne, pTwo, pThree, stopBefore, stopAfterOne, stopAfterTwo, riskDistance, rewardDistance]
money(float value) =>
na(value) ? "—" : (value > 0 ? "+" : "") + str.tostring(value, "0.00") + " " + syminfo.currency
levelLabel(string title, float price, float entry) =>
float changePct = not na(entry) and entry > 0 ? (price - entry) / entry * 100.0 : na
title + " " + str.tostring(price, format.mintick) + (not showPctOnLabelsInput or na(changePct) ? "" : " (" + (changePct >= 0 ? "+" : "") + str.tostring(changePct, "#.##") + "%)")
// Called only for confirmed bars strictly AFTER entry, with valid ordered targets.
// Capture the effective stop at bar start; a new BE stop cannot fire on this bar.
tradeStep(int dir, float entry, float stop, float tp1, float tp2, float tp3, bool useBE, bool wasBE, bool wasTP1, bool wasTP2, bool wasTP3, float h, float l) =>
float effectiveStop = wasBE ? entry : stop
bool rawTP1 = dir == 1 ? h >= tp1 : l <= tp1
bool rawTP2 = dir == 1 ? h >= tp2 : l <= tp2
bool rawTP3 = dir == 1 ? h >= tp3 : l <= tp3
bool rawSL = dir == 1 ? l <= effectiveStop : h >= effectiveStop
bool firstTP1 = rawTP1 and not wasTP1
bool firstTP2 = rawTP2 and not wasTP2
bool firstTP3 = rawTP3 and not wasTP3
bool nextTP1 = wasTP1 or rawTP1
bool nextTP2 = wasTP2 or rawTP2
bool nextTP3 = wasTP3 or rawTP3
bool moveBE = useBE and firstTP1 and not wasBE and not rawTP3
bool nextBE = wasBE or moveBE
bool closeSL = rawSL and not firstTP1 and not firstTP2
int stopExitKind = wasBE ? 3 : 2
int exitKind = rawTP3 ? 1 : closeSL ? stopExitKind : 0
[nextBE, nextTP1, nextTP2, nextTP3, firstTP1, firstTP2, firstTP3, moveBE, exitKind, effectiveStop]
lineStyle(string value) =>
value == "Dashed" ? line.style_dashed : value == "Dotted" ? line.style_dotted : line.style_solid
jsonNumber(float value) =>
na(value) ? "null" : str.tostring(value, "0.########")
jsonEscape(string value) =>
str.replace_all(str.replace_all(value, "\\", "\\\\"), "\"", "\\\"")
panelRow(array<string> keys, array<string> values, array<color> colors, array<string> hints, string key, string value, color textColor, string hint) =>
array.push(keys, key)
array.push(values, value)
array.push(colors, textColor)
array.push(hints, hint)
// Fit in bar coordinates (not elapsed wall-clock time), relative to the first bar.
fit(array<int> xs, array<float> hs, array<float> ls, int mask, bool upper) =>
float sx = 0.0
float sy = 0.0
float sxx = 0.0
float sxy = 0.0
int count = 0
int origin = array.get(xs, 0)
for i = 0 to N - 1
if isUpper(mask, i) == upper
float x = array.get(xs, i) - origin
float y = upper ? array.get(hs, i) : array.get(ls, i)
sx += x
sy += y
sxx += x * x
sxy += x * y
count += 1
float denominator = count * sxx - sx * sx
float slope = count >= 2 and denominator > 0 ? (count * sxy - sx * sy) / denominator : na
float intercept = not na(slope) ? (sy - slope * sx) / count : na
[slope, intercept]
// ══════════════════════════════════════════════════════════
// 7. FORMATION, SIGNALS, RISK PLAN & DRAWINGS
// ══════════════════════════════════════════════════════════
// Rebuild only on the last bar; delete every previous object first.
if barstate.islast
if not na(vwapCurve)
polyline.delete(vwapCurve)
vwapCurve := na
if not na(targetShading)
linefill.delete(targetShading)
targetShading := na
if not na(shading)
linefill.delete(shading)
shading := na
while array.size(drawnLines) > 0
line.delete(array.pop(drawnLines))
while array.size(drawnLabels) > 0
label.delete(array.pop(drawnLabels))
string status = "Select " + str.tostring(N) + " distinct candles"
string detail = "Drag each time marker to a different candle"
string note = "Linear scale · selected candles only"
string targetText = "Target: waiting for formation"
string stopText = "SL: waiting for formation"
string entryText = "Entry: waiting for confirmed breakout"
string tp1Text = "TP1: —"
string tp2Text = "TP2: —"
string vwapText = showVwapInput ? "VWAP: waiting for formation" : "VWAP: disabled"
string marginText = "Margin: " + str.tostring(marginAmountInput, "#.##") + " " + syminfo.currency
string leverageText = "Leverage: " + str.tostring(leverageInput, "#.##") + "×"
string notionalText = "Notional: —"
string quantityText = "Quantity: —"
string rrText = "RR: —"
string tp1CloseText = "TP1 Close: —"
string tp1ProfitText = "TP1 Profit: —"
string tp2CloseText = "TP2 Close: —"
string tp2ProfitText = "TP2 Profit: —"
string stopLossText = "SL Before TP1: —"
string netStopText = "TP1 + TP2 then SL: —"
string stopAfterOneText = "TP1 then SL: —"
string tp3CloseText = "TP3 Close: —"
string tp3ProfitText = "TP3 Profit (90% H): —"
string totalProfitText = "Total TP Profit: —"
string mathNote = "Linear-contract plan · excludes fees/funding\nTheoretical quantity; not rounded to broker lots"
string trendText = "Neutral"
string signalText = "Wait"
string confidenceText = "Not evaluated"
string tp3LevelText = "TP3: —"
string riskPercentText = "—"
bool hasEntry = false
int formationBias = 0
int displayDirection = 0
bool displayTp1Reached = false
bool displayTp2Reached = false
bool displayTp3Reached = false
string dashEntryText = "—"
string dashSLText = "—"
string dashTP1Text = "—"
string dashTP2Text = "—"
string dashTP3Text = "—"
string modeledResultText = "—"
bool displayBE = false
string dashRRText = "—"
color dashRRColor = TEXT_MUTED
color dashRiskColor = TEXT_MUTED
array<string> pendingEvents = array.new_string()
string pendingAlertDetails = ""
string pendingAlertFields = ""
color statusColor = NEUTRAL_TEXT
bool ready = true
bool allClosed = true
for i = 0 to N - 1
ready := ready and not na(array.get(bars, i))
allClosed := allClosed and array.get(closed, i)
if ready
array<int> order = array.sort_indices(bars, order.ascending)
array<int> xs = array.new_int()
array<float> hs = array.new_float()
array<float> ls = array.new_float()
bool unique = true
for i = 0 to N - 1
int j = array.get(order, i)
array.push(xs, array.get(bars, j))
array.push(hs, array.get(highs, j))
array.push(ls, array.get(lows, j))
if i > 0
unique := unique and array.get(xs, i) != array.get(xs, i - 1)
int first = array.get(xs, 0)
int last = array.get(xs, N - 1)
if not unique
status := "Duplicate candle selection"
detail := "Each anchor must belong to a different candle"
else if first < bar_index - 9999
status := "Selection is too far back"
detail := "The first candle must be within the last 9999 bars"
else
float span = last - first
float scale = math.max(array.max(hs) - array.min(ls), syminfo.mintick)
float tolerance = math.max(scale * tolerancePctInput / 100.0, syminfo.mintick * 0.5)
float best = na
float runnerUp = na
int bestMask = na
float bestU = na
float bestL = na
float bestUI = na
float bestLI = na
float bestError = na
int candidates = 0
// At most 64 assignments. Each side needs at least two contacts.
for mask = 0 to int(math.pow(2, N)) - 1
bool alternating = true
for i = 1 to N - 1
alternating := alternating and isUpper(mask, i) != isUpper(mask, i - 1)
if modeInput == "Any" or alternating
[u, ui] = fit(xs, hs, ls, mask, true)
[l, li] = fit(xs, hs, ls, mask, false)
float startWidth = ui - li
float endWidth = startWidth + (u - l) * span
bool geometry = not na(u) and not na(l) and startWidth > 0 and endWidth > 0 and (l - u) * span > syminfo.mintick * 0.5
geometry := geometry and (not strictWedgeInput or (u > 0 and l > 0) or (u < 0 and l < 0))
if geometry
float squaredError = 0.0
float maxError = 0.0
float outside = 0.0
for i = 0 to N - 1
float x = array.get(xs, i) - first
float top = ui + u * x
float bottom = li + l * x
float residual = isUpper(mask, i) ? array.get(hs, i) - top : array.get(ls, i) - bottom
squaredError += residual * residual
maxError := math.max(maxError, math.abs(residual))
outside := math.max(outside, math.max(array.get(hs, i) - top, bottom - array.get(ls, i)))
if maxError <= tolerance and outside <= tolerance
float score = math.sqrt(squaredError / N) / scale + outside / scale
candidates += 1
if na(best) or score < best
runnerUp := best
best := score
bestMask := mask
bestU := u
bestL := l
bestUI := ui
bestLI := li
bestError := maxError
else if na(runnerUp) or score < runnerUp
runnerUp := score
if na(bestMask)
status := "No valid wedge found"
detail := "Check candles, contact order, and tolerance"
else
float apexX = (bestUI - bestLI) / (bestL - bestU)
float apexPrice = bestUI + bestU * apexX
float lastUpper = bestUI + bestU * span
float lastLower = bestLI + bestL * span
int firstTime = array.get(historyTime, first % HISTORY)
int lastTime = array.get(historyTime, last % HISTORY)
line topLine = line.new(firstTime, bestUI, lastTime, lastUpper, xloc = xloc.bar_time, color = upperColorInput, width = 2)
line bottomLine = line.new(firstTime, bestLI, lastTime, lastLower, xloc = xloc.bar_time, color = lowerColorInput, width = 2)
array.push(drawnLines, topLine)
array.push(drawnLines, bottomLine)
if not showWedgeInput
line.set_color(topLine, color.new(upperColorInput, 100))
line.set_color(bottomLine, color.new(lowerColorInput, 100))
if showWedgeInput and showFillInput
shading := linefill.new(topLine, bottomLine, color.new(bestU < 0 and bestL < 0 ? bullColorInput : bestU > 0 and bestL > 0 ? bearColorInput : ENTRY_COLOR, FILL_TRANSP))
if showWedgeInput and showApexInput
int apexTime = barTime(first + apexX)
array.push(drawnLines, line.new(lastTime, lastUpper, apexTime, apexPrice, xloc = xloc.bar_time, color = upperColorInput, style = line.style_dashed))
array.push(drawnLines, line.new(lastTime, lastLower, apexTime, apexPrice, xloc = xloc.bar_time, color = lowerColorInput, style = line.style_dashed))
array.push(drawnLabels, label.new(apexTime, apexPrice, "Apex", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(LINE_SUBTLE, 85), textcolor = TEXT_COLOR, size = levelSize))
// Target distance uses anchors 1 and 2 in chronological order,
// with the same assigned High/Low prices as the on-chart labels.
float anchor1 = isUpper(bestMask, 0) ? array.get(hs, 0) : array.get(ls, 0)
float anchor2 = isUpper(bestMask, 1) ? array.get(hs, 1) : array.get(ls, 1)
float height = math.abs(anchor2 - anchor1)
// Pick the earliest LOWER contact, regardless of its point number.
// Measure the upper boundary at that contact's actual bar, then
// reflect the parallel through its Low across the upper boundary.
// Every valid 4-point candidate has exactly two lower contacts.
float parallelOffset = na
for i = 0 to N - 1
if not isUpper(bestMask, i)
float channelX = array.get(xs, i) - first
parallelOffset := bestUI + bestU * channelX - array.get(ls, i)
break
if showParallelInput
array.push(drawnLines, line.new(firstTime, bestUI + parallelOffset, lastTime, lastUpper + parallelOffset, xloc = xloc.bar_time, color = upperColorInput, style = line.style_dashed, width = 1))
if showApexInput
int parallelEndTime = barTime(first + apexX)
array.push(drawnLines, line.new(lastTime, lastUpper + parallelOffset, parallelEndTime, apexPrice + parallelOffset, xloc = xloc.bar_time, color = upperColorInput, style = line.style_dashed, width = 1))
int breakoutBar = na
int direction = 0
float breakoutLevel = na
float entryPrice = na
float targetPrice = na
float targetNear = na
int confirmedLast = barstate.isconfirmed ? bar_index : bar_index - 1
// The first close crossing a boundary AFTER point 4 and BEFORE
// the apex fixes direction and target. No intrabar confirmation.
if allClosed and confirmedLast > last
for b = last + 1 to confirmedLast
float x = b - first
float c = array.get(historyClose, b % HISTORY)
if na(breakoutBar) and x < apexX
float previous = array.get(historyClose, (b - 1) % HISTORY)
float uNow = bestUI + bestU * x
float lNow = bestLI + bestL * x
bool breakUp = c > uNow and previous <= bestUI + bestU * (x - 1)
bool breakDown = c < lNow and previous >= bestLI + bestL * (x - 1)
if breakUp or breakDown
breakoutBar := b
direction := breakUp ? 1 : -1
breakoutLevel := breakUp ? uNow : lNow
entryPrice := c
targetPrice := math.round_to_mintick(breakoutLevel + direction * height)
targetNear := math.round_to_mintick(breakoutLevel + direction * height * 0.9)
// Classify the formation by BOTH boundary slopes, independently
// of the breakout direction used for targets.
bool risingWedge = bestU > 0 and bestL > 0
bool fallingWedge = bestU < 0 and bestL < 0
string shape = risingWedge ? "Rising Wedge" : fallingWedge ? "Falling Wedge" : "Converging Triangle"
trendText := risingWedge ? "Bearish · Rising Wedge" : fallingWedge ? "Bullish · Falling Wedge" : "Neutral · Triangle"
formationBias := fallingWedge ? 1 : risingWedge ? -1 : 0
// Stop follows formation direction, using only assigned anchors:
// falling -> below the lowest Low; rising -> below the highest High.
float stopAnchor = na
int stopAnchorBar = na
float vwapAnchorPrice = na
int vwapAnchorBar = na
for i = 0 to N - 1
bool upper = isUpper(bestMask, i)
if (fallingWedge and not upper) or (risingWedge and upper)
float candidate = upper ? array.get(hs, i) : array.get(ls, i)
bool replaceAnchor = na(stopAnchor) or (fallingWedge ? candidate < stopAnchor : candidate > stopAnchor)
if replaceAnchor
stopAnchor := candidate
stopAnchorBar := array.get(xs, i)
// VWAP shares the extreme anchor, without the stop offset.
bool replaceVwapAnchor = na(vwapAnchorPrice) or (fallingWedge ? candidate < vwapAnchorPrice : candidate > vwapAnchorPrice)
if replaceVwapAnchor
vwapAnchorPrice := candidate
vwapAnchorBar := array.get(xs, i)
float stopPrice = na
if not na(stopAnchor)
stopPrice := math.round_to_mintick(stopAnchor - stopOffsetTicksInput * syminfo.mintick)
float remainingDistance = targetNear - entryPrice
float tp1Price = math.round_to_mintick(entryPrice + remainingDistance * tp1PctInput / 100.0)
float tp2Price = math.round_to_mintick(entryPrice + remainingDistance * tp2PctInput / 100.0)
bool orderedTargets = direction * (tp1Price - entryPrice) > 0 and direction * (tp2Price - tp1Price) > 0 and direction * (targetNear - tp2Price) > 0
bool validTradePlan = not na(breakoutBar) and orderedTargets and not na(stopPrice) and direction * (entryPrice - stopPrice) > 0
// Only confirmed TP3, initial SL, or an already-active BE stop can finish a trade.
int tradeEndBar = bar_index
int tradeExitKind = 0
float tradeExitPrice = na
string tradeFinishReason = ""
bool beActive = false
int beActivationBar = na
bool tp1Reached = false
bool tp2Reached = false
bool tp3Reached = false
int firstTP1Bar = na
int firstTP2Bar = na
int firstTP3Bar = na
if validTradePlan and confirmedLast > breakoutBar
for b = breakoutBar + 1 to confirmedLast
float h = array.get(historyHigh, b % HISTORY)
float l = array.get(historyLow, b % HISTORY)
[nextBE, nextTP1, nextTP2, nextTP3, firstTP1, firstTP2, firstTP3, moveBE, exitKind, effectiveStop] = tradeStep(direction, entryPrice, stopPrice, tp1Price, tp2Price, targetNear, moveToBEInput, beActive, tp1Reached, tp2Reached, tp3Reached, h, l)
beActive := nextBE
tp1Reached := nextTP1
tp2Reached := nextTP2
tp3Reached := nextTP3
if firstTP1
firstTP1Bar := b
if firstTP2
firstTP2Bar := b
if firstTP3
firstTP3Bar := b
if moveBE
beActivationBar := b
if exitKind != 0
tradeEndBar := b
tradeExitKind := exitKind
tradeExitPrice := exitKind == 1 ? targetNear : effectiveStop
tradeFinishReason := exitKind == 1 ? "Target reached" : exitKind == 3 ? "BE stop reached" : "SL reached"
break
displayTp1Reached := tp1Reached
displayTp2Reached := tp2Reached
displayTp3Reached := tp3Reached
displayBE := beActive
int tradeEndTime = not na(breakoutBar) ? array.get(historyTime, tradeEndBar % HISTORY) : na
int tradeLabelTime = not na(breakoutBar) ? barTime(tradeEndBar + LABEL_OFFSET_BARS) : na
targetText := "Height H = " + str.tostring(height, format.mintick) + " · waiting for breakout close"
if not allClosed
targetText := "Target: wait for all four anchors to close"
else if na(breakoutBar) and confirmedLast - first >= apexX
targetText := "Apex passed without confirmed breakout · H = " + str.tostring(height, format.mintick)
else if not na(breakoutBar)
hasEntry := validTradePlan
displayDirection := direction
signalText := validTradePlan ? (direction == 1 ? "Buy" : "Sell") + (tradeFinishReason == "" ? " · active" : " · " + tradeFinishReason) : "Breakout · invalid SL or target plan"
tp3LevelText := "TP3: " + str.tostring(targetNear, format.mintick) + " · 90% H"
string targetRange = str.tostring(math.min(targetNear, targetPrice), format.mintick) + " — " + str.tostring(math.max(targetNear, targetPrice), format.mintick)
targetText := (direction == 1 ? "Target ↑ " : "Target ↓ ") + targetRange + " · 90–100% H" + (tradeFinishReason == "" ? " · active" : " · " + tradeFinishReason)
// Entry is the confirming close, never a retroactive fill at
// the boundary. Intermediate targets divide the remaining
// price distance to T3, the near 90% H boundary.
entryText := "Entry " + str.tostring(entryPrice, format.mintick) + " · breakout close"
int levelsStartTime = array.get(historyTime, breakoutBar % HISTORY)
if showTradeLevelsInput and validTradePlan
array.push(drawnLines, line.new(levelsStartTime, entryPrice, tradeEndTime, entryPrice, xloc = xloc.bar_time, color = ENTRY_COLOR, style = lineStyle(entryLineStyleInput), width = 1))
if showSignalLabelsInput and validTradePlan
array.push(drawnLabels, label.new(levelsStartTime, entryPrice, (direction == 1 ? "▲ BUY " : "▼ SELL ") + str.tostring(entryPrice, format.mintick), xloc = xloc.bar_time, yloc = direction == 1 ? yloc.belowbar : yloc.abovebar, style = direction == 1 ? label.style_label_up : label.style_label_down, color = direction == 1 ? bullColorInput : bearColorInput, textcolor = direction == 1 ? BULL_LABEL_TEXT : BEAR_LABEL_TEXT, size = signalSize, tooltip = "Confirmed breakout close\nSL: " + (na(stopPrice) ? "—" : str.tostring(stopPrice, format.mintick)) + " | TP3: " + str.tostring(targetNear, format.mintick)))
if showTradeLevelsInput and showTradeLabelsInput and validTradePlan
array.push(drawnLabels, label.new(tradeLabelTime, entryPrice, "ENTRY " + str.tostring(entryPrice, format.mintick) + (beActive ? " → SL (BE)" : ""), xloc = xloc.bar_time, style = label.style_label_left, color = beActive ? BE_COLOR : ENTRY_COLOR, textcolor = LABEL_TEXT, size = levelSize))
dashEntryText := (direction == 1 ? "Long @ " : "Short @ ") + str.tostring(entryPrice, format.mintick)
dashSLText := beActive ? "BE @ " + str.tostring(entryPrice, format.mintick) : na(stopPrice) ? "—" : str.tostring(stopPrice, format.mintick)
dashTP1Text := orderedTargets ? (displayTp1Reached ? "✓ " : "") + str.tostring(tp1Price, format.mintick) : "Invalid target spacing"
dashTP2Text := orderedTargets ? (displayTp2Reached ? "✓ " : "") + str.tostring(tp2Price, format.mintick) : "—"
dashTP3Text := (displayTp3Reached ? "✓ " : "") + str.tostring(targetNear, format.mintick)
// Financial plan is independent of whether drawing toggles are enabled.
bool validShares = tp1ClosePctInput + tp2ClosePctInput < 100.0
bool validSize = entryPrice > 0 and syminfo.pointvalue > 0
float tp3ClosePct = 100.0 - tp1ClosePctInput - tp2ClosePctInput
notionalText := "Notional: " + str.tostring(marginAmountInput * leverageInput, "0.00") + " " + syminfo.currency
if validSize
[qty, qOne, qTwo, qThree, pOne, pTwo, pThree, stopBefore, stopAfterOne, stopAfterTwo, riskDistance, rewardDistance] = tradeMath(marginAmountInput, leverageInput, entryPrice, syminfo.pointvalue, direction, stopPrice, tp1Price, tp2Price, targetNear, tp1ClosePctInput, tp2ClosePctInput)
quantityText := "Quantity: " + str.tostring(qty, "0.########") + " units/contracts (theoretical)"
bool validStop = not na(riskDistance) and riskDistance > 0
riskPercentText := beActive ? "0.00% (BE)" : validStop ? str.tostring(riskDistance / entryPrice * 100.0, "0.00") + "%" : "Invalid SL side"
stopLossText := validStop ? "SL Before TP1: " + money(stopBefore) : "SL: no level on the risk side of entry"
if validStop and rewardDistance > 0
rrText := "RR SL : TP3 = 1 : " + str.tostring(rewardDistance / riskDistance, "0.00")
dashRRText := str.tostring(rewardDistance / riskDistance, "#.##") + "R"
dashRRColor := rewardDistance / riskDistance >= 1.5 ? BULL_TEXT : rewardDistance / riskDistance >= 1.0 ? NEUTRAL_TEXT : BEAR_TEXT
dashRiskColor := beActive ? BE_COLOR : riskDistance / entryPrice * 100.0 > 3.0 ? BEAR_TEXT : riskDistance / entryPrice * 100.0 > 1.0 ? NEUTRAL_TEXT : BULL_TEXT
else
rrText := "RR: check the SL side and TP3 level"
if validShares
tp1CloseText := "TP1 Close: " + str.tostring(tp1ClosePctInput, "0.##") + "% · " + str.tostring(qOne, "0.########") + " units/contracts"
tp2CloseText := "TP2 Close: " + str.tostring(tp2ClosePctInput, "0.##") + "% · " + str.tostring(qTwo, "0.########") + " units/contracts"
tp3CloseText := "TP3 Close: " + str.tostring(tp3ClosePct, "0.##") + "% · " + str.tostring(qThree, "0.########") + " units/contracts"
if orderedTargets
tp1ProfitText := "TP1 Profit: " + money(pOne)
tp2ProfitText := "TP2 Profit: " + money(pTwo)
tp3ProfitText := "TP3 " + str.tostring(targetNear, format.mintick) + " (90% H) · profit " + money(pThree)
totalProfitText := "Total TP Profit: " + money(pOne + pTwo + pThree)
if validStop
stopAfterOneText := (moveToBEInput ? "TP1 then BE: " : "TP1 then SL: ") + money(moveToBEInput ? pOne : stopAfterOne)
netStopText := (moveToBEInput ? "TP1 + TP2 then BE: " : "TP1 + TP2 then SL: ") + money(moveToBEInput ? pOne + pTwo : stopAfterTwo)
totalProfitText += " · Plan RR " + str.tostring((pOne + pTwo + pThree) / -stopBefore, "0.00")
if tradeExitKind != 0
float realizedTP = (tp1Reached ? pOne : 0.0) + (tp2Reached ? pTwo : 0.0)
float remainingQty = qty - (tp1Reached ? qOne : 0.0) - (tp2Reached ? qTwo : 0.0)
modeledResultText := money(realizedTP + direction * (tradeExitPrice - entryPrice) * remainingQty * syminfo.pointvalue) + " · " + tradeFinishReason
else if validTradePlan
modeledResultText := "Active · realized " + money((tp1Reached ? pOne : 0.0) + (tp2Reached ? pTwo : 0.0))
else
tp3CloseText := "Invalid shares: TP1 + TP2 must total less than 100%"
else
quantityText := "Quantity: positive price and point value required"
if direction * remainingDistance <= 0
tp1Text := "Targets: TP3 was already passed at entry"
else if tp1PctInput >= tp2PctInput
tp1Text := "Targets: TP1 percentage must be below TP2"
else if not orderedTargets
tp1Text := "Targets: insufficient price ticks between levels"
else
tp1Text := "TP1 " + str.tostring(tp1Price, format.mintick) + " · " + str.tostring(tp1PctInput, "#.##") + "% of path"
tp2Text := "TP2 " + str.tostring(tp2Price, format.mintick) + " · " + str.tostring(tp2PctInput, "#.##") + "% of path"
if showTradeLevelsInput and validTradePlan
array.push(drawnLines, line.new(levelsStartTime, tp1Price, tradeEndTime, tp1Price, xloc = xloc.bar_time, color = displayTp1Reached ? TP_HIT_COLOR : TP1_COLOR, style = displayTp1Reached ? line.style_solid : lineStyle(tpLineStyleInput), width = 1))
array.push(drawnLines, line.new(levelsStartTime, tp2Price, tradeEndTime, tp2Price, xloc = xloc.bar_time, color = displayTp2Reached ? TP_HIT_COLOR : TP2_COLOR, style = displayTp2Reached ? line.style_solid : lineStyle(tpLineStyleInput), width = 1))
if showTradeLabelsInput
array.push(drawnLabels, label.new(tradeLabelTime, tp1Price, levelLabel(displayTp1Reached ? "TP1 ✓" : "TP1", tp1Price, entryPrice), xloc = xloc.bar_time, style = label.style_label_left, color = displayTp1Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, textcolor = LABEL_TEXT, size = levelSize))
if showTradeLabelsInput
array.push(drawnLabels, label.new(tradeLabelTime, tp2Price, levelLabel(displayTp2Reached ? "TP2 ✓" : "TP2", tp2Price, entryPrice), xloc = xloc.bar_time, style = label.style_label_left, color = displayTp2Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, textcolor = LABEL_TEXT, size = levelSize))
if showTradeLevelsInput and validTradePlan
array.push(drawnLines, line.new(levelsStartTime, targetNear, tradeEndTime, targetNear, xloc = xloc.bar_time, color = displayTp3Reached ? TP_HIT_COLOR : TP3_COLOR, style = displayTp3Reached ? line.style_solid : lineStyle(tpLineStyleInput), width = 1))
if showTradeLabelsInput
array.push(drawnLabels, label.new(tradeLabelTime, targetNear, levelLabel(displayTp3Reached ? "TP3 ✓" : "TP3", targetNear, entryPrice), xloc = xloc.bar_time, style = label.style_label_left, color = displayTp3Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, textcolor = LABEL_TEXT, size = levelSize))
// Confirmed event snapshots; historical reconstruction never sends alerts.
if showAlertsInput and validTradePlan and barstate.isrealtime and barstate.isconfirmed
if alertEntryInput and breakoutBar == bar_index
array.push(pendingEvents, direction == 1 ? "BUY" : "SELL")
if alertExitInput and orderedTargets and bar_index > breakoutBar
if beActivationBar == bar_index
array.push(pendingEvents, "BREAK_EVEN")
if firstTP1Bar == bar_index
array.push(pendingEvents, "TP1_TOUCH")
if firstTP2Bar == bar_index
array.push(pendingEvents, "TP2_TOUCH")
if alertExitInput and tradeEndBar == bar_index and tradeFinishReason != ""
string exitEvent = tradeExitKind == 3 ? "BE_STOP_OUT" : tradeExitKind == 2 ? "SL_TOUCH" : "TP3_TOUCH"
array.push(pendingEvents, exitEvent)
float alertRisk = direction * (entryPrice - stopPrice)
float alertReward = direction * (targetNear - entryPrice)
float alertRR = alertRisk > 0 and alertReward > 0 ? alertReward / alertRisk : na
pendingAlertDetails := " | Entry: " + str.tostring(entryPrice, format.mintick) + " | SL: " + str.tostring(beActive ? entryPrice : stopPrice, format.mintick) + " | TP1: " + str.tostring(tp1Price, format.mintick) + " | TP2: " + str.tostring(tp2Price, format.mintick) + " | TP3: " + str.tostring(targetNear, format.mintick) + " | Initial RR: " + (na(alertRR) ? "—" : str.tostring(alertRR, "0.00"))
pendingAlertFields := ',"side":"' + (direction == 1 ? "buy" : "sell") + '","entry":' + jsonNumber(entryPrice) + ',"sl":' + jsonNumber(beActive ? entryPrice : stopPrice) + ',"initial_sl":' + jsonNumber(stopPrice) + ',"tp1":' + jsonNumber(tp1Price) + ',"tp2":' + jsonNumber(tp2Price) + ',"tp3":' + jsonNumber(targetNear) + ',"rr":' + jsonNumber(alertRR)
if showTargetInput and validTradePlan
int breakoutTime = array.get(historyTime, breakoutBar % HISTORY)
array.push(drawnLines, line.new(breakoutTime, breakoutLevel, breakoutTime, targetPrice, xloc = xloc.bar_time, color = targetColorInput, style = line.style_dotted))
line targetFarLine = line.new(breakoutTime, targetPrice, tradeEndTime, targetPrice, xloc = xloc.bar_time, color = targetColorInput, width = 1)
line targetNearLine = line.new(breakoutTime, targetNear, tradeEndTime, targetNear, xloc = xloc.bar_time, color = targetColorInput, width = 1)
array.push(drawnLines, targetFarLine)
array.push(drawnLines, targetNearLine)
if showTradeLevelsInput and validTradePlan
line.set_color(targetNearLine, color.new(targetColorInput, 100))
targetShading := linefill.new(targetFarLine, targetNearLine, color.new(color.yellow, FILL_TRANSP))
if showTradeLabelsInput
array.push(drawnLabels, label.new(tradeEndTime, (targetNear + targetPrice) / 2.0, "Target 90–100% H\n" + targetRange, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.yellow, 80), textcolor = TEXT_COLOR, size = levelSize))
if showLabelsInput
for i = 0 to N - 1
bool upper = isUpper(bestMask, i)
float price = upper ? array.get(hs, i) : array.get(ls, i)
label point = label.new(array.get(historyTime, array.get(xs, i) % HISTORY), price, str.tostring(i + 1) + (upper ? " H" : " L"), xloc = xloc.bar_time, style = upper ? label.style_label_down : label.style_label_up, color = color.new(upper ? upperColorInput : lowerColorInput, 85), textcolor = TEXT_COLOR, size = levelSize)
array.push(drawnLabels, point)
bool ambiguous = not na(runnerUp) and runnerUp - best <= 0.01
confidenceText := ambiguous ? "Ambiguous assignment" : allClosed ? "Valid assignment" : "Provisional anchors"
stopText := "SL: no anchor rule for triangles"
if not na(stopPrice)
stopText := "SL " + str.tostring(stopPrice, format.mintick) + (fallingWedge ? " · below the lowest Low" : " · below the highest High")
if na(breakoutBar)
stopText += " · waiting for entry"
else
stopText += tradeFinishReason == "" ? " · active" : " · " + tradeFinishReason
if beActive
stopText := "SL BE @ " + str.tostring(entryPrice, format.mintick) + " · " + (tradeFinishReason == "" ? "active from candle after TP1" : tradeFinishReason)
if showStopInput and validTradePlan
int stopStartTime = array.get(historyTime, breakoutBar % HISTORY)
int originalStopEndTime = beActive ? array.get(historyTime, beActivationBar % HISTORY) : tradeEndTime
color originalStopColor = beActive ? color.new(SL_COLOR, 70) : SL_COLOR
array.push(drawnLines, line.new(stopStartTime, stopPrice, originalStopEndTime, stopPrice, xloc = xloc.bar_time, color = originalStopColor, style = lineStyle(slLineStyleInput), width = 2))
if showTradeLabelsInput
int originalLabelTime = beActive ? barTime(beActivationBar + LABEL_OFFSET_BARS) : tradeLabelTime
array.push(drawnLabels, label.new(originalLabelTime, stopPrice, levelLabel(beActive ? "INITIAL SL" : "SL", stopPrice, entryPrice), xloc = xloc.bar_time, style = label.style_label_left, color = originalStopColor, textcolor = beActive ? TEXT_MUTED : LABEL_TEXT, size = levelSize))
if beActive and beActivationBar < tradeEndBar
int beStartTime = barTime(beActivationBar + 1)
array.push(drawnLines, line.new(beStartTime, entryPrice, tradeEndTime, entryPrice, xloc = xloc.bar_time, color = BE_COLOR, style = lineStyle(slLineStyleInput), width = 2))
if beActive and showTradeLabelsInput and not showTradeLevelsInput
array.push(drawnLabels, label.new(tradeLabelTime, entryPrice, "SL (BE) " + str.tostring(entryPrice, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = BE_COLOR, textcolor = LABEL_TEXT, size = levelSize))
if showVwapInput and na(vwapAnchorBar)
vwapText := "VWAP: no anchor rule for triangles"
if showVwapInput and not na(vwapAnchorBar)
array<chart.point> vwapPoints = array.new<chart.point>()
array<chart.point> averagePoints = array.new<chart.point>()
float cumulativePV = 0.0
float cumulativeVolume = 0.0
float cumulativePrice = 0.0
int averageCount = 0
float lastAverage = na
int averageEndTime = na
float lastVwap = na
int lastVwapTime = na
bool missingVolume = false
string finishReason = ""
// Low-source VWAP for falling wedges; High-source for rising.
// With positive anchor volume, its first value is exactly the
// chosen extreme. Include the final touch candle as before.
for b = vwapAnchorBar to bar_index
int slot = b % HISTORY
float v = array.get(historyVolume, slot)
float h = array.get(historyHigh, slot)
float l = array.get(historyLow, slot)
float c = array.get(historyClose, slot)
float sourcePrice = fallingWedge ? l : h
cumulativePrice += sourcePrice
averageCount += 1
lastAverage := cumulativePrice / averageCount
averageEndTime := array.get(historyTime, slot)
array.push(averagePoints, chart.point.from_time(averageEndTime, lastAverage))
missingVolume := missingVolume or na(v) or v < 0
if not na(v) and v > 0
cumulativePV += sourcePrice * v
cumulativeVolume += v
if cumulativeVolume > 0
lastVwap := cumulativePV / cumulativeVolume
lastVwapTime := array.get(historyTime, slot)
array.push(vwapPoints, chart.point.from_time(lastVwapTime, lastVwap))
// The average consumes the same confirmed exit snapshot as all trade lines.
if validTradePlan and tradeExitKind != 0 and b >= tradeEndBar
finishReason := tradeFinishReason
break
// Choose ONE weighting scheme for the whole displayed span;
// never mix actual volumes with fabricated per-bar volumes.
bool noUsableVolume = missingVolume or cumulativeVolume <= 0
bool useAverage = vwapVolumeModeInput == "Unweighted" or (vwapVolumeModeInput == "Auto" and noUsableVolume)
if not useAverage and missingVolume
vwapText := "VWAP: missing volumes; calculation unavailable"
else if not useAverage and cumulativeVolume <= 0
vwapText := "VWAP: no positive volume"
else
array<chart.point> displayedPoints = useAverage ? averagePoints : vwapPoints
float displayedPrice = useAverage ? lastAverage : lastVwap
int displayedTime = useAverage ? averageEndTime : lastVwapTime
string averageName = useAverage ? "Unweighted Average" : "VWAP"
if array.size(displayedPoints) >= 2
vwapCurve := polyline.new(displayedPoints, curved = false, closed = false, xloc = xloc.bar_time, line_color = vwapColorInput, line_width = 2)
string vwapState = finishReason != "" ? "finished: " + finishReason : not validTradePlan ? "waiting for valid entry" : "active"
vwapText := averageName + (fallingWedge ? " Low " : " High ") + str.tostring(displayedPrice, format.mintick) + " · " + vwapState
array.push(drawnLabels, label.new(displayedTime, displayedPrice, averageName, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(vwapColorInput, 80), textcolor = TEXT_COLOR, size = levelSize))
status := shape + (ambiguous ? " · ambiguous" : "")
detail := "Fit Error: " + str.tostring(bestError, format.mintick) + " · candidates: " + str.tostring(candidates)
note := (allClosed ? "" : "Unclosed anchor: geometry is provisional!\n") + "Linear scale · only selected candles checked"
statusColor := ambiguous or not allClosed ? NEUTRAL_TEXT : ENTRY_COLOR
else
detail := "Anchor outside loaded history or not available yet"
// ══════════════════════════════════════════════════════
// 8. SECTIONED DASHBOARD
// ══════════════════════════════════════════════════════
array<string> rowKeys = array.new_string()
array<string> rowValues = array.new_string()
array<color> rowColors = array.new<color>()
array<string> rowHints = array.new_string()
if showDashInput
string trendWord = formationBias == 1 ? "Bullish" : formationBias == -1 ? "Bearish" : "Neutral"
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Header", "◆ MWedge · " + trendWord, HEADER_TEXT, "Four manually selected candles; automatic High/Low assignments.")
if dashMarketInput
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Market", "", HEADER_TEXT, "Expected wedge bias is independent of the confirmed breakout direction.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Trend", trendWord, formationBias == 1 ? BULL_TEXT : formationBias == -1 ? BEAR_TEXT : TEXT_MUTED, "Falling wedge: Bullish bias. Rising wedge: Bearish bias. This is the expected pattern direction; BUY/SELL requires a confirmed breakout.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Signal", signalText, displayDirection == 1 ? BULL_TEXT : displayDirection == -1 ? BEAR_TEXT : TEXT_MUTED, "Entry is the first confirmed boundary-crossing close after candle 4 and before the apex.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Timeframe", timeframe.period, TEXT_COLOR, "All calculations use the chart timeframe; no higher-timeframe data.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Assignment", confidenceText, statusColor, "Valid/ambiguous describes the High/Low assignment, not trade strength or win probability.")
if dashGeometryInput
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Formation", "", HEADER_TEXT, "Fit diagnostics for the selected candles.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Status", status, statusColor, "Choose four distinct candles within 9999 bars. Unclosed anchors produce provisional geometry.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Fit", detail, TEXT_MUTED, "Maximum anchor residual and number of valid assignments. Only selected candles are checked.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Scale", note, TEXT_MUTED, "The wedge uses linear price geometry. Live anchor data can change before the anchor candle closes.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Target", targetText, NEUTRAL_TEXT, "90–100% H measured from the broken boundary. H is the price difference between assigned points 1 and 2.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "VWAP", vwapText, TEXT_COLOR, "Extreme-anchored average. Without usable volume, Auto uses equal candle weights for the entire span.")
if dashTradeInput
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Trade", "", HEADER_TEXT, "Fixed levels for one manually selected formation.")
if not hasEntry
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Waiting", "Flat · waiting for confirmed breakout", TEXT_MUTED, "No trade plan is active until a breakout candle closes.")
else
panelRow(rowKeys, rowValues, rowColors, rowHints, "Entry", dashEntryText, displayDirection == 1 ? BULL_TEXT : BEAR_TEXT, "Assumed entry is the breakout candle close; actual fill prices may differ.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "SL", dashSLText, displayBE ? BE_COLOR : SL_COLOR, "Initial stop uses selected anchors. BE @ marks the entry-level stop after TP1, effective from the following candle. Only TP3/SL/BE-stop finish the trade.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP1", dashTP1Text, displayTp1Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, "First configurable fraction of the entry-to-TP3 price path.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP2", dashTP2Text, displayTp2Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, "Second configurable fraction of the entry-to-TP3 price path.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP3", dashTP3Text, displayTp3Reached ? TP_HIT_COLOR : TP_LABEL_COLOR, "Nearest target-zone boundary at 90% H. The final position remainder closes here in the plan.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "R:R", dashRRText, dashRRColor, "Initial SL : TP3 = 1 : reward/risk. This planned ratio stays fixed after BE; SL Dist shows the current stop distance.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "SL Dist", riskPercentText, dashRiskColor, "Risk-side price distance from entry to SL divided by entry price.")
if dashMathInput
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Position Plan", "", HEADER_TEXT, "Linear-contract estimates, not execution statistics.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Margin / Leverage", marginText + " · " + leverageText, TEXT_COLOR, "Margin is in quote currency. Notional equals margin multiplied once by leverage.")
if not hasEntry
panelRow(rowKeys, rowValues, rowColors, rowHints, "Plan", "Waiting for confirmed entry", TEXT_MUTED, "Sizing and P&L require a known entry price.")
else
panelRow(rowKeys, rowValues, rowColors, rowHints, "Position", notionalText + " · " + quantityText, TEXT_COLOR, "Quantity = notional / (entry × point value). Theoretical units/contracts; not rounded to broker lot sizes.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP1 Plan", tp1CloseText + " · " + tp1ProfitText, BULL_TEXT, "Close share of the initial position × directional TP1 price move × point value.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP2 Plan", tp2CloseText + " · " + tp2ProfitText, BULL_TEXT, "TP2's share is measured against initial size, not the remainder after TP1.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "TP3 Plan", tp3CloseText + " · " + tp3ProfitText, BULL_TEXT, "TP3 closes 100% minus TP1 and TP2 shares. Default remaining share: 34%.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "All Targets", totalProfitText, BULL_TEXT, "Sum of all three partial profits. Plan RR uses this sum divided by the initial full-position SL risk.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "SL Before TP1", stopLossText, BEAR_TEXT, "Full initial position stops out before any take-profit exit.")
panelRow(rowKeys, rowValues, rowColors, rowHints, moveToBEInput ? "TP1 then BE" : "TP1 then SL", stopAfterOneText, NEUTRAL_TEXT, "With BE enabled, the remainder exits at entry and this scenario retains only TP1 profit. Excludes fees.")
panelRow(rowKeys, rowValues, rowColors, rowHints, moveToBEInput ? "TP1 + TP2 then BE" : "TP1 + TP2 then SL", netStopText, NEUTRAL_TEXT, "With BE enabled, the remainder exits at entry and this scenario retains TP1 + TP2 profits. Excludes fees.")
if hasEntry
panelRow(rowKeys, rowValues, rowColors, rowHints, "Modeled Result", modeledResultText, TEXT_COLOR, "Gross result from the confirmed OHLC timeline and configured partial closes. Optimistic TP priority; not broker execution data.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "Model", mathNote, TEXT_MUTED, "Excludes fees, funding, swaps, slippage, liquidation, and inverse-contract settlement. OHLC sequence is unknown; new TP touches take optimistic priority over SL. BE cannot stop out on its activation candle.")
panelRow(rowKeys, rowValues, rowColors, rowHints, "#Version", "MWedge · v" + INDICATOR_VERSION, TEXT_MUTED, "Reactive Trail System 2.2.1 presentation adapted for the manual formation planner.")
int requiredRows = array.size(rowKeys)
// RTS dynamic-height pattern: rebuild explicitly to clear old merged cells.
if not na(panel)
table.delete(panel)
panel := table.new(dashPosition, 2, requiredRows, bgcolor = TABLE_BG, border_color = TABLE_BORDER, border_width = 1, frame_color = TABLE_BORDER, frame_width = 1)
panelRows := requiredRows
int r = 0
bool zeb = false
color headerBg = formationBias == 1 ? HEADER_BG_BULL : formationBias == -1 ? HEADER_BG_BEAR : HEADER_BG
for i = 0 to requiredRows - 1
string key = array.get(rowKeys, i)
string value = array.get(rowValues, i)
bool merged = str.startswith(key, "#")
bool header = key == "#Header"
bool footer = key == "#Version"
bool waiting = key == "#Waiting"
color rowBg = header ? headerBg : footer ? TABLE_BG : merged and not waiting ? TABLE_ROW_ALT : zeb ? TABLE_ROW_ALT : TABLE_BG
string prefix = key + ": "
if str.startswith(value, prefix)
value := str.substring(value, str.length(prefix))
else if str.startswith(value, key + " ")
value := str.substring(value, str.length(key) + 1)
if merged
string heading = header or footer or waiting ? value : "— " + str.substring(key, 1) + " —"
table.cell(panel, 0, r, heading, text_color = header ? HEADER_TEXT : TEXT_MUTED, bgcolor = rowBg, text_size = header or waiting ? dashSize : dashSizeSub, text_halign = text.align_center, tooltip = array.get(rowHints, i))
table.merge_cells(panel, 0, r, 1, r)
else
table.cell(panel, 0, r, key, text_color = TEXT_MUTED, bgcolor = rowBg, text_size = dashSize, tooltip = array.get(rowHints, i))
table.cell(panel, 1, r, value, text_color = array.get(rowColors, i), bgcolor = rowBg, text_size = dashSize, tooltip = array.get(rowHints, i))
zeb := not zeb
r += 1
else if not na(panel)
table.delete(panel)
panel := na
panelRows := 0
// ══════════════════════════════════════════════════════
// 9. WATERMARK
// ══════════════════════════════════════════════════════
table.cell(watermark, 0, 0, showWatermarkInput ? "WillyAlgoTrader" : "", text_color = WM_COLOR, text_size = size.normal, bgcolor = color.new(TABLE_BG, 100))
// ══════════════════════════════════════════════════════
// 10. ALERTS — one bundled message per confirmed candle
// ══════════════════════════════════════════════════════
if showAlertsInput and barstate.isrealtime and barstate.isconfirmed and array.size(pendingEvents) > 0
string events = array.join(pendingEvents, ", ")
string eventJson = '["' + array.join(pendingEvents, '","') + '"]'
string textMessage = events + " | " + syminfo.tickerid + " | TF: " + timeframe.period + " | Price: " + str.tostring(close, format.mintick) + " | Time: " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) + pendingAlertDetails
string jsonMessage = '{"events":' + eventJson + ',"ticker":"' + jsonEscape(syminfo.tickerid) + '","timeframe":"' + jsonEscape(timeframe.period) + '","time":' + str.tostring(time) + ',"price":' + jsonNumber(close) + pendingAlertFields + '}'
alert(webhookInput ? jsonMessage : textMessage, alert.freq_once_per_bar_close)