MoTrade - Funded Line

MoTradeSystems · study · 574 行 · 点赞 9 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ============================================================================
//  MoTrade - Funded Line
//  Version 1.1.1
//
//  © 2026 MoTradeSystems · Moritz Engerer.
//  Open source on TradingView.
//  This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ · © 2026 MoTradeSystems
// ----------------------------------------------------------------------------
//  TradingView publication metadata
//  Publisher: MoTradeSystems
//  Version:   1.1.1
//  Category:  Portfolio management, Educational
//  Tags:      prop firm, drawdown, daily loss, risk management, funded account, futures
// ============================================================================
// @description MoTrade Funded Line: draws the loss rules of a funded or
//  evaluation account as horizontal lines on the chart and shows how many
//  points and dollars remain until the daily loss limit or the drawdown limit
//  is reached. Limits come from a program preset (quoted from each firm's
//  public rules, with a retrieval date) or from your own manual inputs. It is a
//  measuring tool, not a signal: no entries, no exits, no forecast. All state
//  is computed from completed bars only. Clarity, not certainty.
//
//  Changelog
//  v1.1.1 — two changes to v1.1.0. No input removed or renamed; two inputs are appended at the end of
//   the input list (saved settings keep their positions). Every other default is unchanged.
//   1. Long and short colors. With Direction = Both the long side and the short side differ by color
//      as well as by position and by the prefix "Long" or "Short". Two new inputs, Long color and Short
//      color, default to the two candle tones of the house palette: Brand Blue #2768C8 (rising candles)
//      for the long side and Muted Blue-Grey #9AB3D0 (falling candles) for the short side. No red and no
//      green. Both sides use their color in the limit lines, in the distance label (label background)
//      and in the table (cell behind the row name of the Long and Short buffer rows). In Both the two
//      lines of one side share the side color and are told apart by line style: the drawdown line keeps
//      Line style, the daily loss line is dotted (dashed when Line style is already Dotted). Long and
//      Short alone, Daily loss line color and Drawdown line color are unchanged. Alerts are unchanged:
//      five conditions, in Both they watch the nearer side.
//   2. Presets rebuilt from the rule database export of 2026-11-07 (futures programs, VERIFIED fields
//      with a quote only). The values and retrieval dates of all seven programs are the same as in
//      v1.1.0; the generated block carries the new source hash. FundedNext Futures Legacy 100K is no
//      longer in the export (the firm stopped selling it on 2026-10-11). The option stays in the list
//      with its old values and its old retrieval date (2026-09-01) so that saved settings keep working.
//  v1.1.0 — three changes after the first review (Mo, 01.11.2026). No input removed or renamed; the
//   input Direction gains one option and one input is appended at the end of the input list (saved
//   settings keep their positions). The presets are unchanged.
//   1. Lot size. The rules table has its own row "Lot size" in Full and in Compact: the number of
//      contracts (input Contracts) and the point value per contract that is used (input Point value
//      per contract, or the symbol's own value, marked "(symbol value)").
//   2. Long and short. Input Direction has a third option "Both" (appended after Long and Short, which
//      are unchanged). With Both, the limit lines, the distance labels and the table buffers are shown
//      for a long position (limits below price) and a short position (limits above price) at the same
//      time; labels and table rows carry the direction. Both is a planning view: both sides are measured
//      from the current price without open P&L (one real position cannot be long and short at once), also
//      with Line anchor = Entry price; the table shows the row "Both: planning view from current price".
//      Long and Short alone are unchanged. Each direction keeps its own intraday peak and day roll state.
//      Alert conditions stay one per type (none per direction), so nothing fires twice: Long watches the
//      long side, Short the short side, Both the nearer of the two sides.
//   3. House colors (MoTradeSystems visual system, chart palette). No red or green in the chart. Default
//      of Daily loss line color: light #E6EDF3 (was orange). Default of Drawdown line color: Signal Cyan
//      #3DC8FF (was red). Table and label: near-black #0D1117 background, #E6EDF3 text, #2B4258 border,
//      monospace font. New input "Color candles (house palette)", default on: rising candles #2768C8,
//      falling candles #9AB3D0 (body, border and wick). barcolor() recolours the bodies in every layout;
//      plotcandle() adds border and wick where this indicator sits above the main series.
//  v1.0.0 — first public release. Same logic and presets as 0.2.2; header, version and
//   publication metadata. One notice in the rules table: the fixed last Full row
//   "Educational/analysis tool — not financial advice." is removed (the source note row
//   keeps the notice and shows in Full and Compact); Full table has 7 rows instead of 8.
//   No input added, removed or renamed; defaults unchanged.
//  v0.2.2 — display and day-roll options. Seven inputs appended
//   at the end of the input list (saved settings keep their positions); all defaults give the
//   0.2.1 look and numbers.
//   Table position / Table text size / Table rows (Full or Compact).
//   Label size / Labels (nearer limit only or both limits) / Label text (add the line price).
//   Roll balance at day reset (default off): only when the position was held over the reset
//   (entry time set, Line anchor = Entry price) its open P&L at the reset is added to Balance at
//   day start; EOD trailing raises the high-water mark to that value. Closed trades stay with the
//   inputs. Closed-balance, intraday trailing and static unchanged.
//   Compact table rows carry the same flags as Full (soft breach, Eval only, peak not tracked).
//   dayKey from year/month/day (same day boundaries); tooltip of "Reset time zone" reworded.
//   Tooltip of "Show rules table" no longer says "bottom right". No input removed or renamed.
//  v0.2.1 — fixes from the re-review of v0.2.0 (internal review).
//   H1  Closed-balance trailing uses the current balance: base = max(high-water mark, balance).
//   M1  Intraday trailing base = max(peak, balance). Without an entry time the table
//       row "Max drawdown" adds "peak not tracked, set entry time".
//   M2  "soft breach" is a flag only where the firm's quote says it; where it comes only
//       from the curated rule text the table reads "soft breach, from rule notes".
//   L1  Stand date also covers the lock level field.
//   L2  Option labels carry no flags (saved settings stay valid). Flags live in the
//       table and in the distance label. A saved name that is no longer in the list
//       shows "preset not found, Manual" instead of falling back silently.
//   L3  Peak tracking counts the entry bar (time_close > entry time). Tooltip: far future = off.
//   L4  Distance label reads "Distance to blow-up (Eval only)" where the daily limit
//       applies to evaluations only.
//   No input removed, no GUI title changed (option labels of the preset list lost their flag suffix).
//  v0.2.0 — fixes from the review of v0.1.0 (internal review).
//   F1  New input "Current balance (USD)". Equity = current balance + open P&L.
//       The daily floor stays at balance at day start minus the daily limit.
//       The line price is now the inverse of the equity formula with the
//       current balance (v0.1.0 used the day-start balance).
//   F2  FX/CFD presets removed from the preset block (futures only in v1.0).
//       No currency conversion. Point value for FX stays a manual input.
//   F3  Drawdown type enum: static, EOD trailing, intraday trailing,
//       closed-balance trailing (new, handled like EOD). Unqualified
//       "trailing" is no longer assumed to be intraday in the generator.
//   F4  New input "Entry time (for peak tracking)". The intraday peak is
//       tracked from that bar on, only upward, and is not reset at the day
//       reset.
//   M1  Lines only from today's reset (or from the entry bar). KEEP_DAYS = 1.
//   M2  Lock level in USD as a preset field (P_LOCK) and as a manual input.
//       "Stop trailing at account size" stays.
//   M3  Preset label flag "(soft breach)"; label text "Distance to daily stop
//       (soft)" when the nearer limit is a soft daily limit.
//   M4  Preset label flag "(Eval only)" where the daily limit applies to
//       evaluations only.
//   M5  table.merge_cells runs once.
//   LOW "n/a" instead of NaN when points cannot be computed. One alert
//       condition per drawdown type (replaces "Trailing drawdown within N
//       points", which also fired for static drawdowns). Licence header MPL-2.0.
//       max_bars_back = 500 removed: the script reads at most one bar back
//       ([1]); every other series is a var or a drawing object. Confirm in the
//       first TradingView compile.
//
//  v0.1.0 — first draft. Not compiled on TradingView yet.
//   Model: you enter account size, high-water mark, balance at day start,
//   contracts and (optionally) your entry price. Open P&L is derived from the
//   last completed bar; the script cannot read your broker account.
// ============================================================================
indicator("MoTrade - Funded Line", "Funded Line", overlay = true, max_lines_count = 50, max_labels_count = 5)
 
