Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Monthly Strategy Performance Table

A Pine Script v5 strategy built on SMA (close, 200). It has 2 order rules, 1 entry among them, and trades long only with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 100% of equity and pays 0.005 commission. 18 settings; defaults include MA 1 Length 200, MA 2 Length 10 and Stop Loss Percent 0.10.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Monthly Strategy Performance Table repaint?
No
No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
How did Monthly Strategy Performance Table do on BTCUSDT 1D with default settings?
+25.68%
From 26 Jan 2024 to 21 Oct 2026, over 36 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Monthly Strategy Performance Table run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 36 before, 62 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does Monthly Strategy Performance Table use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does Monthly Strategy Performance Table run in Zeal Terminal?
Yes
It compiles in 549 ms and runs 1,000 bars in 109 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Plot
  • Plot
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (12)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$125,682$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Zeal Terminal's engine currently reads an order side written as direction = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 41) so the engine trades the way the script says.
Table drawn by the script, as it stood on the last bar
YearJanFebMarAprMayJunJulAugSepOctNovDecTOTALMaxDDREALIZED P&L
20244.28123.19+19.47%-0.77%CAGR: +7.92%
20253.91-13.667.7105.94-2.396.32-0.85-4.78-2.39-3.640-3.83%-13.66%MaxDD: -13.61%
202600000001.168.041.3+10.5%-0.35%DD Bars: 457
MAR: 0.58
Return: +25.68%
Net profit
+25.68%
$25,682.40
Buy and hold
+102.5%
same period
Closed trades
36
23 won · 13 lost
Profitable
63.9%
of closed trades
Profit factor
1.50
gross profit ÷ gross loss
Max drawdown
20.19%
−$25,359.60

One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

What a careful reader of this script would point out, found by checking the source and the backtest.

  • Check

    1 setting does nothing

    “Cell Text Color” is declared but never read.

  • Check

    No stop loss

    Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Strategy Parameters
MA 1 LengthLong-term MA200int · step 10ma1
MA 2 LengthShort-term MA10int · step 10ma2
Stop Loss PercentFailsafe Stop Loss Percent Decline0.10float · step 0.1stopPrice stopCondition
Exit On Lower CloseWait for a lower-close before exiting above MA2falseboolsellCondition
Time Filter
Start FilterStart date & time to begin searching for setupstimestamp("01 Jan 1995 13:30 +0000")timef_dateFilter
End FilterEnd date & time to stop searching for setupstimestamp("1 Jan 2099 19:30 +0000")timef_dateFilter
Monthly Performance Table
Turn On |trueboolline 288
Debug Mode |falseboolline 213 New Month New Year
Decimal PrecisionDecimal precision of each cell2int · min 1line 90
Title Cell Color#cccccccolorline 292 line 293 line 294 line 295 line 296 line 297 line 298 line 299 line 300 line 301 line 302 line 303 line 304 line 305 line 306 line 313 line 348 line 349 line 350 line 351 line 352 line 353
Title Text Color#363a45colorline 292 line 293 line 294 line 295 line 296 line 297 line 298 line 299 line 300 line 301 line 302 line 303 line 304 line 305 line 306 line 313 line 348 line 349 line 350 line 351 line 352 line 353
Cell Text Colorcolor.whitecolorunused
Year Profit Colorcolor.new(color.green, 50)colory_color m_color
Year Loss Colorcolor.new(color.red, 50)colory_color m_color
Year B/E Colorcolor.new(color.white, 50)colory_color m_color line 319
Page NumberWhich page of results to display1int · min 1 · max 10 · step 1startIndex
Page Size (Rows)How many rows to display20int · min 1startIndex endIndex line 280
Text SizeSmallstring · options ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"]tableTextSize

What it calculates

  • SMAclose, MA 1 Length (200)ma1 · line 28
  • SMAclose, MA 2 Length (10)ma2 · line 29

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

The script has 61 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long longbuyConditionOn41
Close LongsellCondition or stopConditionOn46

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source.

Not measuredAn engine gap, not the scriptThe script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script. The answer comes from the checks on the source alone.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+25.7%+102.5%3664%1.5020.2%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+6.6%+5.5%5269%1.426.2%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+0.2%+9.8%3474%1.0042.2%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+13.3%+8.4%6077%1.4510.1%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−26.6%+16.7%3266%0.7641.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+4.5%+21.5%4663%1.1410.8%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−7.5%+148.3%3863%0.9231.8%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+9.5%+17.1%3871%1.648.9%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

