Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Risk Management and Positionsize - MACD example

A Pine Script v5 strategy built on SMA or Linreg or EMA or WMA, EMA (src, 55) and SMA (MACD_Value_HTF, dynamicSmoothing). It has 4 order rules, 2 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays 0.03% commission. 13 settings; defaults include Initial Balance 10000, Margin Factor -0.5 and Quantity Contracts 3.5.

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 Risk Management and Positionsize - MACD example repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did Risk Management and Positionsize - MACD example do on BTCUSDT 1D with default settings?
Not measured
It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its entry conditions never all held on this data. It closed no trades on the other markets either. A backtest, not investment advice.
Does Risk Management and Positionsize - MACD example run in Pine Script v6?
Not tested
Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download.
Does Risk Management and Positionsize - MACD example use a stop loss?
No
Every exit waits for a signal; nothing limits a losing trade before it fires.
Does Risk Management and Positionsize - MACD example run in Zeal Terminal?
Yes
It compiles in 48 ms and runs 1,000 bars in 81 ms, in the browser.

BTCUSDT · 1D · default settings

  • Zero Line
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctZero Line$10,000$20,253Equity from $10,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. 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. The live re-run is not offered here: the script requests BTCUSDT 30, which this page cannot load in your browser.

Needs BTCUSDT 30 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.

Net profit
0.00%
$0.00
Buy and hold
+102.5%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
0.00%
$0.00

One run with the author's default settings, $10,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

    No stop loss

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

  • Note

    1 setting has no label

    In the settings dialog MarginFactor (line 26) shows an empty name. The labels on this page come from the variable names.

  • Note

    Uses an argument v6 removed

    when = on line 176, 179. The upgraded version below moves each call inside an if block.

Settings

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

SettingDefaultType and rangeFeeds
Risk Management
Initial Balancestarting capital10000float · min 1 · max 1000000 · step 1000EquityCurrent
qty based on equity %true turns on MarginFactor based on equity, false gives fixed qty for positionsizetrueboolQtyTrade
Margin Factor (no label in the script)Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument-0.5float · min - 0.9 · max 100 · step 0.1QtyEquity
Quantity ContractsMargin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument3.5float · min 0 · max 1000000 · step 0.01QtyTrade
Higher Time Frame MACD Settings
MA typeEMAstring · options ["EMA","DEMA","TEMA","SMA","WMA", "HMA"]fast_ma slow_ma signal
Higher Time Frame30timeframeMACD_Value_HTF SIGNAL_Value_HTF higherTFMinutes
Fast MA Length11int · min 1fast_ma
Slow MA Length26int · min 1slow_ma
Length Signal MA9int · min 1signal
Plot Signal?trueboolLong Condition Short Condition
Higher Time Frame Trend
Higher Time Frame1DtimeframeMA_Value_HTF higherTFMinutes_trend
Length MANumber of bars used to measure trend on higher timeframe chart55int · min 1result e mg MAtrend
MA type for HTF trendEMAstring · options ["EMA","DEMA","TEMA","SMA","WMA", "HMA", "McGinley"]MAtrend

What it calculates

  • SMA / Linreg / EMA / WMAta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1result · line 129
  • EMAsrc, Length MA (55)e · line 145
  • SMAMACD_Value_HTF, dynamicSmoothingMACD_Value_HTF_Smooth · line 113
  • SMASIGNAL_Value_HTF, dynamicSmoothingSIGNAL_Value_HTF_Smooth · line 114
  • SMAHIST_Value_HTF, dynamicSmoothingHIST_Value_HTF_Smooth · line 115
  • EMAsrc, Length MA (55)mg · line 156
  • SMAMA_Value_HTF, dynamicSmoothing_trendMA_Value_Smooth · line 167

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.