// ---------------------------------------------------------------------------
// 1. Constants and groups
// ---------------------------------------------------------------------------
GRP_PRESET  = "Program"
GRP_ACCOUNT = "Account (typed in by you)"
GRP_MANUAL  = "Manual limits (used when Program = Manual)"
GRP_RESET   = "Day reset"
GRP_DISPLAY = "Display"
GRP_ALERT   = "Alerts"
GRP_TABLE   = "Table & label"
 
TYPE_STATIC   = 0
TYPE_EOD      = 1
TYPE_INTRADAY = 2
TYPE_CLOSED   = 3
UNIT_PCT      = 0
UNIT_USD      = 1
UNIT_NONE     = 2
KEEP_DAYS     = 1
MS_PER_MIN    = 60000
LUM_LIGHT     = 150.0
 
// House palette (MoTradeSystems visual system, chart palette). No red or green in the chart.
C_BLUE        = #2768C8
C_GREY        = #9AB3D0
C_CYAN        = #3DC8FF
C_TEXT        = #E6EDF3
C_DIV         = #2B4258
C_BG          = #0D1117
 
// --- PRESETS (generated 2026-11-07, source rules.json, sha256 17aaa8ac96323b45922f902312eec5f7e8f9a353d3821da0ff0d694f6f0e43f4) ---
// Do not edit by hand: rebuild with tools/funded_line/build_presets.py.
// Units: *_UNIT 0 = fraction of account size, 1 = USD fixed (valid for P_SIZE), 2 = no limit.
// Types: 0 = static, 1 = EOD trailing, 2 = intraday trailing, 3 = closed-balance trailing (handled like EOD).
// P_LOCK = USD level where a trailing floor stops (0 = export names no lock). P_SOFT = 1 soft breach (quoted), 2 soft breach from rule notes only (soft breach, from rule notes), 0 none. P_EVAL = 1 when the daily loss applies to evaluations only. Flags show in the table and the distance label, not in the option labels.
// Retained for saved settings (DG-2026-09-23-02): FundedNext Futures Legacy 100K. Not in the current export, values and stand date from the earlier export rules.json sha256 48ca712dce64c2a8f1747b66103f74b11eb2cca06506f8603456653dfd8f8dc4.
// Filter: futures only (--nur-futures; asset tag in PICKS, rules.json has no asset_class field). Excluded: 5.
PRESET_IN = input.string("Manual", "Firm / Program", options = ["Manual", "Phidias 100K 1-Step (A)", "Phidias 100K 1-Step (B)", "Apex 1-Step 100K", "Tradeify Growth 100K", "FundedNext Futures Rapid Daily 100K", "FundedNext Futures Legacy 100K", "Blue Guardian Futures 1-Step 100K"], group = GRP_PRESET, tooltip = "Pick a program to load its quoted limits, or Manual to type your own. Futures only in v1.0. Rules change: check your firm before relying on a preset.", display = display.none)
var array<string> P_NAME = array.from("Manual", "Phidias 100K 1-Step (A)", "Phidias 100K 1-Step (B)", "Apex 1-Step 100K", "Tradeify Growth 100K", "FundedNext Futures Rapid Daily 100K", "FundedNext Futures Legacy 100K", "Blue Guardian Futures 1-Step 100K")
var array<float> P_DD = array.from(0.0, 3000.0, 3000.0, 3000.0, 3500.0, 2500.0, 3000.0, 3500.0)
var array<int> P_DD_UNIT = array.from(0, 1, 1, 1, 1, 1, 1, 1)
var array<float> P_DL = array.from(0.0, 0.0, 0.0, 1500.0, 2500.0, 1250.0, 0.0, 2000.0)
var array<int> P_DL_UNIT = array.from(2, 2, 2, 1, 1, 1, 2, 1)
var array<int> P_TYPE = array.from(0, 1, 1, 1, 1, 1, 1, 1)
var array<int> P_SIZE = array.from(0, 100000, 100000, 100000, 100000, 100000, 100000, 100000)
var array<string> P_ASOF = array.from("n/a", "2026-09-01", "2026-09-01", "2026-09-09", "2026-09-09", "2026-09-01", "2026-09-01", "2026-09-01")
var array<float> P_LOCK = array.from(0.0, 100100.0, 100100.0, 0.0, 100100.0, 100100.0, 100000.0, 100000.0)
var array<int> P_SOFT = array.from(0, 0, 0, 0, 1, 0, 0, 2)
var array<int> P_EVAL = array.from(0, 0, 0, 1, 0, 0, 0, 0)
// --- END PRESETS ---
 
