Pine Script v4 · Strategy
Monthly MA Close
A Pine Script v4 strategy built on EMA or SMA (close, 8). 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 no commission. 13 settings; defaults include Ticker MA SPY, Time MA (W, D, [min]) M and Period MA 8.
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 MA Close repaint?
- Yes
- At least one pattern in the source can repaint: higher-timeframe data.
- How did Monthly MA Close do on BTCUSDT 1D with default settings?
- +106.31%
- From 26 Jan 2024 to 21 Oct 2026, over 1 closed trade, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Monthly MA Close be converted to Pine Script v5?
- No
- The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
- What alerts does Monthly MA Close have?
- 2
- Bullish; Bearish.
- Does Monthly MA Close use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
BTCUSDT · 1D · default settings
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
Needs SPY M data, not available: not a Binance spot market Values that depend on it are empty on this chart.
- Net profit
- +106.31%
- $106,310.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 1
- 1 won · 0 lost
- Profitable
- 100.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 3.19%
- −$6,583.24
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long position was still open at the last bar. 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
“Show Date Range” 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
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
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.
-
Note
Uses an argument v6 removed
when = on line 58, 59. The upgraded version below moves each call inside an if block.
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames security → request.security, ema → ta.ema, sma → ta.sma.
- 2 strategy calls use the when = argument (line 58, 59). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
DiffersTrades differ: 1 before, 1 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 8: security → request.security
- Line 22: security → request.security
- Line 34: input(type = input.symbol) → input.symbol()
- Line 35: input(type = input.string) → input.string()
- Line 37: ema → ta.ema
10 more edits
- Line 37: sma → ta.sma
- Line 38: ema → ta.ema
- Line 38: sma → ta.sma
- Line 42: input(type = input.bool) → input.bool()
- Line 43: input(type = input.integer) → input.int()
- Line 44: input(type = input.integer) → input.int()
- Line 45: input(type = input.integer) → input.int()
- Line 46: input(type = input.integer) → input.int()
- Line 47: input(type = input.integer) → input.int()
- Line 48: input(type = input.integer) → input.int()
⋯// © universique-//@version=4+//@version=5strategy("Monthly MA Close ", shorttitle="MMAC", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)⋯// Function to securely and simply call `security()` so that it never repaints and never looks ahead.-f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)+f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)//sec10 = f_secureSecurity(syminfo.tickerid, higherTf, data)⋯ // Dependency: f_resInMinutes().- security(syminfo.tickerid, _res, f_resInMinutes())+ request.security(syminfo.tickerid, _res, f_resInMinutes())// —————————— Determine if current timeframe is smaller that higher timeframe selected in Inputs.⋯ticker = input(false, title="Other ticker MA")-tic_ma = input(title="Ticker MA", type=input.symbol, defval="SPY")+tic_ma = input.symbol(title="Ticker MA", defval="SPY")-res_ma = input(title="Time MA (W, D, [min])", type=input.string, defval="M")+res_ma = input.string(title="Time MA (W, D, [min])", defval="M")len_ma = input(8, minval=1, title="Period MA")-ma_cus = exponential?f_secureSecurity(tic_ma, res_ma, ema(close,len_ma)) : f_secureSecurity(tic_ma, res_ma, sma(close,len_ma))+ma_cus = exponential?f_secureSecurity(tic_ma, res_ma, ta.ema(close,len_ma)) : f_secureSecurity(tic_ma, res_ma, ta.sma(close,len_ma))-ma_long = exponential?f_secureSecurity(syminfo.tickerid, res_ma, ema(close,len_ma)) : f_secureSecurity(syminfo.tickerid, res_ma, sma(close,len_ma))+ma_long = exponential?f_secureSecurity(syminfo.tickerid, res_ma, ta.ema(close,len_ma)) : f_secureSecurity(syminfo.tickerid, res_ma, ta.sma(close,len_ma))cl1 = f_secureSecurity(syminfo.tickerid, 'M', close)⋯// Input Backtest Range-showDate = input(defval = false, title = "Show Date Range", type = input.bool)+showDate = input.bool(defval = false, title = "Show Date Range")-fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)+fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)-fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)+fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)-fromYear = input(defval = 1995, title = "From Year", type = input.integer, minval = 1850)+fromYear = input.int(defval = 1995, title = "From Year", minval = 1850)-thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)+thruMonth = input.int(defval = 1, title = "Thru Month", minval = 1, maxval = 12)-thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)+thruDay = input.int(defval = 1, title = "Thru Day", minval = 1, maxval = 31)-thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1850)+thruYear = input.int(defval = 2112, title = "Thru Year", minval = 1850)// Funcion Example⋯Clean v5
VerifiedSame 1 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 31: input() → input.bool()
- Line 32: input() → input.bool()
- Line 33: input() → input.bool()
- Line 36: input() → input.int()
- Line 58: when = window() and bullish_cross → if block
- Line 59: when = window() and bearish_cross → if block
⋯// Input-switch1=input(true, title="Show MA")+switch1=input.bool(true, title="Show MA")-exponential = input(true, title="Exponential MA")+exponential = input.bool(true, title="Exponential MA")-ticker = input(false, title="Other ticker MA")+ticker = input.bool(false, title="Other ticker MA")tic_ma = input.symbol(title="Ticker MA", defval="SPY")res_ma = input.string(title="Time MA (W, D, [min])", defval="M")-len_ma = input(8, minval=1, title="Period MA")+len_ma = input.int(8, minval=1, title="Period MA")ma_cus = exponential?f_secureSecurity(tic_ma, res_ma, ta.ema(close,len_ma)) : f_secureSecurity(tic_ma, res_ma, ta.sma(close,len_ma))⋯// Strategy-strategy.entry("long", strategy.long, when = window() and bullish_cross)+if window() and bullish_cross+ strategy.entry("long", strategy.long)-strategy.close("long", when = window() and bearish_cross)+if window() and bearish_cross+ strategy.close("long")// Output⋯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: 1 before, 1 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.
⋯// © universique-//@version=5+//@version=6strategy("Monthly MA Close ", shorttitle="MMAC", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)⋯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 |
|---|---|---|---|
| Show MA | true | bool | plot |
| Exponential MA | true | bool | ma_cus ma_long |
| Other ticker MA | false | bool | bullish_cross bearish_cross |
| Ticker MA | SPY | symbol | ma_cus cl2 |
| Time MA (W, D, [min]) | M | string | ma_cus ma_long |
| Period MA | 8 | int · min 1 | ma_cus ma_long |
| Show Date Range | false | bool | unused |
| From Month | 1 | int (written input.integer) · min 1 · max 12 | start |
| From Day | 1 | int (written input.integer) · min 1 · max 31 | start |
| From Year | 1995 | int (written input.integer) · min 1850 | start |
| Thru Month | 1 | int (written input.integer) · min 1 · max 12 | finish |
| Thru Day | 1 | int (written input.integer) · min 1 · max 31 | finish |
| Thru Year | 2112 | int (written input.integer) · min 1850 | finish |
What it calculates
- EMA / SMA (
ema,ta.emain v5)close, Period MA (8)ma_cus · line 37 - EMA / SMA (
ema,ta.emain v5)close, Period MA (8)ma_long · line 38
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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | window() and bullish_cross | On | 58 |
| Close long | window() and bearish_cross | On | 59 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| Bullish | alertcondition | Bullish | 63 |
| Bearish | alertcondition | Bearish | 64 |
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
- CheckHigher-timeframe data1 security call(s) use lookahead_on (line 8). Without a [1] offset this reads future bars in history.
- 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
Not run on other markets: the script requests SPY M, and that data is not available here (not a Binance spot market). Its results would rest on empty values.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 0 | — | $0.00 |
| Sideways market | 1 | 100% | $106,310.00 |
| Falling market | 0 | — | $0.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
0.0%
The 95th percentile of the worst drawdown when the same 1 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 0.0% to 0.0%; the tick is what actually happened, 0.0%. Order luck alone moves it this much.
All 1 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 27 Jan 2024 41,823.50 | 2 Dec 2025 86,286.00 | 675 | $106,310.00 |
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 MA Close this page | — | v4 strategy | +106.3% | 1 | 3.2% |
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.7% |
| 4-Hour Stochastic EMA Trend by slymnturkoglu | ema sma | v4 strategy | No trades on this market | ||
| 4X EMA and volume strategy by SoftKill21 | ema sma | v4 strategy | +1.8% | 3 | 25.8% |
| Simple Momentum Strategy Based on SMA, EMA and Volume by slip_stream | sma ema | v4 strategy | +7.4% | 18 | 27.4% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 15 ms | With a workaround 1,000 bars in 60 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“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. PineTS runs Pine Script v5 and v6 only.
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/// © universique//@version=4strategy("Monthly MA Close ", shorttitle="MMAC", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)//MAY 6 2020 18:00// No repaint function // Function to securely and simply call `security()` so that it never repaints and never looks ahead.f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)//sec10 = f_secureSecurity(syminfo.tickerid, higherTf, data)// ————— Converts current chart resolution into a float minutes value.f_resInMinutes() => _resInMinutes = timeframe.multiplier * ( timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)// ————— Returns the float minutes value of the string _res.f_tfResInMinutes(_res) => // _res: resolution of any TF (in "timeframe.period" string format). // Dependency: f_resInMinutes(). security(syminfo.tickerid, _res, f_resInMinutes())// —————————— Determine if current timeframe is smaller that higher timeframe selected in Inputs.// Get higher timeframe in minutes.//higherTfInMinutes = f_tfResInMinutes(higherTf)// Get current timeframe in minutes.currentTfInMinutes = f_resInMinutes()// Compare current TF to higher TF to make sure it is smaller, otherwise our plots don't make sense.//chartOnLowerTf = currentTfInMinutes < higherTfInMinutes// Inputswitch1=input(true, title="Show MA")exponential = input(true, title="Exponential MA")ticker = input(false, title="Other ticker MA")tic_ma = input(title="Ticker MA", type=input.symbol, defval="SPY")res_ma = input(title="Time MA (W, D, [min])", type=input.string, defval="M")len_ma = input(8, minval=1, title="Period MA")ma_cus = exponential?f_secureSecurity(tic_ma, res_ma, ema(close,len_ma)) : f_secureSecurity(tic_ma, res_ma, sma(close,len_ma))ma_long = exponential?f_secureSecurity(syminfo.tickerid, res_ma, ema(close,len_ma)) : f_secureSecurity(syminfo.tickerid, res_ma, sma(close,len_ma))cl1 = f_secureSecurity(syminfo.tickerid, 'M', close)cl2 = f_secureSecurity(tic_ma, 'M', close)// Input Backtest RangeshowDate = input(defval = false, title = "Show Date Range", type = input.bool)fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)fromYear = input(defval = 1995, title = "From Year", type = input.integer, minval = 1850)thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1850)// Funcion Examplestart = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start windowfinish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish windowwindow() => time >= start and time <= finish ? true : false // create function "within window of time"// Calculationbullish_cross = ticker?cl2>ma_cus : cl1>ma_longbearish_cross = ticker?cl2<ma_cus : cl1<ma_longMAColor = bullish_cross ? color.green : bearish_cross ? color.red : color.orange// Strategystrategy.entry("long", strategy.long, when = window() and bullish_cross)strategy.close("long", when = window() and bearish_cross)// Outputplot(switch1?ma_long:na,color = MAColor,linewidth=4)// Alertsalertcondition(bullish_cross, title='Bullish', message='Bullish')alertcondition(bearish_cross, title='Bearish', message='Bearish')