lengthLength MAsetting · 55InitialBalanceInitial Balancesetting · 10000closecloseprice dataMarginFactorMargin Factorsetting · -0.5QtyNrQuantity Contractssetting · 3.5MA_TypeMA typesetting · EMAfastlengthFast MA Lengthsetting · 11slowlengthSlow MA Lengthsetting · 26signallengthLength Signal MAsetting · 9TimeFrame_MACDHigher Time Framesetting · 30MA_Type_trendMA type for HTF trendsetting · EMATimeFrame_TrendHigher Time Framesetting · 1DresultSMA / Linreg / EMA / WMA→ resulteEMA→ eMACD_Value_HTF_SmoothSMA→ MACD_Value_HTF_SmoothSIGNAL_Value_HTF_SmoothSMA→ SIGNAL_Value_HTF_SmoothHIST_Value_HTF_SmoothSMA→ HIST_Value_HTF_SmoothmgEMA→ mgMA_Value_SmoothSMA→ MA_Value_SmoothEquityCurrentEquityCurrentvalueQtyEquityQtyEquityvalueQtyTradeQtyTradevaluefast_mafast_mavalueslow_maslow_mavaluemacdmacdvaluesignalsignalvaluehisthistvalueMACD_Value_HTF, SIGNAL_Value_HTF, higherTFMinutesMACD_Value_HTF · SIGNAL…3 valuesHIST_Value_HTFHIST_Value_HTFvaluemultiplier, currentTFMinutesmultiplier · currentTFM…2 valuesdynamicSmoothingdynamicSmoothingvalueMAtrendMAtrendvalueMA_Value_HTFMA_Value_HTFvaluehigherTFMinutes_trendhigherTFMinutes_trendvaluedynamicSmoothing_trenddynamicSmoothing_trendvalueLongConditionLongConditionconditionShortConditionShortConditionconditionUPUPconditionDOWNDOWNconditionentry:LongOpen Longstrategy.entryclose_all:close_all strategy.close_allentry:ShortOpen Shortstrategy.entryhline:183hlinehlineplot:184Histogramplotplot:185Signalplotplot:186MACDplotplot:187Long Conditionplotplot:188Short Conditionplotplotshape:189plotshapeplotshapeplotshape:190plotshapeplotshape

Order rules

OrderFires whenBy defaultLine
Open Long longLongCondition and UP == trueOn175
Close strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth)On176
Open Short shortShortCondition and DOWN == trueOn178
Close strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth)On179

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 measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • ClearHigher-timeframe data3 request.security call(s), none with lookahead on.
  • 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 BTCUSDT 30, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.

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
Risk Management and Positionsize - MACD example this page—v5 strategy0.0%00.0%
MACD ReLoaded STRATEGY by KivancOzbilgicema linreg wma smav5 strategy+7.8%315.1%
Linear Regression MA - Strategy by lazy_capitalistsma linreg emav5 strategy−1,240.4%10318.7%
Forex SWING Trader by SoftKill21wma ema smav4 strategyNo trades on this market
DRSI DMA Scalping Strategy No Repaint by allenlksma wma emav4 strategy−99.5%44137.7%
Profit Maximizer PMax Strategy - Long-Short by melihtunasma ema linregv4 strategy+16.2%427.8%

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.

  • 2 strategy calls use the when = argument (line 176, 179). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 176: when = strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) → if block
  • Line 179: when = strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) → if block