// ---------------------------------------------------------------------------
// 2. Inputs
// ---------------------------------------------------------------------------
size_in      = input.float(100000.0, "Account size (USD)", minval = 1.0, group = GRP_ACCOUNT, tooltip = "Starting balance of the account. Presets quoted in USD for a 100K tier use 100,000 regardless of this value.", display = display.none)
hwm_in       = input.float(0.0, "Equity high-water mark (USD)", minval = 0.0, group = GRP_ACCOUNT, tooltip = "Highest account equity or balance reached so far, as your firm measures it. 0 = account size. Update it by hand after each new high. If you were already in a position before the entry time, enter the high reached so far here.", display = display.none)
daystart_in  = input.float(0.0, "Balance at day start (USD)", minval = 0.0, group = GRP_ACCOUNT, tooltip = "Account balance at the last day reset. 0 = same as the high-water mark. The daily loss floor is this balance minus the daily loss limit.", display = display.none)
balance_in   = input.float(0.0, "Current balance (USD)", minval = 0.0, group = GRP_ACCOUNT, tooltip = "Enter your current balance after closed trades today. Equity = current balance + open P&L. 0 = same as the balance at day start.", display = display.none)
contracts_in = input.int(1, "Contracts", minval = 1, group = GRP_ACCOUNT, tooltip = "Position size used to convert dollars into points.", display = display.none)
pv_in        = input.float(0.0, "Point value per contract (USD)", minval = 0.0, group = GRP_ACCOUNT, tooltip = "Dollar value of one full price point per contract. 0 = use the symbol's own point value. Futures only in v1.0: for FX or CFD symbols the symbol's own point value is not in USD per contract, so enter the value yourself.", display = display.none)
dir_in       = input.string("Long", "Direction", options = ["Long", "Short", "Both"], group = GRP_ACCOUNT, tooltip = "Direction of the position. Long: limits sit below price. Short: limits sit above price. Both: planning view. The limits of a long position (below price) and of a short position (above price) are drawn at the same time, both measured from the current price without open profit or loss, whatever Line anchor says, because one real position cannot be long and short at once. Alert conditions then watch the nearer side; for one real position choose Long or Short.", display = display.none)
anchor_in    = input.string("Entry price", "Line anchor", options = ["Entry price", "Current price"], group = GRP_ACCOUNT, tooltip = "Entry price: lines are fixed in price terms around your entry and open P&L is counted. Current price: lines stay a constant distance from the last completed bar. With Direction = Both the lines always start from the current price.", display = display.none)
entry_in     = input.float(0.0, "Entry price", minval = 0.0, group = GRP_ACCOUNT, tooltip = "Average entry price of your open position. 0 = use the last completed bar.", display = display.none)
entry_time_in = input.time(0, "Entry time (for peak tracking)", group = GRP_ACCOUNT, tooltip = "Intraday trailing only: the equity peak is tracked from this bar on, never earlier, and only upward. It is not reset at the day reset. 0 = not set: the peak is not tracked and the base is the larger of the high-water mark and the current balance. A time far in the future = off. For a high reached before this time, enter it under Equity high-water mark (USD).", display = display.none)
 
man_dd_usd   = input.float(3000.0, "Max drawdown (USD)", minval = 0.0, group = GRP_MANUAL, tooltip = "Maximum loss allowed from the reference level, in dollars.", display = display.none)
man_dl_usd   = input.float(0.0, "Daily loss limit (USD)", minval = 0.0, group = GRP_MANUAL, tooltip = "Maximum loss allowed within one day, in dollars. 0 = no daily limit.", display = display.none)
man_type_in  = input.string("EOD trailing", "Drawdown type", options = ["Static", "EOD trailing", "Intraday trailing", "Closed-balance trailing"], group = GRP_MANUAL, tooltip = "Static: fixed floor under the starting balance. EOD trailing: floor follows the highest end-of-day balance. Intraday trailing: floor follows the highest equity reached intraday. Closed-balance trailing: updates on closed trades; enter balance after each close (treated like EOD trailing).", display = display.none)
lock_in      = input.bool(false, "Stop trailing at account size", group = GRP_MANUAL, tooltip = "When on, a trailing floor never rises above the account size (many programs lock the floor there). Check your firm's rule. Ignored when Lock level (USD) is above 0.", display = display.none)
lock_usd_in  = input.float(0.0, "Lock level (USD)", minval = 0.0, group = GRP_MANUAL, tooltip = "A trailing floor never rises above this balance level, for example 100100 for a lock at the starting balance plus 100. 0 = off. Presets carry their own quoted lock level.", display = display.none)
 