Settings heatmap

Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (MA 1 Length 340, MA 2 Length 6) made +25.0% before 26 Dec 2025 and +4.6% after it, worse than the defaults' +12.3% after. Tuning on the past did not carry forward. 45% of the 64 combinations made money in-sample and 78% out-of-sample.

Before 26 Dec 2025 · in-sample
MA 2 Length ↓ · MA 1 Length →100120140170200240280340
5+22%+1%−5%+4%+3%+20%+15%+11%
6−12%−21%−17%−8%+1%+24%+24%+25%
7−4%−16%−14%−5%−0%+16%+15%+4%
9−2%−13%−16%−3%+4%+13%+16%+7%
10+10%−8%−8%+7%+13%+4%+6%−6%
12−10%−23%−21%−9%−0%+5%+7%+4%
14−14%−27%−25%−14%−5%−5%−1%−5%
17−8%−21%−22%−22%+9%+0%+0%−0%
From 26 Dec 2025 · out-of-sample
MA 2 Length ↓ · MA 1 Length →100120140170200240280340
5+7%+6%+3%+17%+17%+20%+20%+5%
6+2%+2%−0%+12%+15%+18%+18%+5%
7+1%+1%−0%+13%+15%+18%+18%+5%
9+1%+1%−1%+12%+15%+16%+17%+1%
10−2%−2%−4%+10%+12%+11%+11%+1%
12+3%+3%+1%+1%+10%+10%+10%+1%
14+2%+2%−0%−0%+8%+8%+8%−0%
17−4%−4%−6%−6%+3%+3%+3%−0%

Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market2070%$32,190.00
Sideways market1553%−$7,411.69
Falling market1100%$904.03

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

24.4%

The 95th percentile of the worst drawdown when the same 36 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 12.4% to 24.4%; the tick is what actually happened, 13.6%. Order luck alone moves it this much.

0%28%
All 36 trades
SideEntryExitBarsP&L
long24 Oct 2024 66,668.6025 Oct 2024 68,198.301$2,294.35
long26 Oct 2024 66,698.3028 Oct 2024 68,021.702$2,029.62
long3 Nov 2024 69,374.707 Nov 2024 75,572.004$9,319.25
long26 Nov 2024 93,010.0028 Nov 2024 95,863.102$3,486.02
long3 Dec 2024 95,840.604 Dec 2024 95,849.701$11.08
long10 Dec 2024 97,276.5012 Dec 2024 101,125.002$4,634.38
long19 Dec 2024 100,204.0026 Dec 2024 99,429.607−$941.12
long27 Dec 2024 95,791.603 Jan 2025 96,984.807$1,505.10
long9 Jan 2025 95,060.6015 Jan 2025 96,560.906$1,930.73
long27 Jan 2025 102,620.0030 Jan 2025 103,733.003$1,348.08
long1 Feb 2025 102,430.0013 Feb 2025 97,870.0012−$5,591.76
long14 Feb 2025 96,608.1015 Feb 2025 97,500.501$1,108.63
long17 Feb 2025 96,118.1021 Feb 2025 98,305.004$2,756.05
long22 Feb 2025 96,182.0027 Feb 2025 84,250.105−$15,369.30
long28 Feb 2025 84,708.603 Mar 2025 94,270.003$12,249.20
long4 Mar 2025 86,221.206 Mar 2025 90,606.002$6,141.89
long8 Mar 2025 86,801.7011 Mar 2025 78,595.903−$11,997.80
long13 Mar 2025 83,680.1016 Mar 2025 84,338.403$904.03
long5 May 2025 94,277.607 May 2025 96,834.002$3,140.49
long18 May 2025 103,127.0019 May 2025 106,454.001$3,838.48
long29 May 2025 107,782.008 Jun 2025 105,552.0010−$2,540.26
long13 Jun 2025 105,672.0024 Jun 2025 105,334.0011−$384.44
long2 Jul 2025 105,681.003 Jul 2025 108,850.001$3,593.93
long20 Jul 2025 117,840.0023 Jul 2025 119,954.003$2,215.37
long26 Jul 2025 117,614.0028 Jul 2025 119,416.002$1,924.80
long29 Jul 2025 118,062.008 Aug 2025 117,472.0010−$638.03
long16 Aug 2025 117,342.0023 Aug 2025 116,936.007−$439.36
long24 Aug 2025 115,438.003 Sep 2025 111,240.0010−$4,601.41
long20 Sep 2025 115,632.0030 Sep 2025 114,312.0010−$1,392.32
long11 Oct 2025 112,774.0024 Oct 2025 110,078.0013−$2,881.87
long30 Oct 2025 110,021.0011 Nov 2025 106,011.0012−$4,288.38
long31 Aug 2026 77,682.001 Sep 2026 78,581.301$1,312.38
long2 Sep 2026 77,439.004 Sep 2026 81,270.402$5,673.77
long9 Sep 2026 78,455.8019 Sep 2026 80,883.9010$3,724.64
long29 Sep 2026 83,500.002 Oct 2026 84,880.103$2,050.65
long8 Oct 2026 83,321.8021 Oct 2026 83,028.1013−$444.55

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
Monthly Strategy Performance Table this page—v5 strategy+25.7%3620.2%
Follow the Crypto Shorts by xtradernetsmav4 strategyNo trades on this market
buy down and sell high trend 200 sma and ma cross by willi130503smav4 strategyNo trades on this market
Mayer Multiple Strategy by xtradernetsmav4 strategyNo trades on this market
Moving Average Cross Strategy early Closing by Geduldtradersmav4 strategy+73.8%20151.5%
MFI Simple Strategy by OztheWozsmav5 strategy−0.2%283.2%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 36 before, 62 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// major improvements and fixes to the code that made this script much better!-// @version=5+// @version=6//////////////////////////////////////////////////////////////////////////⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 549 msWith a workaround 1,000 bars in 109 msNot measured
PineTSNot testedNot testedNot measured

Zeal Terminal's engine currently reads an order side written as direction = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 41) so the engine trades the way the script says.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © ZenAndTheArtOfTrading// Version 2 (Last Updated 29th June, 2023)// Huge thanks to Marc (https://www.tradingview.com/u/Mrcrbw/) for providing// major improvements and fixes to the code that made this script much better!// @version=5//////////////////////////////////////////////////////////////////////////// EXAMPLE STRATEGY (REPLACE THIS CODE WITH YOUR OWN)                   //// Replace lines 15 -> 69 with your own strategy script code!           //// This example system is my Simple Pullback Strategy                   //// Check my TradingView profile for more info about this script         ////////////////////////////////////////////////////////////////////////////strategy("Monthly Performance Table",      overlay=true,      initial_capital=100000,     default_qty_type=strategy.percent_of_equity,      default_qty_value=100,     commission_type=strategy.commission.cash_per_contract,      commission_value=0.005)// Get user inputi_ma1           = input.int(title="MA 1 Length", defval=200, step=10, group="Strategy Parameters", tooltip="Long-term MA")i_ma2           = input.int(title="MA 2 Length", defval=10, step=10, group="Strategy Parameters", tooltip="Short-term MA")i_stopPercent   = input.float(title="Stop Loss Percent", defval=0.10, step=0.1, group="Strategy Parameters", tooltip="Failsafe Stop Loss Percent Decline")i_lowerClose    = input.bool(title="Exit On Lower Close", defval=false, group="Strategy Parameters", tooltip="Wait for a lower-close before exiting above MA2")i_startTime     = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")i_endTime       = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")// Get indicator valuesma1 = ta.sma(close, i_ma1)ma2 = ta.sma(close, i_ma2)// Check filter(s)f_dateFilter = time >= i_startTime and time <= i_endTime// Check buy/sell conditionsvar float buyPrice = 0buyCondition    = close > ma1 and close < ma2 and strategy.position_size == 0 and f_dateFiltersellCondition   = close > ma2 and strategy.position_size > 0 and (not i_lowerClose or close < low[1])stopDistance    = strategy.position_size > 0 ? ((buyPrice - close) / close) : nastopPrice       = strategy.position_size > 0 ? buyPrice - (buyPrice * i_stopPercent) : nastopCondition   = strategy.position_size > 0 and stopDistance > i_stopPercent// Enter positionsif buyCondition    strategy.entry(id="Long", direction=strategy.long, comment="Equity = $" + str.tostring(strategy.equity, "#.##"))if buyCondition[1]    buyPrice := strategy.position_avg_price// Exit positionsif sellCondition or stopCondition    strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=true" : ""))    buyPrice := na// Draw pretty colorsplot(buyPrice, color=color.lime, style=plot.style_linebr)plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)plot(ma1, color=color.blue)plot(ma2, color=color.orange)////////////////////////////////////////////////////////////// END EXAMPLE STRATEGY (REPLACE THIS CODE WITH YOUR OWN) ////////////////////////////////////////////////////////////////-------------------------------------------------------------------------////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MONTHLY TABLE based on the script written by QuantNomad - Copy & Paste code from here down into your strategy script /{// Original Script: https://tradingview.com/script/kzp8e4X3-Monthly-Returns-in-PineScript-Strategies/                   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////var string GROUP_PERFORMANCE_TABLE = "Monthly Performance Table"mptable_on = input.bool(title="Turn On |", defval=true, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles")mptable_debug = input.bool(title="Debug Mode |", defval=false, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles")mptable_precision = input.int(title="Decimal Precision", defval=2, minval=1, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Toggles", tooltip="Decimal precision of each cell")mptable_titleColor = input.color(title="Title Cell Color", defval=#cccccc, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_titleTextColor = input.color(title="Title Text Color", defval=#363a45, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_textColor = input.color(title="Cell Text Color", defval=color.white, display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_ProfitColor = input.color(title="Year Profit Color", defval=color.new(color.green, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_LossColor = input.color(title="Year Loss Color", defval=color.new(color.red, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_BreakEvenColor = input.color(title="Year B/E Color", defval=color.new(color.white, 50), display=display.none, group=GROUP_PERFORMANCE_TABLE, inline="MPT_Colors")mptable_pageNumber = input.int(title="Page Number", defval=1, minval=1, step=1, maxval=10, display=display.none, group=GROUP_PERFORMANCE_TABLE, tooltip="Which page of results to display") - 1 // -1 is for corection for arrays. Aaray index start with 0 mptable_pageSize = input.int(title="Page Size (Rows)", defval=20, minval=1, display=display.none, group=GROUP_PERFORMANCE_TABLE, tooltip="How many rows to display") - 1  // 9 is used to show 10 rows of data due to array start from 0mptable_tableTextSize = input.string(title="Text Size", defval="Small", options=["Auto",  "Huge",  "Large", "Normal", "Small", "Tiny"], display=display.none, group=GROUP_PERFORMANCE_TABLE)// Custom function for getting table text sized based on user inputtable_text_size(_size) =>    switch _size        "Auto"   => size.auto           "Huge"   => size.huge           "Large"  => size.large          "Normal" => size.normal         "Small"  => size.small        => size.tinytableTextSize = table_text_size(mptable_tableTextSize)// Custom function for getting decimal precision based on given number // (eg. if number is > 0 but < 0.05 or < 0 and > -0.05, set precision to 3 to avoid rounding to 0 which is misleading)GetRoundingPrecision(float num) =>    if (num > 0 and num < 0.05) or (num < 0 and num > -0.05)        3    else        mptable_precision// Define an open trade's cost (used to calculate commission cost)type TradeCost    int entryTime    float entryPrice    float cost// Define a monthly/yearly return typetype StrategyReturn    float profit    float drawdown    float peak    int timestamp// Store accumulated P&L valuesvar float accumulatedMonthlyPL = 0var float accumulatedYearlyPL = 0var float bestAccumulatedMonthlyPL = 0var float bestAccumulatedYearlyPL = 0// Store drawdown valuesvar float equityPeak = strategy.initial_capitalvar float yearlyEquityHigh = 0var float currentYearlyDrawdown = 0var float yearlyMaxDrawdown = 0var float worstDrawdown = 0var float monthlyEquityHigh = 0var float currentMonthlyDrawdown = 0var float monthlyMaxDrawdown = 0var int currentDrawdownBars = 0var int maxDrawdownBars = 0// Store stat arraysvar totalDrawdownBars = array.new<int>(0)var totalDrawdowns = array.new<float>(0)// Store long & short trade countvar int totalBreakEvenTrades = 0var int totalLongTrades = 0var int totalLongTradeWins = 0var int totalShortTrades = 0var int totalShortTradeWins = 0// Store open trade commission costs in arrayvar costOfOpenTrades = array.new<TradeCost>(0)// Detect opened trade and save cost of trade (I tried many methods to get my numbers to match the Cumulative Profit list in the Strategy Tester, no idea why, but none of them worked without doing this)if strategy.opentrades != strategy.opentrades[1] and strategy.closedtrades == strategy.closedtrades[1]    costOfTrade = strategy.grossloss - strategy.grossloss[1]    costOfOpenTrades.push(TradeCost.new(strategy.opentrades.entry_time(strategy.opentrades - 1), strategy.opentrades.entry_price(strategy.opentrades - 1), costOfTrade))// Detect a closed trade// TV Documentation: Trade List's Cumulative Profit % Formula = TradeProfit / (InitialCapital + Cumulative Profit of the previous trades) * 100%if strategy.closedtrades != strategy.closedtrades[1]        // Retrieve trade cost for the closed trade    float tradeCost = 0    int removeIdx = -1    if costOfOpenTrades.size() > 0        for i = 0 to costOfOpenTrades.size() - 1            TradeCost tc = costOfOpenTrades.get(i)            if tc.entryTime == strategy.closedtrades.entry_time(strategy.closedtrades - 1) and tc.entryPrice == strategy.closedtrades.entry_price(strategy.closedtrades - 1)                tradeCost := tc.cost                removeIdx := i                 break        // Remove cost    if removeIdx != -1        costOfOpenTrades.remove(removeIdx)    // Calculate equity before trade closed (strategy.equity will not do, because it changes bar-by-bar based on open P&L not realized P&L)    float preEquity = strategy.initial_capital + strategy.netprofit[1]    // Calculate P&L + cost of this trade    float profitLoss = 0     if strategy.losstrades > strategy.losstrades[1]        profitLoss := (strategy.grossloss - (strategy.grossloss[1] - tradeCost)) * -1    else        profitLoss := strategy.grossprofit - strategy.grossprofit[1]        // Check if this was a long or short trade and if it won or lost    if strategy.position_size[1] > 0        totalLongTrades := totalLongTrades + 1        if profitLoss > 0            totalLongTradeWins := totalLongTradeWins + 1    else if strategy.position_size[1] < 0        totalShortTrades := totalShortTrades + 1        if profitLoss > 0            totalShortTradeWins := totalShortTradeWins + 1            // Check if the trade broke even    if profitLoss == 0        totalBreakEvenTrades := totalBreakEvenTrades + 1    // Calculate cumulative profit % for this trade     float cumulativeProfitPercent = (profitLoss / preEquity) * 100    // Store highest peak value of equity (we can now use strategy.equity since equity has updated to realized P&L on this bar)    if strategy.equity > equityPeak        equityPeak := strategy.equity    // Calculate total system drawdown %    float equityDD = ((strategy.equity - equityPeak) / equityPeak) * 100    if equityDD < worstDrawdown        worstDrawdown := equityDD    // Store accumulated monthly + yearly P&L    accumulatedMonthlyPL := cumulativeProfitPercent + accumulatedMonthlyPL[1]    accumulatedYearlyPL := accumulatedYearlyPL + cumulativeProfitPercent    // Save max favourable excursion for this month (ie. peak return as %)    if accumulatedMonthlyPL > bestAccumulatedMonthlyPL        bestAccumulatedMonthlyPL := accumulatedMonthlyPL    // Save max favourable excursion for this year (ie. peak return as %)    if accumulatedYearlyPL > bestAccumulatedYearlyPL        bestAccumulatedYearlyPL := accumulatedYearlyPL    // Track max equity high over current year for max yearly drawdown calculation    if accumulatedYearlyPL > yearlyEquityHigh        yearlyEquityHigh := accumulatedYearlyPL        // Check if our yearly realized equity high minus current realized equity exceeds our stored max drawdown for the year, update if necessary, and save worst drawdown    if accumulatedYearlyPL - yearlyEquityHigh < 0        currentYearlyDrawdown := accumulatedYearlyPL - yearlyEquityHigh        if currentYearlyDrawdown < yearlyMaxDrawdown            yearlyMaxDrawdown := currentYearlyDrawdown        currentDrawdownBars := currentDrawdownBars + 1        // Track max equity high over current month for max monthly drawdown calculation    if accumulatedMonthlyPL > monthlyEquityHigh        monthlyEquityHigh := accumulatedMonthlyPL        // Check if our monthly realized equity high minus current realized equity exceeds our stored max drawdown for the month, update if necessary, and save worst drawdown    if accumulatedMonthlyPL - monthlyEquityHigh < 0        currentMonthlyDrawdown := accumulatedMonthlyPL - monthlyEquityHigh        if currentMonthlyDrawdown < monthlyMaxDrawdown            monthlyMaxDrawdown := currentMonthlyDrawdown        // Debug label    if mptable_debug        string debugTip = "Equity = $" + str.tostring(strategy.equity, "#.##") +          "\nP&L=" + str.tostring(cumulativeProfitPercent) + "%" +         "\nAccumMonthlyP&L=" + str.tostring(math.round(accumulatedMonthlyPL, GetRoundingPrecision(accumulatedMonthlyPL))) + "%" +         "\nAccumYearlyP&L=" + str.tostring(math.round(accumulatedYearlyPL, GetRoundingPrecision(accumulatedYearlyPL))) + "%" +         "\nMonthlyMaxDD=" + str.tostring(math.round(monthlyMaxDrawdown, GetRoundingPrecision(monthlyMaxDrawdown))) + "%" +         "\nYearlyMaxDD=" + str.tostring(math.round(yearlyMaxDrawdown, GetRoundingPrecision(yearlyMaxDrawdown))) + "%" +         "\nTotalMaxDD=" + str.tostring(math.round(worstDrawdown, GetRoundingPrecision(worstDrawdown))) + "%" +         "\nCurrentDDBars=" + str.tostring(currentDrawdownBars) +         "\nMaxDDBars=" + str.tostring(maxDrawdownBars) +         "\nTotalBreakEven=" + str.tostring(totalBreakEvenTrades) +         "\nTotalLongs=" + str.tostring(totalLongTrades) +         "\nTotalLongWins=" + str.tostring(totalLongTradeWins) +         "\nTotalShorts=" + str.tostring(totalShortTrades) +         "\nTotalShortWins=" + str.tostring(totalShortTradeWins)        label.new(bar_index, high + (high * 0.01), "P&L " + str.tostring(math.round(cumulativeProfitPercent, GetRoundingPrecision(cumulativeProfitPercent))) + "%", tooltip=debugTip, textcolor=color.white)// Calculate drawdown since last equity high (NOT max drawdown, just the current max DD since we were out of DD)float t_equityDD = ((strategy.equity - equityPeak) / equityPeak) * 100var float currentMaxDrawdownSinceLast = 0// Update Max Drawdown bar count and current DD if equity is under water, check isconfirmed to prevent double-counting bars with recalc_on_order_fills onif strategy.equity < equityPeak and barstate.isconfirmed    currentDrawdownBars := currentDrawdownBars + 1    if currentDrawdownBars > maxDrawdownBars        maxDrawdownBars := currentDrawdownBars    if t_equityDD < currentMaxDrawdownSinceLast        currentMaxDrawdownSinceLast := t_equityDDelse    if currentDrawdownBars > 0        totalDrawdownBars.push(currentDrawdownBars)        totalDrawdowns.push(currentMaxDrawdownSinceLast)    currentDrawdownBars := 0    currentMaxDrawdownSinceLast := 0// Prepare arrays to store Yearly and Monthly P&Lsvar monthlyReturns = array.new<StrategyReturn>(0)var yearlyReturns = array.new<StrategyReturn>(0)var bool firstEntryTime = false// Retrieve entry time of initial entry in open positionif not firstEntryTime and strategy.opentrades.entry_time(0)    firstEntryTime := true// Detect new month and yearnew_month = month(time) != month(time[1])new_year = year(time) != year(time[1])// Detect a new month and store its return profileif not barstate.isfirst and new_month and firstEntryTime or barstate.islastconfirmedhistory    StrategyReturn mr = StrategyReturn.new(accumulatedMonthlyPL, monthlyMaxDrawdown, bestAccumulatedMonthlyPL, time[1]) // time)    monthlyReturns.push(mr)    accumulatedMonthlyPL := 0    monthlyMaxDrawdown := 0    monthlyEquityHigh := 0    currentMonthlyDrawdown := 0    bestAccumulatedMonthlyPL := 0    // Detect a new year and reset tracking variablesif not barstate.isfirst and new_year and firstEntryTime or barstate.islastconfirmedhistory    StrategyReturn yr = StrategyReturn.new(accumulatedYearlyPL, yearlyMaxDrawdown, bestAccumulatedYearlyPL, time[1])    yearlyReturns.push(yr)    accumulatedYearlyPL := 0    yearlyMaxDrawdown := 0    yearlyEquityHigh := 0    currentYearlyDrawdown := 0    bestAccumulatedYearlyPL := 0// DEBUG codebgcolor(mptable_debug and new_month ? color.lime : na, title="New Month", display=display.none)bgcolor(mptable_debug and new_year ? color.red : na, title="New Year", display=display.none)// END DEBUG CODE// Define Monthly P&L Table    var table performance_table = table(na)//Adjust mptable_pageSize if the years are less than the mptable_pageSizeif yearlyReturns.size() < mptable_pageSize    mptable_pageSize := yearlyReturns.size()// Caluclate the start and end of page to displaystartIndex = math.max(math.min(yearlyReturns.size() - 1, yearlyReturns.size() - 1 - (mptable_pageSize + 1) * mptable_pageNumber), mptable_pageSize - 1)endIndex = math.max(startIndex - mptable_pageSize, 0)mptable_pageSize := endIndex <= mptable_pageSize ? endIndex : mptable_pageSize// If this is the last bar on our chart, display the performance tablevar int EXTRA_STAT_ROWS = 5 // This ensures table includes enough rows for CAGR etcif mptable_on and monthlyReturns.size() > 0 and barstate.islastconfirmedhistory    // Create table (100 rows = 100 years of data, should be plenty for all markets!)    performance_table := table.new(position.bottom_right, columns=17, rows=yearlyReturns.size() + EXTRA_STAT_ROWS, border_width=1)    // Set column headers    performance_table.cell(0, 0, "Year", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(1, 0, "Jan", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(2, 0, "Feb", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(3, 0, "Mar", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(4, 0, "Apr", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(5, 0, "May", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(6, 0, "Jun", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(7, 0, "Jul", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(8, 0, "Aug", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(9, 0, "Sep", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(10, 0, "Oct", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(11, 0, "Nov", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(12, 0, "Dec", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(13, 0, "TOTAL", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    performance_table.cell(14, 0, "MaxDD", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)    // Set yearly values    for year_index = startIndex to yearlyReturns.size() == 0 ? na : endIndex                // Get yearly return for this loop, set year number in first column, determine color of cell        StrategyReturn yearlyReturn = yearlyReturns.get(year_index)        // Set year title and determine color        performance_table.cell(0, year_index + 1, str.tostring(year(yearlyReturn.timestamp)), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_size=tableTextSize)        color y_color = yearlyReturn.profit > 0 ? mptable_ProfitColor : yearlyReturn.profit == 0 ? mptable_BreakEvenColor : mptable_LossColor        // Populate yearly cell values        string yearlyTip = "MaxDD: " + str.tostring(math.round(yearlyReturn.drawdown, GetRoundingPrecision(yearlyReturn.drawdown))) + "%" +             "\nMFE: " + str.tostring(math.round(yearlyReturn.peak, GetRoundingPrecision(yearlyReturn.peak))) + "%"        performance_table.cell(13, year_index + 1, (yearlyReturn.profit > 0 ? "+" : "") + str.tostring(math.round(yearlyReturn.profit, GetRoundingPrecision(yearlyReturn.profit))) + "%", bgcolor=y_color, text_color=color.white, text_size=tableTextSize, tooltip=yearlyTip)        performance_table.cell(14, year_index + 1, str.tostring(math.round(yearlyReturn.drawdown, GetRoundingPrecision(yearlyReturn.drawdown))) + "%", bgcolor=mptable_BreakEvenColor, text_color=color.white, text_size=tableTextSize)        // Set monthly values        for month_index = 0 to monthlyReturns.size() - 1            // Get monthly return for this loop, get current year for this loop, then calculate the corresponding table column and row            StrategyReturn monthlyReturn = monthlyReturns.get(month_index)            int yearOfMonth = year(monthlyReturn.timestamp)            int monthCol = month(monthlyReturn.timestamp)                        // populate monthly profit only if the years of the yearly return match with the monthly return.             if yearOfMonth == year(yearlyReturn.timestamp)                 // Determine color for monthly P&L                color m_color = monthlyReturn.profit > 0 ? color.new(mptable_ProfitColor, color.t(mptable_ProfitColor) + 20) : monthlyReturn.profit == 0 ? color.new(mptable_BreakEvenColor, color.t(mptable_BreakEvenColor) + 20) : color.new(mptable_LossColor, color.t(mptable_LossColor) + 20)                                // Set monthly P&L cell                string monthlyTip = "MaxDD: " + str.tostring(math.round(monthlyReturn.drawdown, GetRoundingPrecision(monthlyReturn.drawdown))) + "%" +                     "\nMFE: " + str.tostring(math.round(monthlyReturn.peak, GetRoundingPrecision(monthlyReturn.peak))) + "%"                performance_table.cell(monthCol, year_index + 1, str.tostring(math.round(monthlyReturn.profit, GetRoundingPrecision(monthlyReturn.profit))), bgcolor=m_color, text_color=color.white, text_size=tableTextSize, tooltip=monthlyTip)    float percentReturn = (strategy.netprofit / strategy.initial_capital) * 100    float cagr = (math.pow((strategy.netprofit + strategy.initial_capital) / strategy.initial_capital, 1 / yearlyReturns.size()) - 1) * 100    float mar = cagr / math.abs(worstDrawdown)    lastMonthRowIndex = startIndex < 5 ? 5 : startIndex    // Populate table data    float totalWinRate = (strategy.wintrades / strategy.closedtrades) * 100    float longWinRate = nz((totalLongTradeWins / totalLongTrades) * 100)    float shortWinRate = nz((totalShortTradeWins / totalShortTrades) * 100)    string returnTip = "Based on a total of " + str.tostring(strategy.closedtrades) + " trades" +         "\nWin Rate = " + str.tostring(math.round(totalWinRate, GetRoundingPrecision(totalWinRate))) + "%" +         "\nLong Trades = " + str.tostring(totalLongTrades) + " (Win " + str.tostring(math.round(longWinRate, GetRoundingPrecision(longWinRate))) + "%)" +         "\nShort Trades = " + str.tostring(totalShortTrades) + " (Win " + str.tostring(math.round(shortWinRate, GetRoundingPrecision(shortWinRate))) + "%)"    performance_table.cell(15, lastMonthRowIndex, "Return: " + (percentReturn > 0 ? "+" : "") + str.tostring(math.round(percentReturn, GetRoundingPrecision(percentReturn))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip=returnTip)    performance_table.cell(15, lastMonthRowIndex - 1, "MAR: " + str.tostring(mar, "#.##"), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Measure of return adjusted for risk: CAGR divided by Max Drawdown. Indicates how comfortable the system might be to trade. Higher than 0.5 is ideal, 1.0 and above is very good, and anything 3.0 or above should be considered suspicious.")    performance_table.cell(15, lastMonthRowIndex - 2, "DD Bars: " + str.tostring(maxDrawdownBars), bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Average Drawdown Bars: " + str.tostring(totalDrawdownBars.avg(), "#.#") + "\n\nThis is how many bars it took to recover the longest drawdown (note: this is different to the MAX drawdown, and represents time drawdown)")    performance_table.cell(15, lastMonthRowIndex - 3, "MaxDD: " + str.tostring(math.round(worstDrawdown, GetRoundingPrecision(worstDrawdown))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Average Drawdown: " + str.tostring(totalDrawdowns.avg(), "#.##") + "%\n\nThis number is different to the Strategy Tester because this number is based on closed trade equity while the Tester's MaxDD is based on open equity.")    performance_table.cell(15, lastMonthRowIndex - 4, "CAGR: " + (cagr > 0 ? "+" : "") + str.tostring(math.round(cagr, GetRoundingPrecision(cagr))) + "%", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="Compounded annual growth rate")    performance_table.cell(15, lastMonthRowIndex - 5, "REALIZED P&L", bgcolor=mptable_titleColor, text_color=mptable_titleTextColor, text_font_family=font.family_monospace, text_size=tableTextSize, tooltip="These numbers are based on Realized equity (closed trades)")// } END MONTHLY TABLE/////////// END OF PERFORMANCE TABLE CODE. ///////////