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
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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Risk Management | |||
| Initial Balancestarting capital | 10000 | float · min 1 · max 1000000 · step 1000 | EquityCurrent |
| qty based on equity %true turns on MarginFactor based on equity, false gives fixed qty for positionsize | true | bool | QtyTrade |
| 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.5 | float · min - 0.9 · max 100 · step 0.1 | QtyEquity |
| 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 instrument | 3.5 | float · min 0 · max 1000000 · step 0.01 | QtyTrade |
| Higher Time Frame MACD Settings | |||
| MA type | EMA | string · options ["EMA","DEMA","TEMA","SMA","WMA", "HMA"] | fast_ma slow_ma signal |
| Higher Time Frame | 30 | timeframe | MACD_Value_HTF SIGNAL_Value_HTF higherTFMinutes |
| Fast MA Length | 11 | int · min 1 | fast_ma |
| Slow MA Length | 26 | int · min 1 | slow_ma |
| Length Signal MA | 9 | int · min 1 | signal |
| Plot Signal? | true | bool | Long Condition Short Condition |
| Higher Time Frame Trend | |||
| Higher Time Frame | 1D | timeframe | MA_Value_HTF higherTFMinutes_trend |
| Length MANumber of bars used to measure trend on higher timeframe chart | 55 | int · min 1 | result e mg MAtrend |
| MA type for HTF trend | EMA | string · 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) + 1
result · line 129 - EMAsrc, Length MA (55)
e · line 145 - SMAMACD_Value_HTF, dynamicSmoothing
MACD_Value_HTF_Smooth · line 113 - SMASIGNAL_Value_HTF, dynamicSmoothing
SIGNAL_Value_HTF_Smooth · line 114 - SMAHIST_Value_HTF, dynamicSmoothing
HIST_Value_HTF_Smooth · line 115 - EMAsrc, Length MA (55)
mg · line 156 - SMAMA_Value_HTF, dynamicSmoothing_trend
MA_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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | LongCondition and UP == true | On | 175 |
| Close | strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) | On | 176 |
| Open Short short | ShortCondition and DOWN == true | On | 178 |
| Close | strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) | On | 179 |
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 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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Risk Management and Positionsize - MACD example this page | — | v5 strategy | 0.0% | 0 | 0.0% |
| MACD ReLoaded STRATEGY by KivancOzbilgic | ema linreg wma sma | v5 strategy | +7.8% | 31 | 5.1% |
| Linear Regression MA - Strategy by lazy_capitalist | sma linreg ema | v5 strategy | −1,240.4% | 10 | 318.7% |
| Forex SWING Trader by SoftKill21 | wma ema sma | v4 strategy | No trades on this market | ||
| DRSI DMA Scalping Strategy No Repaint by allenlk | sma wma ema | v4 strategy | −99.5% | 44 | 137.7% |
| Profit Maximizer PMax Strategy - Long-Short by melihtuna | sma ema linreg | v4 strategy | +16.2% | 4 | 27.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 verifiedNeither 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 48 ms | With a workaround 1,000 bars in 81 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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)