reset_hour   = input.int(17, "Reset hour", minval = 0, maxval = 23, group = GRP_RESET, tooltip = "Hour at which your firm's trading day rolls over. The default is a placeholder; the rule export carries no reset time, so check your firm.", display = display.none)
reset_min    = input.int(0, "Reset minute", minval = 0, maxval = 59, group = GRP_RESET, tooltip = "Minute of the day reset.", display = display.none)
tz_in        = input.string("America/Chicago", "Reset time zone", options = ["America/Chicago", "America/New_York", "Europe/Prague", "Europe/Berlin", "UTC"], group = GRP_RESET, tooltip = "Time zone for the day reset. At this time a new daily loss line starts for the new day. Without Roll balance at day reset the level follows your inputs, so update Balance at day start after the reset. With the roll on, a position held over the reset is carried forward at the reset.", display = display.none)
 
show_dl      = input.bool(true, "Show daily loss line", group = GRP_DISPLAY, tooltip = "Shows the line for the daily loss limit.", display = display.none)
show_dd      = input.bool(true, "Show drawdown line", group = GRP_DISPLAY, tooltip = "Shows the line for the drawdown limit.", display = display.none)
col_dl       = input.color(#E6EDF3, "Daily loss line color", group = GRP_DISPLAY, tooltip = "Color of the daily loss line. With Direction = Both the Long color and the Short color apply instead.", display = display.none)
col_dd       = input.color(#3DC8FF, "Drawdown line color", group = GRP_DISPLAY, tooltip = "Color of the drawdown line. With Direction = Both the Long color and the Short color apply instead.", display = display.none)
style_in     = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = GRP_DISPLAY, tooltip = "Line style for both limit lines. With Direction = Both the daily loss lines are dotted (dashed if this is Dotted) so that the two limits of one side stay apart.", display = display.none)
width_in     = input.int(2, "Line width", minval = 1, maxval = 4, group = GRP_DISPLAY, tooltip = "Line width for both limit lines.", display = display.none)
show_label   = input.bool(true, "Show distance label", group = GRP_DISPLAY, tooltip = "Label at the last bar with the distance to the nearest limit; with Labels = Both limits a second label marks the other limit. With Direction = Both every side gets its own label, so up to four labels (two per side).", display = display.none)
show_table   = input.bool(true, "Show rules table", group = GRP_DISPLAY, tooltip = "Table with the active rules and the remaining distance. Position, size and rows are set under Table & label.", display = display.none)
 
alert_dl_pts = input.float(20.0, "Daily loss alert distance (points)", minval = 0.0, group = GRP_ALERT, tooltip = "Used by the alert condition Daily loss within N points. The alert is created from the alert dialog.", display = display.none)
alert_dd_pts = input.float(20.0, "Drawdown alert distance (points)", minval = 0.0, group = GRP_ALERT, tooltip = "Used by the drawdown alert conditions (one per drawdown type). The alert is created from the alert dialog.", display = display.none)
 
// Added in 0.2.2: appended after the last v0.2.1 input so saved settings keep their positions.
tbl_pos_in   = input.string("Bottom right", "Table position", options = ["Bottom right", "Bottom left", "Top right", "Top left", "Middle right", "Middle left", "Bottom center", "Top center"], group = GRP_TABLE, tooltip = "Where the rules table sits on the chart.", display = display.none)
tbl_size_in  = input.string("Small", "Table text size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = GRP_TABLE, tooltip = "Text size of the table. The note rows use one step smaller (at least Tiny).", display = display.none)
tbl_rows_in  = input.string("Full", "Table rows", options = ["Full", "Compact"], group = GRP_TABLE, tooltip = "Full: all rows. Compact: program, lot size, daily loss buffer, drawdown buffer (with their flags) and the source note. With Direction = Both each buffer has a Long and a Short row and one planning-view row is added.", display = display.none)
lbl_size_in  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = GRP_TABLE, tooltip = "Text size of the distance label.", display = display.none)
lbl_mode_in  = input.string("Nearer limit only", "Labels", options = ["Nearer limit only", "Both limits"], group = GRP_TABLE, tooltip = "Nearer limit only: one label. Both limits: a second label for the farther limit.", display = display.none)
lbl_text_in  = input.string("Distance only", "Label text", options = ["Distance only", "Distance and line price"], group = GRP_TABLE, tooltip = "Distance and line price adds the price of the line to the label.", display = display.none)
roll_in      = input.bool(false, "Roll balance at day reset", group = GRP_RESET, tooltip = "Off: the balance at day start stays as typed in. On: when your position was open over a day reset (entry time set, Line anchor = Entry price), its open profit or loss at the reset is added to the balance at day start, and EOD trailing raises the high-water mark to that value. Closed trades still need Balance at day start and Current balance. Without an entry time nothing rolls.", display = display.none)
 
// Added in 1.1.0: appended after the last v1.0.0 input so saved settings keep their positions.
candle_in    = input.bool(true, "Color candles (house palette)", group = GRP_DISPLAY, tooltip = "Colors the price candles in the MoTradeSystems chart palette: rising candles in Brand Blue, falling candles in light blue-grey (body, border and wick). Switch it off to keep your own chart colors. If several MoTrade indicators on one chart color candles, only one of them should do it.", display = display.none)
 
// Added in 1.1.1: appended after the last v1.1.0 input so saved settings keep their positions.
col_long_in  = input.color(#2768C8, "Long color (Direction = Both)", group = GRP_DISPLAY, tooltip = "Used only with Direction = Both: color of the limit lines, the distance label and the table rows of the long side (limits below price). Default: Brand Blue, the color of rising candles in the house palette. Long and Short alone use the two line colors above.", display = display.none)
col_short_in = input.color(#9AB3D0, "Short color (Direction = Both)", group = GRP_DISPLAY, tooltip = "Used only with Direction = Both: color of the limit lines, the distance label and the table rows of the short side (limits above price). Default: light blue-grey, the color of falling candles in the house palette. It is a color code for the side, not a signal.", display = display.none)
 
// ---------------------------------------------------------------------------
// 3. Helpers
// ---------------------------------------------------------------------------
f_limit(float value, int unit, float sz) =>
    unit == UNIT_PCT ? value * sz : unit == UNIT_USD ? value : na
 
f_type_from_text(string s) =>
    s == "Static" ? TYPE_STATIC : s == "EOD trailing" ? TYPE_EOD : s == "Closed-balance trailing" ? TYPE_CLOSED : TYPE_INTRADAY
 
f_type_name(int t) =>
    t == TYPE_STATIC ? "static" : t == TYPE_EOD ? "EOD trailing" : t == TYPE_CLOSED ? "closed-balance trailing" : "intraday trailing"
 
f_style(string s) =>
    s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed
 
f_usd(float v) =>
    na(v) ? "none" : "$" + str.tostring(math.round(v))
 
f_pts(float v) =>
    na(v) ? "n/a" : str.tostring(v, "#.##")
 
f_dist(float buf, float k) =>
    k > 0 ? buf / k : na
 
// Text color that stays readable on a tone: near-black on light tones, light on dark tones.
f_on(color c) =>
    float lum = 0.2126 * color.r(c) + 0.7152 * color.g(c) + 0.0722 * color.b(c)
    lum > LUM_LIGHT ? C_BG : C_TEXT
 
f_floor_price(float floorBal, float bal, float entry, float dirSign, float k) =>
    k > 0 ? entry + dirSign * (floorBal - bal) / k : na
 
f_table_pos(string s) =>
    switch s
        "Bottom left" => position.bottom_left
        "Top right" => position.top_right
        "Top left" => position.top_left
        "Middle right" => position.middle_right
        "Middle left" => position.middle_left
        "Bottom center" => position.bottom_center
        "Top center" => position.top_center
        => position.bottom_right
 
f_text_size(string s) =>
    switch s
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        "Huge" => size.huge
        => size.small
 
f_note_size(string s) =>
    switch s
        "Normal" => size.small
        "Large" => size.normal
        "Huge" => size.large
        => size.tiny
 
f_label_size(string s) =>
    switch s
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
f_start_line(array<line> arr, float y, color col, string sty, int w) =>
    if array.size(arr) > 0
        line.set_extend(array.get(arr, array.size(arr) - 1), extend.none)
    array.push(arr, line.new(bar_index, y, bar_index, y, color = col, style = f_style(sty), width = w, extend = extend.right))
    if array.size(arr) > KEEP_DAYS
        line.delete(array.shift(arr))
 
f_move_line(array<line> arr, float y) =>
    if array.size(arr) > 0 and not na(y)
        line l = array.get(arr, array.size(arr) - 1)
        line.set_xy1(l, line.get_x1(l), y)
        line.set_xy2(l, bar_index, y)
 
// ---------------------------------------------------------------------------
// 4. Rules for the active program
// ---------------------------------------------------------------------------
int   progRaw   = array.indexof(P_NAME, PRESET_IN)
bool  presetMissing = progRaw < 0
int   progIdx   = math.max(progRaw, 0)
bool  isManual  = progIdx == 0
float presetSz  = array.get(P_SIZE, progIdx)
float acctSize  = isManual or presetSz <= 0 ? size_in : presetSz
float ddLimit   = isManual ? man_dd_usd : f_limit(array.get(P_DD, progIdx), array.get(P_DD_UNIT, progIdx), acctSize)
float dlLimit   = isManual ? (man_dl_usd > 0 ? man_dl_usd : na) : f_limit(array.get(P_DL, progIdx), array.get(P_DL_UNIT, progIdx), acctSize)
int   ddType    = isManual ? f_type_from_text(man_type_in) : array.get(P_TYPE, progIdx)
float lockLevel = isManual ? (lock_usd_in > 0 ? lock_usd_in : lock_in ? acctSize : 0.0) : array.get(P_LOCK, progIdx)
bool  isSoft    = not isManual and array.get(P_SOFT, progIdx) == 1
bool  isEvalDl  = not isManual and array.get(P_EVAL, progIdx) == 1
string stand    = array.get(P_ASOF, progIdx)
 
// ---------------------------------------------------------------------------
// 5. Account model (completed bars only)
// ---------------------------------------------------------------------------
float pointValue = pv_in > 0 ? pv_in : syminfo.pointvalue
float k          = contracts_in * pointValue
bool  showL      = dir_in != "Short"
bool  showS      = dir_in != "Long"
bool  isBoth     = dir_in == "Both"
float px         = barstate.isconfirmed ? close : nz(close[1], close)
// Direction Both is a planning view: both sides start from the current price and carry no open P&L,
// because one real position cannot be long and short at once.
float entry      = anchor_in == "Entry price" and entry_in > 0 and not isBoth ? entry_in : px
float hwm0       = hwm_in > 0 ? hwm_in : acctSize
float dayStart   = daystart_in > 0 ? daystart_in : hwm0
float balance    = balance_in > 0 ? balance_in : dayStart
// Equity of a long position (L) and of a short position (S) opened at the entry price.
// Direction Long uses L only, Short uses S only, Both uses both (entry = current price, so eqL = eqS = balance).
float eqL        = balance + (px - entry) * k
float eqS        = balance - (px - entry) * k
 
int   shifted = time - (reset_hour * 60 + reset_min) * MS_PER_MIN
int   dayKey  = year(shifted, tz_in) * 10000 + month(shifted, tz_in) * 100 + dayofmonth(shifted, tz_in)
float dayChg  = ta.change(dayKey)
bool  newDay  = barstate.isfirst or dayChg != 0
bool  entryBar = entry_time_in > 0 and time_close > entry_time_in and nz(time_close[1], 0) <= entry_time_in
bool  tracking = entry_time_in > 0 and time_close > entry_time_in
 
// Roll at day reset (off by default): when the position was open over the reset (entry time set,
// Entry price anchor), its open P&L at the reset is added to the typed balance at day start.
// Closed trades are not known to the script; EOD trailing raises the high-water mark to that value.
// One state per direction, because the open P&L of a long and of a short position differ.
var float dayStartRollL = dayStart
var float hwmRollL = hwm0
var float dayStartRollS = dayStart
var float hwmRollS = hwm0
bool heldOverReset = anchor_in == "Entry price" and not isBoth and bar_index > 0 and tracking[1]
bool rollNow = roll_in and newDay and not barstate.isfirst and heldOverReset
if rollNow
    float openPrevL = nz(eqL[1] - balance, 0.0)
    dayStartRollL := dayStart + openPrevL
    hwmRollL := math.max(hwmRollL, dayStartRollL)
    float openPrevS = nz(eqS[1] - balance, 0.0)
    dayStartRollS := dayStart + openPrevS
    hwmRollS := math.max(hwmRollS, dayStartRollS)
float dayStartEffL = roll_in ? dayStartRollL : dayStart
float dayStartEffS = roll_in ? dayStartRollS : dayStart
float hwmEffL = roll_in and ddType == TYPE_EOD ? hwmRollL : hwm0
float hwmEffS = roll_in and ddType == TYPE_EOD ? hwmRollS : hwm0
 
// Peak: starts at the high-water mark, rises only, never reset by a new day. One peak per direction.
var float peakL = hwm0
var float peakS = hwm0
if tracking and barstate.isconfirmed and ddType == TYPE_INTRADAY
    peakL := math.max(peakL, eqL)
    peakS := math.max(peakS, eqS)
 
bool  hasDd     = ddLimit > 0
bool  hasDl     = not na(dlLimit)
 
// Floors, buffers and line prices of one direction. dirSign: 1 = long (floor below price), -1 = short (above).
f_side(float eqX, float peakX, float dayStartEffX, float hwmEffX, float dirSign) =>
    float baseX     = ddType == TYPE_STATIC ? acctSize : ddType == TYPE_INTRADAY ? math.max(peakX, balance) : ddType == TYPE_CLOSED ? math.max(hwmEffX, balance) : hwmEffX
    float floorRawX = baseX - ddLimit
    float ddFloorX  = lockLevel > 0 and ddType != TYPE_STATIC ? math.min(floorRawX, lockLevel) : floorRawX
    float dlFloorX  = dayStartEffX - dlLimit
    float bufDdX    = hasDd ? eqX - ddFloorX : na
    float bufDlX    = hasDl ? eqX - dlFloorX : na
    float ptsDdX    = f_dist(bufDdX, k)
    float ptsDlX    = f_dist(bufDlX, k)
    float pxDdX     = hasDd ? f_floor_price(ddFloorX, balance, entry, dirSign, k) : na
    float pxDlX     = hasDl ? f_floor_price(dlFloorX, balance, entry, dirSign, k) : na
    [bufDdX, bufDlX, ptsDdX, ptsDlX, pxDdX, pxDlX]
 
[bufDdL, bufDlL, ptsDdL, ptsDlL, pxDdL, pxDlL] = f_side(eqL, peakL, dayStartEffL, hwmEffL, 1.0)
[bufDdS, bufDlS, ptsDdS, ptsDlS, pxDdS, pxDlS] = f_side(eqS, peakS, dayStartEffS, hwmEffS, -1.0)
 
// ---------------------------------------------------------------------------
// 6. Lines (today's reset or the entry bar onward; earlier days are not drawn)
// ---------------------------------------------------------------------------
var array<line> linesDlL = array.new<line>()
var array<line> linesDdL = array.new<line>()
var array<line> linesDlS = array.new<line>()
var array<line> linesDdS = array.new<line>()
 
// Direction Both: each side has one color; the daily loss line is dotted (dashed if Line style is Dotted).
string styleDl = isBoth ? (style_in == "Dotted" ? "Dashed" : "Dotted") : style_in
color  colDlL  = isBoth ? col_long_in : col_dl
color  colDdL  = isBoth ? col_long_in : col_dd
color  colDlS  = isBoth ? col_short_in : col_dl
color  colDdS  = isBoth ? col_short_in : col_dd
 
if newDay or entryBar
    if showL and show_dl and not na(pxDlL)
        f_start_line(linesDlL, pxDlL, colDlL, styleDl, width_in)
    if showL and show_dd and not na(pxDdL)
        f_start_line(linesDdL, pxDdL, colDdL, style_in, width_in)
    if showS and show_dl and not na(pxDlS)
        f_start_line(linesDlS, pxDlS, colDlS, styleDl, width_in)
    if showS and show_dd and not na(pxDdS)
        f_start_line(linesDdS, pxDdS, colDdS, style_in, width_in)
f_move_line(linesDlL, pxDlL)
f_move_line(linesDdL, pxDdL)
f_move_line(linesDlS, pxDlS)
f_move_line(linesDdS, pxDdS)
 
// ---------------------------------------------------------------------------
// 7. Label and table (last bar only)
// ---------------------------------------------------------------------------
f_buffer_text(float pts, float buf) =>
    na(buf) ? "n/a" : buf <= 0 ? "limit reached" : f_pts(pts) + " pts / " + f_usd(buf)
 
string lblSize = f_label_size(lbl_size_in)
bool   withPx  = lbl_text_in == "Distance and line price"
 
f_lbl_text(bool forDl, float buf, float pts, float lpx, string prefix) =>
    string which = forDl ? "daily loss" : "drawdown"
    string head  = forDl and isSoft ? "Distance to daily stop (soft)" : forDl and isEvalDl ? "Distance to blow-up (Eval only)" : "Distance to blow-up"
    string txt   = buf <= 0 ? head + ": limit reached (" + which + ")" : head + ": " + f_pts(pts) + " pts (" + f_usd(buf) + ") · " + which
    prefix + (withPx ? txt + " · at " + str.tostring(lpx, format.mintick) : txt)
 
f_place_label(label lb, float y, string txt, color bg, color fg) =>
    label out = lb
    if na(out)
        out := label.new(bar_index, y, txt, style = label.style_label_left, color = bg, textcolor = fg, size = lblSize, text_font_family = font.family_monospace)
    else
        label.set_xy(out, bar_index, y)
        label.set_text(out, txt)
    out
 
// One label of one direction: nearer = true marks the nearer limit, nearer = false the farther limit.
f_side_label(label lb, bool nearer, float bDl, float bDd, float pDl, float pDd, float xDl, float xDd, string prefix, color bg, color fg) =>
    bool useDl = hasDl and (not hasDd or bDl < bDd)
    bool forDl = nearer ? useDl : not useDl
    float buf  = forDl ? bDl : bDd
    float pts  = forDl ? pDl : pDd
    float lpx  = forDl ? xDl : xDd
    f_place_label(lb, lpx, f_lbl_text(forDl, buf, pts, lpx, prefix), bg, fg)
 
var label lbNearL = na
var label lbFarL  = na
var label lbNearS = na
var label lbFarS  = na
string pfxL = isBoth ? "Long · " : ""
string pfxS = isBoth ? "Short · " : ""
// Both: the label background carries the side color; otherwise the house label look.
color  lblBgL = isBoth ? color.new(col_long_in, 15) : color.new(C_BG, 15)
color  lblFgL = isBoth ? f_on(col_long_in) : C_TEXT
color  lblBgS = isBoth ? color.new(col_short_in, 15) : color.new(C_BG, 15)
color  lblFgS = isBoth ? f_on(col_short_in) : C_TEXT
bool   farOn = lbl_mode_in == "Both limits" and hasDl and hasDd
if barstate.islast and show_label
    if showL and (not na(pxDdL) or not na(pxDlL))
        lbNearL := f_side_label(lbNearL, true, bufDlL, bufDdL, ptsDlL, ptsDdL, pxDlL, pxDdL, pfxL, lblBgL, lblFgL)
        if farOn and not na(pxDlL) and not na(pxDdL)
            lbFarL := f_side_label(lbFarL, false, bufDlL, bufDdL, ptsDlL, ptsDdL, pxDlL, pxDdL, pfxL, lblBgL, lblFgL)
    if showS and (not na(pxDdS) or not na(pxDlS))
        lbNearS := f_side_label(lbNearS, true, bufDlS, bufDdS, ptsDlS, ptsDdS, pxDlS, pxDdS, pfxS, lblBgS, lblFgS)
        if farOn and not na(pxDlS) and not na(pxDdS)
            lbFarS := f_side_label(lbFarS, false, bufDlS, bufDdS, ptsDlS, ptsDdS, pxDlS, pxDdS, pfxS, lblBgS, lblFgS)
 
bool isCompact = tbl_rows_in == "Compact"
int  nSide     = isBoth ? 2 : 1
int  nHint     = isBoth ? 1 : 0
int  tblRows   = (isCompact ? 3 + 2 * nSide : 6 + 2 * nSide) + nHint
string tblSize  = f_text_size(tbl_size_in)
string noteSize = f_note_size(tbl_size_in)
// The script reruns from the first bar when an input changes, so this table is created fresh
// for the chosen row count: no stale cells after switching Full and Compact or Direction.
var table tb = table.new(f_table_pos(tbl_pos_in), 2, tblRows, bgcolor = color.new(C_BG, 15), border_width = 1, border_color = C_DIV)
var bool tbMerged = false
f_row(int r, string a, string b) =>
    table.cell(tb, 0, r, a, text_color = color.new(C_TEXT, 25), text_halign = text.align_left, text_size = tblSize, text_font_family = font.family_monospace)
    table.cell(tb, 1, r, b, text_color = C_TEXT, text_halign = text.align_right, text_size = tblSize, text_font_family = font.family_monospace)
 
// Buffer rows of one side: with Direction = Both the cell behind the row name carries the side color.
f_row_dir(int r, string a, string b, color tone) =>
    bool tinted = not na(tone)
    table.cell(tb, 0, r, a, text_color = tinted ? f_on(tone) : color.new(C_TEXT, 25), text_halign = text.align_left, text_size = tblSize, text_font_family = font.family_monospace, bgcolor = tinted ? color.new(tone, 15) : na)
    table.cell(tb, 1, r, b, text_color = C_TEXT, text_halign = text.align_right, text_size = tblSize, text_font_family = font.family_monospace)
 
if barstate.islast and show_table
    color toneL = isBoth ? col_long_in : color(na)
    color toneS = isBoth ? col_short_in : color(na)
    string standTxt = isManual ? "your input" : stand
    string dlFlag = array.get(P_SOFT, progIdx) == 2 ? " · soft breach, from rule notes" : isSoft ? " · soft breach" : isEvalDl ? " · Eval only" : ""
    string peakHint = ddType == TYPE_INTRADAY and entry_time_in == 0 ? " · peak not tracked, set entry time" : ""
    string retiredTxt = PRESET_IN == "FundedNext Futures Legacy 100K" ? " No longer offered." : ""
    string note = isManual ? "Limits typed in by you." : "Rules as retrieved on " + stand + " from the firm's public rules." + retiredTxt
    string lotTxt = str.tostring(contracts_in) + (contracts_in == 1 ? " contract" : " contracts") + " · $" + str.tostring(pointValue, "#.#####") + " per point each" + (pv_in > 0 ? "" : " (symbol value)")
    string sfxL = isBoth ? " · Long" : ""
    string sfxS = isBoth ? " · Short" : ""
    int row = 0
    f_row(row, "Program", presetMissing ? "preset not found, Manual" : PRESET_IN)
    row += 1
    if isBoth
        f_row(row, "Direction", "Both: planning view from current price")
        row += 1
    if not isCompact
        f_row(row, "Rules as of", standTxt)
        row += 1
    f_row(row, "Lot size", lotTxt)
    row += 1
    if not isCompact
        f_row(row, "Daily loss limit", f_usd(dlLimit) + (hasDl ? dlFlag : ""))
        row += 1
        f_row(row, "Max drawdown", f_usd(ddLimit) + " · " + f_type_name(ddType) + peakHint)
        row += 1
    // Buffer rows: the Compact rows carry the same flags as the Full limit rows.
    if showL
        f_row_dir(row, "Daily loss buffer" + sfxL, hasDl ? f_buffer_text(ptsDlL, bufDlL) + (isCompact ? dlFlag : "") : "no daily limit", toneL)
        row += 1
    if showS
        f_row_dir(row, "Daily loss buffer" + sfxS, hasDl ? f_buffer_text(ptsDlS, bufDlS) + (isCompact ? dlFlag : "") : "no daily limit", toneS)
        row += 1
    if showL
        f_row_dir(row, "Drawdown buffer" + sfxL, (hasDd ? f_buffer_text(ptsDdL, bufDdL) : "n/a") + (isCompact ? peakHint : ""), toneL)
        row += 1
    if showS
        f_row_dir(row, "Drawdown buffer" + sfxS, (hasDd ? f_buffer_text(ptsDdS, bufDdS) : "n/a") + (isCompact ? peakHint : ""), toneS)
        row += 1
    table.cell(tb, 0, row, note, text_color = color.new(C_TEXT, 25), text_size = noteSize, text_font_family = font.family_monospace)
    if not tbMerged
        table.merge_cells(tb, 0, row, 1, row)
        tbMerged := true
 
// ---------------------------------------------------------------------------
// 8. Candles (house palette)
// ---------------------------------------------------------------------------
// barcolor() recolours the candle bodies in every layout. plotcandle() additionally draws body, border
// and wick in the same colours; it is visible where this indicator sits above the main series
// (TradingView visual order), otherwise the chart keeps its own border and wick colours. na = chart candles.
// The four series are gated by candle_in as well as the colours, so with the input off nothing is drawn.
color candleCol = candle_in ? (close >= open ? C_BLUE : C_GREY) : na
barcolor(candleCol, title = "Candles (house palette)", editable = false)
plotcandle(candle_in ? open : na, candle_in ? high : na, candle_in ? low : na, candle_in ? close : na, "Candles (house palette)", color = candleCol, wickcolor = candleCol, bordercolor = candleCol, editable = false, display = display.pane)
 
// ---------------------------------------------------------------------------
// 9. Alerts (conditions only, no orders)
// ---------------------------------------------------------------------------
// One condition per type, never one per direction, so no alert fires twice for the same bar.
// Direction Long watches the long side, Short the short side, Both the nearer of the two sides.
float alPtsDl = isBoth ? math.min(ptsDlL, ptsDlS) : showS ? ptsDlS : ptsDlL
float alPtsDd = isBoth ? math.min(ptsDdL, ptsDdS) : showS ? ptsDdS : ptsDdL
alertcondition(hasDl and alPtsDl <= alert_dl_pts, "Daily loss within N points", "Funded Line: the daily loss limit is within the alert distance set in the indicator inputs.")
alertcondition(hasDd and ddType == TYPE_STATIC and alPtsDd <= alert_dd_pts, "Static drawdown within N points", "Funded Line: the static drawdown limit is within the alert distance set in the indicator inputs.")
alertcondition(hasDd and ddType == TYPE_EOD and alPtsDd <= alert_dd_pts, "EOD trailing drawdown within N points", "Funded Line: the EOD trailing drawdown limit is within the alert distance set in the indicator inputs.")
alertcondition(hasDd and ddType == TYPE_INTRADAY and alPtsDd <= alert_dd_pts, "Intraday trailing drawdown within N points", "Funded Line: the intraday trailing drawdown limit is within the alert distance set in the indicator inputs.")
alertcondition(hasDd and ddType == TYPE_CLOSED and alPtsDd <= alert_dd_pts, "Closed-balance trailing drawdown within N points", "Funded Line: the closed-balance trailing drawdown limit is within the alert distance set in the indicator inputs.")

← 返回列表