⋯    strategy.entry("Long", strategy.long, qty = QtyTrade)-strategy.close_all(when = strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))   +if strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth)+    strategy.close_all()   if ShortCondition and DOWN == true    strategy.entry("Short", strategy.short, qty = QtyTrade)-strategy.close_all(when = strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))   +if strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth)+    strategy.close_all()   /////////////////////////////////////////////////⋯

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯////////////////////////////////////////////////////////////////////////////////////////-//@version=5+//@version=6strategy(title = "Risk Management and Positionsize - MACD example", shorttitle =  "Risk Management", overlay=false, ⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 48 msWith a workaround 1,000 bars in 81 msNot measured
PineTSNot testedNot testedNot 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.

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/// © Harrocop////////////////////////////////////////////////////////////////////////////////////////// This is a basis position sizing tool to play around with marginfactor or quantity Contracts.// It gives traders the possibility to quickly adjust settings to test backtesting outcomes.// The Strategy comes with the following.// - MACD Signalline based on Higher Time Frame Settings.// - Filter based on Moving Average Type on higher time frame settings.// - Dynamic smoothing calculations makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame.// - Exit strategy is simplified using MACD crossover / crossunder.// - no fixed stoploss.// - The below strategy is for educational purposes about how to use position sizing.//////////////////////////////////////////////////////////////////////////////////////////@version=5strategy(title = "Risk Management and Positionsize - MACD example", shorttitle =  "Risk Management", overlay=false,          pyramiding=0, initial_capital = 10000,         calc_on_order_fills=false,         slippage = 0,         commission_type=strategy.commission.percent, commission_value=0.03)////////////////////////////////////////////////////////////////         Risk Management        //////////////////////////////////////////////////////////////////RISKM = "Risk Management"InitialBalance = input.float(defval = 10000, title = "Initial Balance", minval = 1, maxval = 1000000, step = 1000, tooltip = "starting capital", group = RISKM)LeverageEquity = input.bool(defval = true, title = "qty based on equity %", tooltip = "true turns on MarginFactor based on equity, false gives fixed qty for positionsize", group = RISKM)MarginFactor = input.float(-0.5, minval = - 0.9, maxval = 100, step = 0.1, tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)QtyNr = input.float(defval = 3.5, title = "Quantity Contracts", minval = 0, maxval = 1000000, step = 0.01,  tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)EquityCurrent = InitialBalance + strategy.netprofit[1]QtyEquity = EquityCurrent * (1 + MarginFactor) / close[1]QtyTrade = LeverageEquity ? QtyEquity : QtyNr////////////////////////////////////////////////////////////////         Input MACD HTF         //////////////////////////////////////////////////////////////////MACD_settings = "Higher Time Frame MACD Settings"MA_Type  = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type", inline = "1", group = MACD_settings)TimeFrame_MACD = input.timeframe(title='Higher Time Frame', defval='30', inline = "1", group = MACD_settings)fastlength = input.int(11, title="Fast MA Length", minval=1, inline = "2", group = MACD_settings)slowlength = input.int(26, title="Slow MA Length", minval=1, inline = "2", group = MACD_settings)signallength = input.int(9, title="Length Signal MA", minval=1, inline = "3", group = MACD_settings)Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "3", group = MACD_settings)ma(type, src, length) =>    float result = 0    if type == 'TMA' // Triangular Moving Average        result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)        result    if type == 'LSMA' // Least Squares Moving Average        result := ta.linreg(src, length, 0)        result    if type == 'SMA'  // Simple Moving Average        result := ta.sma(src, length)        result    if type == 'EMA'  // Exponential Moving Average        result := ta.ema(src, length)        result    if type == 'DEMA'  // Double Exponential Moving Average        e = ta.ema(src, length)        result := 2 * e - ta.ema(e, length)        result    if type == 'TEMA'  // Triple Exponentiale        e = ta.ema(src, length)        result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)        result    if type == 'WMA'  // Weighted Moving Average        result := ta.wma(src, length)        result    if type == 'HMA'  // Hull Moving Average        result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))        result    result// MACD function for calculation higher timeframemacd_function() =>    fast_ma = ma(MA_Type, close, fastlength)    slow_ma = ma(MA_Type, close, slowlength)    macd = fast_ma - slow_ma    macd    signal_function() =>    fast_ma = ma(MA_Type, close, fastlength)    slow_ma = ma(MA_Type, close, slowlength)    macd = fast_ma - slow_ma    signal = ma(MA_Type, macd, signallength)    signalhist_function() =>    fast_ma = ma(MA_Type, close, fastlength)    slow_ma = ma(MA_Type, close, slowlength)    macd = fast_ma - slow_ma    signal = ma(MA_Type, macd, signallength)    hist = macd - signal    histMACD_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, macd_function())SIGNAL_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, signal_function())HIST_Value_HTF = MACD_Value_HTF - SIGNAL_Value_HTF// Get minutes for current and higher timeframes// Function to convert a timeframe string to its equivalent in minutestimeframeToMinutes(tf) =>    multiplier = 1    if (str.endswith(tf, "D"))        multiplier := 1440    else if (str.endswith(tf, "W"))        multiplier := 10080    else if (str.endswith(tf, "M"))        multiplier := 43200    else if (str.endswith(tf, "H"))        multiplier := int(str.tonumber(str.replace(tf, "H", "")))    else        multiplier := int(str.tonumber(str.replace(tf, "m", "")))    multiplier// Get minutes for current and higher timeframescurrentTFMinutes = timeframeToMinutes(timeframe.period)higherTFMinutes = timeframeToMinutes(TimeFrame_MACD)// Calculate the smoothing factordynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)MACD_Value_HTF_Smooth = ta.sma(MACD_Value_HTF, dynamicSmoothing)SIGNAL_Value_HTF_Smooth = ta.sma(SIGNAL_Value_HTF, dynamicSmoothing)HIST_Value_HTF_Smooth = ta.sma(HIST_Value_HTF, dynamicSmoothing)// Determin Long and Short ConditionsLongCondition = ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth < 0ShortCondition = ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth > 0////////////////////////////////////////////////////////////////          Filter Trend          //////////////////////////////////////////////////////////////////TREND = "Higher Time Frame Trend"TimeFrame_Trend = input.timeframe(title='Higher Time Frame', defval='1D', inline = "Trend1", group = TREND)length = input.int(55, title="Length MA", minval=1, tooltip = "Number of bars used to measure trend on higher timeframe chart", inline = "Trend1", group = TREND)MA_Type_trend  = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA", "McGinley"], title="MA type for HTF trend", inline = "Trend2", group = TREND)ma_trend(type, src, length) =>    float result = 0    if type == 'TMA' // Triangular Moving Average        result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)        result    if type == 'LSMA' // Least Squares Moving Average        result := ta.linreg(src, length, 0)        result    if type == 'SMA'  // Simple Moving Average        result := ta.sma(src, length)        result    if type == 'EMA'  // Exponential Moving Average        result := ta.ema(src, length)        result    if type == 'DEMA'  // Double Exponential Moving Average        e = ta.ema(src, length)        result := 2 * e - ta.ema(e, length)        result    if type == 'TEMA'  // Triple Exponentiale        e = ta.ema(src, length)        result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)        result    if type == 'WMA'  // Weighted Moving Average        result := ta.wma(src, length)        result    if type == 'HMA'  // Hull Moving Average        result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))        result    if type == 'McGinley' // McGinley Dynamic Moving Average        mg = 0.0        mg := na(mg[1]) ? ta.ema(src, length) : mg[1] + (src - mg[1]) / (length * math.pow(src / mg[1], 4))        result := mg        result    result// Moving AverageMAtrend = ma_trend(MA_Type_trend, close, length)MA_Value_HTF = request.security(syminfo.ticker, TimeFrame_Trend, MAtrend)// Get minutes for current and higher timeframeshigherTFMinutes_trend = timeframeToMinutes(TimeFrame_Trend)// Calculate the smoothing factordynamicSmoothing_trend = math.round(higherTFMinutes_trend / currentTFMinutes)MA_Value_Smooth = ta.sma(MA_Value_HTF, dynamicSmoothing_trend)// Trend HTFUP = MA_Value_Smooth > MA_Value_Smooth[1] // Use "UP" Function to use as filter in combination with other indicatorsDOWN = MA_Value_Smooth < MA_Value_Smooth[1] // Use "Down" Function to use as filter in combination with other indicators////////////////////////////////////////////////////////////       Strategy       /////////////////////////////////////////////////////////////////if LongCondition and UP == true    strategy.entry("Long", strategy.long, qty = QtyTrade)strategy.close_all(when = strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))   if ShortCondition and DOWN == true    strategy.entry("Short", strategy.short, qty = QtyTrade)strategy.close_all(when = strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))   ////////////////////////////////////////////////////////////         Plots        /////////////////////////////////////////////////////////////////hline(0, "Zero Line", color=color.new(#787B86, 50))plot(HIST_Value_HTF_Smooth, title="Histogram", style=plot.style_columns, color=(HIST_Value_HTF_Smooth>=0 ? (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(0, 255, 8) : color.rgb(0, 100, 5)) : (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(150, 35, 35) : color.rgb(255, 0, 0))))plot(SIGNAL_Value_HTF_Smooth, title="Signal", color=color.orange)plot(MACD_Value_HTF_Smooth, title="MACD", color=color.blue)plot(Plot_Signal ? LongCondition ? MACD_Value_HTF_Smooth : na : na, "Long Condition", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4)plot(Plot_Signal ? ShortCondition ? MACD_Value_HTF_Smooth : na : na, "Short Condition", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4)plotshape(UP == true, "trend up", style = shape.square, location = location.bottom, color = color.green, size = size.tiny)plotshape(DOWN == true, "trend down", style = shape.square, location = location.bottom, color = color.red, size = size.tiny)