Strategy · Pine Script v6 · On the chart

MACD Money Management Strategy

by propuchon· code credited to yourusername

A strategy that trades MACD line and signal line crossovers within a chosen date range and compares three position sizing methods: a fixed dollar risk, a fixed percentage of equity risk, or a fixed quantity.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code132
Settings12inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago1 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

132 lines of Pine Script v6 from week 5/macd-mm-strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

macd-mm-strategy.pine
// ————————————————————————————————————————————————————————————————
// This source code is subject to the terms of the Mozilla Public License 2.0
// © yourusername
// ————————————————————————————————————————————————————————————————

//@version=6
strategy("[CUCEDT-W51] MACD Money Management Strategy"
     , overlay = true
     , initial_capital = 1000
     , margin_long = 0
     , margin_short = 0
     , currency = currency.USD
     , commission_type = strategy.commission.cash_per_contract
     , commission_value = 0.0)

//-----------------------------------------------------------------------------
// Constants 
//-----------------------------------------------------------------------------
const string TZ_BANGKOK = "UTC+7"

//-----------------------------------------------------------------------------
// Inputs 
//-----------------------------------------------------------------------------
// --- Backtest Range ---
backtestGroup = "Backtest Range"
startDate     = input.time( timestamp("01 Jan 2023 00:00 +0000"), title = "Start", group = backtestGroup)
endDate       = input.time( timestamp("31 Dec 2030 00:00 +0000"), title = "End",   group = backtestGroup)

// --- MACD Strategy ---
macdGroup    = "MACD Settings"
fastLength   = input.int(12, title="Fast Length", group=macdGroup)
slowLength   = input.int(26, title="Slow Length", group=macdGroup)
signalLength = input.int(9,  title="Signal Smoothing", group=macdGroup)
src          = input.source(close, title="Source", group=macdGroup)

// --- Money Management ---
mmGroup          = "Money Management"
mmType           = input.string("Fix Percent", title="Method", options=["Fix Dollar", "Fix Percent", "Fix Unit"], group=mmGroup)

// Parameters for each method
riskDollar       = input.float(20.0, title="Risk ($) per Trade", tooltip="For Fix Dollar: Amount to lose if SL is hit", group=mmGroup)
riskPercent      = input.float(2.0,   title="Risk (%) per Trade", tooltip="For Fix Percent: % of Equity to lose if SL is hit", group=mmGroup)
fixedLotSize     = input.float(0.01,   title="Fixed Quantity",   tooltip="For Fix Unit: Constant lot size per trade", group=mmGroup)

// --- Risk Management ---
riskGroup   = "Risk Management (TP/SL)"
slPoints    = input.int(500, title="Stop Loss (Ticks)", minval=1, group=riskGroup)
tpPoints    = input.int(1000, title="Take Profit (Ticks)", minval=1, group=riskGroup)

//-----------------------------------------------------------------------------
// Calculations: MACD
//-----------------------------------------------------------------------------
[macdLine, signalLine, histLine] = ta.macd(src, fastLength, slowLength, signalLength)

// Trading Conditions
longCondition  = ta.crossover(macdLine, signalLine)
shortCondition = ta.crossunder(macdLine, signalLine)

//-----------------------------------------------------------------------------
// Calculations: Money Management
//-----------------------------------------------------------------------------
GetPositionSize() =>
    float qty = 0.0
    float equity = strategy.equity
    
    // Calculate Risk per contract in Dollars
    // Loss per 1 contract = (EntryPrice - SLPrice) * syminfo.pointvalue
    // Entry - SL (in price) = slPoints * syminfo.mintick
    // Loss = (slPoints * syminfo.mintick) * syminfo.pointvalue
    
    float lossPerContract = (slPoints * syminfo.mintick) * syminfo.pointvalue
    if lossPerContract == 0 
        lossPerContract := 1.0 // Avoid div by zero
        
    if mmType == "Fix Dollar"
        qty := riskDollar / lossPerContract
        
    else if mmType == "Fix Percent"
        float riskAmt = equity * (riskPercent / 100.0)
        qty := riskAmt / lossPerContract 
            
    else if mmType == "Fix Unit"
        // Constant Size (Fixed Lot)
        qty := fixedLotSize

    qty

//-----------------------------------------------------------------------------
// Execution & Visuals
//-----------------------------------------------------------------------------
// Backtest check
isBacktestDate = (time >= startDate) and (time <= endDate)

positionSize = GetPositionSize()

if isBacktestDate
    if longCondition
        strategy.entry("Long", strategy.long, qty=positionSize)
        strategy.exit("Exit Long", "Long", loss=slPoints, profit=tpPoints)
        
    if shortCondition
        strategy.entry("Short", strategy.short, qty=positionSize)
        strategy.exit("Exit Short", "Short", loss=slPoints, profit=tpPoints)

// Plotting TP / SL levels for active position
// We can use plot() with series conditional
var float activeSL = na
var float activeTP = na
var float activeEntry = na

if strategy.position_size != 0
    // Strategy is in market
    if strategy.position_size > 0
        activeEntry := strategy.opentrades.entry_price(strategy.opentrades - 1)
        activeSL := activeEntry - (slPoints * syminfo.mintick)
        activeTP := activeEntry + (tpPoints * syminfo.mintick)
    else
        activeEntry := strategy.opentrades.entry_price(strategy.opentrades - 1)
        activeSL := activeEntry + (slPoints * syminfo.mintick)
        activeTP := activeEntry - (tpPoints * syminfo.mintick)
else
    activeSL := na
    activeTP := na
    activeEntry := na

plot(activeSL, "SL Level", color=color.red, style=plot.style_linebr, linewidth=2)
plot(activeTP, "TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(activeEntry, "Entry Level", color=color.gray, style=plot.style_linebr, linewidth=1)

// Plot Signals
plotshape(longCondition and isBacktestDate, title="Long", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(shortCondition and isBacktestDate, title="Short", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

Overview

Stop loss and take profit distances are set in ticks. MACD lengths and source are adjustable. The code shown is cut off before the order logic, so exact entry and exit handling is not visible. It draws on the price chart.

Details

Published by

propuchon on GitHub

Code credit

yourusername, as written in the script's header

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Starttimetimestamp("01 Jan 2023 00:00 +0000")startDate
Endtimetimestamp("31 Dec 2030 00:00 +0000")endDate
Fast Lengthint12fastLength
Slow Lengthint26slowLength
Signal Smoothingint9signalLength
Sourcesourceclosesrc
MethodstringFix PercentmmType
Risk ($) per Tradefloat20.0riskDollar
Risk (%) per Tradefloat2.0riskPercent
Fixed Quantityfloat0.01fixedLotSize
Stop Loss (Ticks)int500slPoints
Take Profit (Ticks)int1000tpPoints
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

MACD Strategy

by TradersPost
218 stars

This overlay strategy is built around MACD inputs for a fast average, a slow average, and a signal line. Comments say the script keeps MACD values available and can draw a histogram and zero line in a separate pane, with an optional overlay on price. Settings

Strategy v6 Oscillators & momentumMoving averages
Updated 3 months ago · None stated GitHub repository of MACD Strategy

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers