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
| Year | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | TOTAL | MaxDD | REALIZED P&L |
| 2024 | 4.28 | 12 | 3.19 | +19.47% | -0.77% | CAGR: +7.92% | |||||||||
| 2025 | 3.91 | -13.66 | 7.71 | 0 | 5.94 | -2.39 | 6.32 | -0.85 | -4.78 | -2.39 | -3.64 | 0 | -3.83% | -13.66% | MaxDD: -13.61% |
| 2026 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1.16 | 8.04 | 1.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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Parameters | |||
| MA 1 LengthLong-term MA | 200 | int · step 10 | ma1 |
| MA 2 LengthShort-term MA | 10 | int · step 10 | ma2 |
| Stop Loss PercentFailsafe Stop Loss Percent Decline | 0.10 | float · step 0.1 | stopPrice stopCondition |
| Exit On Lower CloseWait for a lower-close before exiting above MA2 | false | bool | sellCondition |
| Time Filter | |||
| Start FilterStart date & time to begin searching for setups | timestamp("01 Jan 1995 13:30 +0000") | time | f_dateFilter |
| End FilterEnd date & time to stop searching for setups | timestamp("1 Jan 2099 19:30 +0000") | time | f_dateFilter |
| Monthly Performance Table | |||
| Turn On | | true | bool | line 288 |
| Debug Mode | | false | bool | line 213 New Month New Year |
| Decimal PrecisionDecimal precision of each cell | 2 | int · min 1 | line 90 |
| Title Cell Color | #cccccc | color | line 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 | #363a45 | color | line 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 Color | color.white | color | unused |
| Year Profit Color | color.new(color.green, 50) | color | y_color m_color |
| Year Loss Color | color.new(color.red, 50) | color | y_color m_color |
| Year B/E Color | color.new(color.white, 50) | color | y_color m_color line 319 |
| Page NumberWhich page of results to display | 1 | int · min 1 · max 10 · step 1 | startIndex |
| Page Size (Rows)How many rows to display | 20 | int · min 1 | startIndex endIndex line 280 |
| Text Size | Small | string · 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
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | buyCondition | On | 41 |
| Close Long | sellCondition or stopCondition | On | 46 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +25.7% | +102.5% | 36 | 64% | 1.50 | 20.2% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +6.6% | +5.5% | 52 | 69% | 1.42 | 6.2% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +0.2% | +9.8% | 34 | 74% | 1.00 | 42.2% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +13.3% | +8.4% | 60 | 77% | 1.45 | 10.1% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −26.6% | +16.7% | 32 | 66% | 0.76 | 41.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +4.5% | +21.5% | 46 | 63% | 1.14 | 10.8% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −7.5% | +148.3% | 38 | 63% | 0.92 | 31.8% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +9.5% | +17.1% | 38 | 71% | 1.64 | 8.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.
| MA 2 Length ↓ · MA 1 Length → | 100 | 120 | 140 | 170 | 200 | 240 | 280 | 340 |
|---|---|---|---|---|---|---|---|---|
| 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% |
| MA 2 Length ↓ · MA 1 Length → | 100 | 120 | 140 | 170 | 200 | 240 | 280 | 340 |
|---|---|---|---|---|---|---|---|---|
| 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 20 | 70% | $32,190.00 |
| Sideways market | 15 | 53% | −$7,411.69 |
| Falling market | 1 | 100% | $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.
All 36 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 24 Oct 2024 66,668.60 | 25 Oct 2024 68,198.30 | 1 | $2,294.35 |
| long | 26 Oct 2024 66,698.30 | 28 Oct 2024 68,021.70 | 2 | $2,029.62 |
| long | 3 Nov 2024 69,374.70 | 7 Nov 2024 75,572.00 | 4 | $9,319.25 |
| long | 26 Nov 2024 93,010.00 | 28 Nov 2024 95,863.10 | 2 | $3,486.02 |
| long | 3 Dec 2024 95,840.60 | 4 Dec 2024 95,849.70 | 1 | $11.08 |
| long | 10 Dec 2024 97,276.50 | 12 Dec 2024 101,125.00 | 2 | $4,634.38 |
| long | 19 Dec 2024 100,204.00 | 26 Dec 2024 99,429.60 | 7 | −$941.12 |
| long | 27 Dec 2024 95,791.60 | 3 Jan 2025 96,984.80 | 7 | $1,505.10 |
| long | 9 Jan 2025 95,060.60 | 15 Jan 2025 96,560.90 | 6 | $1,930.73 |
| long | 27 Jan 2025 102,620.00 | 30 Jan 2025 103,733.00 | 3 | $1,348.08 |
| long | 1 Feb 2025 102,430.00 | 13 Feb 2025 97,870.00 | 12 | −$5,591.76 |
| long | 14 Feb 2025 96,608.10 | 15 Feb 2025 97,500.50 | 1 | $1,108.63 |
| long | 17 Feb 2025 96,118.10 | 21 Feb 2025 98,305.00 | 4 | $2,756.05 |
| long | 22 Feb 2025 96,182.00 | 27 Feb 2025 84,250.10 | 5 | −$15,369.30 |
| long | 28 Feb 2025 84,708.60 | 3 Mar 2025 94,270.00 | 3 | $12,249.20 |
| long | 4 Mar 2025 86,221.20 | 6 Mar 2025 90,606.00 | 2 | $6,141.89 |
| long | 8 Mar 2025 86,801.70 | 11 Mar 2025 78,595.90 | 3 | −$11,997.80 |
| long | 13 Mar 2025 83,680.10 | 16 Mar 2025 84,338.40 | 3 | $904.03 |
| long | 5 May 2025 94,277.60 | 7 May 2025 96,834.00 | 2 | $3,140.49 |
| long | 18 May 2025 103,127.00 | 19 May 2025 106,454.00 | 1 | $3,838.48 |
| long | 29 May 2025 107,782.00 | 8 Jun 2025 105,552.00 | 10 | −$2,540.26 |
| long | 13 Jun 2025 105,672.00 | 24 Jun 2025 105,334.00 | 11 | −$384.44 |
| long | 2 Jul 2025 105,681.00 | 3 Jul 2025 108,850.00 | 1 | $3,593.93 |
| long | 20 Jul 2025 117,840.00 | 23 Jul 2025 119,954.00 | 3 | $2,215.37 |
| long | 26 Jul 2025 117,614.00 | 28 Jul 2025 119,416.00 | 2 | $1,924.80 |
| long | 29 Jul 2025 118,062.00 | 8 Aug 2025 117,472.00 | 10 | −$638.03 |
| long | 16 Aug 2025 117,342.00 | 23 Aug 2025 116,936.00 | 7 | −$439.36 |
| long | 24 Aug 2025 115,438.00 | 3 Sep 2025 111,240.00 | 10 | −$4,601.41 |
| long | 20 Sep 2025 115,632.00 | 30 Sep 2025 114,312.00 | 10 | −$1,392.32 |
| long | 11 Oct 2025 112,774.00 | 24 Oct 2025 110,078.00 | 13 | −$2,881.87 |
| long | 30 Oct 2025 110,021.00 | 11 Nov 2025 106,011.00 | 12 | −$4,288.38 |
| long | 31 Aug 2026 77,682.00 | 1 Sep 2026 78,581.30 | 1 | $1,312.38 |
| long | 2 Sep 2026 77,439.00 | 4 Sep 2026 81,270.40 | 2 | $5,673.77 |
| long | 9 Sep 2026 78,455.80 | 19 Sep 2026 80,883.90 | 10 | $3,724.64 |
| long | 29 Sep 2026 83,500.00 | 2 Oct 2026 84,880.10 | 3 | $2,050.65 |
| long | 8 Oct 2026 83,321.80 | 21 Oct 2026 83,028.10 | 13 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Monthly Strategy Performance Table this page | — | v5 strategy | +25.7% | 36 | 20.2% |
| Follow the Crypto Shorts by xtradernet | sma | v4 strategy | No trades on this market | ||
| buy down and sell high trend 200 sma and ma cross by willi130503 | sma | v4 strategy | No trades on this market | ||
| Mayer Multiple Strategy by xtradernet | sma | v4 strategy | No trades on this market | ||
| Moving Average Cross Strategy early Closing by Geduldtrader | sma | v4 strategy | +73.8% | 20 | 151.5% |
| MFI Simple Strategy by OztheWoz | sma | v5 strategy | −0.2% | 28 | 3.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
VerifiedNothing 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 549 ms | With a workaround 1,000 bars in 109 ms | Not measured |
| PineTS | Not tested | Not tested | Not 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. ///////////