Strategy · Pine Script v6 · On the chart

Renko MACD Futures Long Only

by PETERSAMUELOPS12· code credited to Gotrade

A long-only futures strategy that simulates Renko bricks on a normal time chart and calculates MACD on the brick closes, which filters out time-based noise.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code286
Settings19inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago25 May 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

286 lines of Pine Script v6 from pinescript/renko_chart_futures_startegy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

renko_chart_futures_startegy.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gotrade

//@version=6
// ── How it works ──────────────────────────────────────────────────────────────
// Applied to a NORMAL time-based chart (1h, 4h, 1D, etc.)
// Internally simulates Renko bricks: a new brick only forms when price moves
// X points in the same direction. The MACD is then calculated on the synthetic
// Renko close series (which only changes when a new brick forms), filtering out
// time-based noise. A bullish MACD crossover on Renko → long entry.
// Long positions only.
strategy("Renko MACD Futures – Long Only", overlay=true,
         default_qty_type=strategy.fixed, default_qty_value=1,
         initial_capital=1000000, margin_long=0.1,
         commission_type=strategy.commission.percent, commission_value=0.04,
         fill_orders_on_standard_ohlc=true)

// ═══════════════════════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════════════════════
grp0 = "Renko Brick Size"
useAtrBrick    = input.bool(true,   "Auto brick size (ATR-based)",            group=grp0,
                    tooltip="ON: brick = ATR × multiplier — adapts to each asset's volatility. OFF: fixed absolute brick size.")
atrRenkoPeriod = input.int(14,      "ATR period for brick size",              group=grp0, minval=1)
atrBrickMult   = input.float(1.0,   "ATR multiplier  (brick = ATR × mult)",  group=grp0, minval=0.1, step=0.1,
                    tooltip="1.0 = one ATR per brick. Smaller = more bricks (noisier), larger = fewer bricks (smoother).")
fixedBrickSize = input.float(10.0,  "Fixed brick size (when ATR OFF)",       group=grp0, minval=0.001,
                    tooltip="Absolute price units. E.g. 10 points for SPX, 100 for BTC, 0.001 for FX pairs.")

grp1 = "MACD Settings (applied to Renko)"
macdFast   = input.int(12, "Fast EMA",   group=grp1, minval=2)
macdSlow   = input.int(26, "Slow EMA",   group=grp1, minval=2)
macdSignal = input.int(9,  "Signal EMA", group=grp1, minval=2)

grp2 = "Trend Filter"
useTrendFilter = input.bool(true,  "Only enter when price above trend MA",   group=grp2,
                    tooltip="Blocks entries when price is in a downtrend. Prevents buying into falling markets.")
trendMAPeriod  = input.int(100,    "Trend MA period (SMA)",                 group=grp2, minval=5)
trendMABuffer  = input.float(1.0,  "Min % above trend MA to enter",        group=grp2, minval=0.0, step=0.5,
                    tooltip="Avoids entries right at the MA boundary where exits could fire immediately.")

grp3 = "Risk Management"
useEquityPct     = input.bool(true,   "Size as % of equity",                 group=grp3)
marginEquityPct  = input.float(0.2,   "Margin % of equity per trade",        group=grp3, minval=0.01, step=0.01)
marginAmt        = input.float(2000,  "Fixed margin (when % mode OFF)",      group=grp3, minval=1)
leverage         = input.int(1000,    "Leverage (x)",                        group=grp3, minval=1, maxval=1000)
trailPct         = input.float(5.0,   "Trailing stop % from peak",           group=grp3, minval=0.1, step=0.1)
trailActivatePct = input.float(8.0,   "Activate trail after X% profit",      group=grp3, minval=0.1, step=0.1,
                      tooltip="Must be > trail stop %. Guarantees trail is above entry when it first fires.")
portfolioStopPct = input.float(50.0,  "Emergency stop: X% loss of peak equity", group=grp3, minval=1.0, maxval=100.0)

grp4 = "Exit Rules"
useRenkoBearExit = input.bool(true,  "Exit on Renko MACD bearish crossover", group=grp4,
                      tooltip="Closes the long when MACD crosses below signal line on the Renko series — trend reversal signal.")
useTrendExit     = input.bool(true,  "Exit on trend MA crossunder",          group=grp4,
                      tooltip="Closes the long when price crosses below the trend MA.")

// ═══════════════════════════════════════════════════════════════════════════════
// RENKO BRICK SIMULATION
// ═══════════════════════════════════════════════════════════════════════════════
// brickSize adapts each bar (ATR changes), but Renko state only updates when
// price moves enough to form a new brick.
brickSize = useAtrBrick ? ta.atr(atrRenkoPeriod) * atrBrickMult : fixedBrickSize

// Persistent Renko state
var float renkoHigh  = na   // price top of the current brick
var float renkoLow   = na   // price bottom of the current brick
var int   renkoDir   = 1    // 1 = last brick was up, -1 = last brick was down
var float renkoClose = na   // synthetic close used for MACD (= renkoHigh for up bricks, renkoLow for down bricks)
var bool  newBrick   = false

// Initialise on bar 0
if na(renkoHigh)
    renkoHigh  := close
    renkoLow   := close - brickSize
    renkoDir   := 1
    renkoClose := close

newBrick := false

// New UP brick(s): price closed above current brick top by at least one brick
if close >= renkoHigh + brickSize
    bricksFormed = int(math.floor((close - renkoHigh) / brickSize))
    renkoHigh   := renkoHigh + brickSize * bricksFormed
    renkoLow    := renkoHigh - brickSize
    renkoDir    := 1
    renkoClose  := renkoHigh
    newBrick    := true

// New DOWN brick(s): price closed below current brick bottom by at least one brick
if close <= renkoLow - brickSize
    bricksFormed = int(math.floor((renkoLow - close) / brickSize))
    renkoLow    := renkoLow - brickSize * bricksFormed
    renkoHigh   := renkoLow + brickSize
    renkoDir    := -1
    renkoClose  := renkoLow
    newBrick    := true

// ═══════════════════════════════════════════════════════════════════════════════
// MACD CALCULATED ON RENKO CLOSE
// ═══════════════════════════════════════════════════════════════════════════════
// renkoClose is flat between bricks → EMAs move only when bricks form.
// This approximates applying MACD to the Renko chart itself.
renkoFastEMA    = ta.ema(renkoClose, macdFast)
renkoSlowEMA    = ta.ema(renkoClose, macdSlow)
renkoMacdLine   = renkoFastEMA - renkoSlowEMA
renkoSignalLine = ta.ema(renkoMacdLine, macdSignal)
renkoHistogram  = renkoMacdLine - renkoSignalLine

// Crossover signals (only meaningful when a new brick has formed)
renkoBullCross = ta.crossover(renkoMacdLine, renkoSignalLine)
renkoBearCross = ta.crossunder(renkoMacdLine, renkoSignalLine)

// ═══════════════════════════════════════════════════════════════════════════════
// TREND FILTER
// ═══════════════════════════════════════════════════════════════════════════════
trendMA          = ta.sma(close, trendMAPeriod)
trendMAThreshold = trendMA * (1 + trendMABuffer / 100)
inUptrend        = close > trendMA
entryOk          = not useTrendFilter or close > trendMAThreshold

// ═══════════════════════════════════════════════════════════════════════════════
// POSITION SIZING
// ═══════════════════════════════════════════════════════════════════════════════
safeEquity      = math.max(strategy.equity, strategy.initial_capital * 0.001)
effectiveMargin = useEquityPct ? safeEquity * marginEquityPct / 100 : marginAmt
notionalSize    = effectiveMargin * leverage
qtyContracts    = notionalSize / math.max(close, 0.000001)

// ═══════════════════════════════════════════════════════════════════════════════
// POSITION STATE & TRAILING STOP
// ═══════════════════════════════════════════════════════════════════════════════
inPos    = strategy.position_size > 0
avgEntry = strategy.position_avg_price
liqPrice = avgEntry > 0 ? avgEntry * (1 - 1.0 / leverage) : na

var float peakSinceEntry = na
if inPos
    peakSinceEntry := math.max(nz(peakSinceEntry, close), high)
else
    peakSinceEntry := na

rawTrailStop   = not na(peakSinceEntry) ? peakSinceEntry * (1 - trailPct / 100) : na
trailStopPrice = (not na(rawTrailStop) and avgEntry > 0) ? math.max(avgEntry, rawTrailStop) : na
trailActive    = inPos and not na(peakSinceEntry) and
                 peakSinceEntry >= avgEntry * (1 + trailActivatePct / 100)

// Equity peak & emergency stop (referenced to running peak, not fixed initial capital)
var float equityPeak = strategy.initial_capital
equityPeak       := math.max(equityPeak, strategy.equity)
portfolioStopAmt  = equityPeak * portfolioStopPct / 100

// ═══════════════════════════════════════════════════════════════════════════════
// ORDERS
// ═══════════════════════════════════════════════════════════════════════════════
// Entry: Renko MACD crosses bullish + uptrend filter + flat
if renkoBullCross and entryOk and not inPos
    strategy.entry("Long", strategy.long, qty=qtyContracts,
                   comment="RENKO MACD↑ brick=" + str.tostring(math.round(brickSize, 2)))

// Exit 1: trailing stop (after trailActivatePct profit, floor at entry)
if trailActive and close <= trailStopPrice
    strategy.close("Long", comment="TRAIL EXIT")

// Exit 2: emergency stop (loss >= X% of equity peak)
if inPos and strategy.openprofit <= -portfolioStopAmt
    strategy.close("Long", comment="EMRG STOP " + str.tostring(portfolioStopPct) + "%")

// Exit 3: Renko MACD bearish crossover (momentum reversal)
if useRenkoBearExit and inPos and renkoBearCross
    strategy.close("Long", comment="RENKO MACD↓")

// Exit 4: price crosses below trend MA
trendCrossunder = ta.crossunder(close, trendMA)
if useTrendExit and inPos and trendCrossunder
    strategy.close("Long", comment="TREND EXIT MA" + str.tostring(trendMAPeriod))

// ═══════════════════════════════════════════════════════════════════════════════
// PLOTS
// ═══════════════════════════════════════════════════════════════════════════════
// Renko brick boundaries as step lines on the price chart
plot(renkoHigh, "Renko Top",    color=renkoDir == 1 ? color.new(color.lime, 30) : color.new(color.red, 30),
     linewidth=1, style=plot.style_stepline)
plot(renkoLow,  "Renko Bottom", color=renkoDir == 1 ? color.new(color.lime, 30) : color.new(color.red, 30),
     linewidth=1, style=plot.style_stepline)

// Trend MA
plot(trendMA, "Trend MA", color=color.new(color.blue, 20), linewidth=2)

// Trailing stop
plot(inPos ? trailStopPrice : na, "Trail Stop",
     color=color.new(color.yellow, 0), linewidth=2, style=plot.style_linebr)
plot(inPos ? liqPrice : na, "Liq Price",
     color=color.new(color.red, 0), linewidth=1, style=plot.style_linebr)

// Signal markers
plotshape(renkoBullCross and entryOk and not inPos,
          "Buy (Renko MACD↑)", shape.triangleup, location.belowbar,
          color.new(color.green, 0), size=size.normal)
plotshape(renkoBullCross and not entryOk,
          "Signal blocked (downtrend)", shape.xcross, location.belowbar,
          color.new(color.gray, 0), size=size.tiny)
plotshape(inPos and renkoBearCross and useRenkoBearExit,
          "Exit (Renko MACD↓)", shape.triangledown, location.abovebar,
          color.new(color.red, 0), size=size.small)
plotshape(newBrick,
          "New Renko Brick", shape.circle, location.belowbar,
          renkoDir == 1 ? color.new(color.lime, 40) : color.new(color.red, 40),
          size=size.tiny)

// Background
bgcolor(not inUptrend and useTrendFilter ? color.new(color.red,   92) : na, title="Downtrend Zone")
bgcolor(inPos                            ? color.new(color.green, 92) : na, title="In Position")

// ═══════════════════════════════════════════════════════════════════════════════
// DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════
var table dash = table.new(position.top_right, 2, 12,
     bgcolor=color.new(color.black, 55), border_width=1, border_color=color.new(color.gray, 60))

if barstate.islast
    pnlCol  = strategy.openprofit >= 0 ? color.lime : color.red
    netCol  = strategy.netprofit  >= 0 ? color.lime : color.red
    dirCol  = renkoDir == 1 ? color.lime : color.red
    macdCol = renkoMacdLine > renkoSignalLine ? color.lime : color.red

    table.cell(dash, 0, 0,  "Renko MACD Futures",  text_color=color.white,
               text_size=size.small, bgcolor=color.new(color.navy, 30))
    table.cell(dash, 1, 0,  "Long Only",            text_color=color.white,
               text_size=size.small, bgcolor=color.new(color.navy, 30))

    table.cell(dash, 0, 1,  "Brick Size",  text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 1,  str.tostring(math.round(brickSize, 2)) +
               (useAtrBrick ? "  (ATR×" + str.tostring(atrBrickMult) + ")" : "  (fixed)"),
               text_color=color.yellow, text_size=size.small)

    table.cell(dash, 0, 2,  "Renko Brick", text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 2,  (renkoDir == 1 ? "▲ UP" : "▼ DOWN") +
               "  H=" + str.tostring(math.round(renkoHigh, 2)) +
               " L=" + str.tostring(math.round(renkoLow, 2)),
               text_color=dirCol, text_size=size.small)

    table.cell(dash, 0, 3,  "Renko MACD",  text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 3,  str.tostring(math.round(renkoMacdLine,   2)) + " / " +
               str.tostring(math.round(renkoSignalLine, 2)) +
               "  H=" + str.tostring(math.round(renkoHistogram, 2)),
               text_color=macdCol, text_size=size.small)

    table.cell(dash, 0, 4,  "Trend",       text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 4,  (inUptrend ? "▲ BULL" : "▼ BEAR") +
               " | MA" + str.tostring(trendMAPeriod) + "=" + str.tostring(math.round(trendMA, 2)),
               text_color=inUptrend ? color.lime : color.red, text_size=size.small)

    table.cell(dash, 0, 5,  "Position",    text_color=color.silver, text_size=size.small)
    posStr = inPos ? ("LONG " + str.tostring(math.round(strategy.position_size, 2)) +
             " @ " + str.tostring(math.round(avgEntry, 2))) : "FLAT"
    table.cell(dash, 1, 5,  posStr, text_color=inPos ? color.lime : color.gray, text_size=size.small)

    table.cell(dash, 0, 6,  "Margin/trade",text_color=color.silver, text_size=size.small)
    modeStr = useEquityPct ? (str.tostring(marginEquityPct) + "% eq=") : "fixed="
    table.cell(dash, 1, 6,  modeStr + str.tostring(math.round(effectiveMargin, 0)) +
               " × " + str.tostring(leverage) + "x",
               text_color=color.yellow, text_size=size.small)

    table.cell(dash, 0, 7,  "Trail Stop",  text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 7,  inPos ? (trailActive ? str.tostring(math.round(trailStopPrice, 2)) :
               "wait +" + str.tostring(trailActivatePct) + "%") : "–",
               text_color=trailActive ? color.yellow : color.gray, text_size=size.small)

    table.cell(dash, 0, 8,  "Liq Price",   text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 8,  inPos ? str.tostring(math.round(liqPrice, 2)) : "–",
               text_color=color.red, text_size=size.small)

    table.cell(dash, 0, 9,  "Emrg Stop",   text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 9,  "-" + str.tostring(math.round(portfolioStopAmt, 0)) +
               " (" + str.tostring(portfolioStopPct) + "% of peak)",
               text_color=color.orange, text_size=size.small)

    table.cell(dash, 0, 10, "Open P&L",    text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 10, "$" + str.tostring(math.round(strategy.openprofit, 2)),
               text_color=pnlCol, text_size=size.small)

    table.cell(dash, 0, 11, "Net Profit",  text_color=color.silver, text_size=size.small)
    table.cell(dash, 1, 11, "$" + str.tostring(math.round(strategy.netprofit, 2)) +
               "  (" + str.tostring(strategy.closedtrades) + " trades)",
               text_color=netCol, text_size=size.small)

Overview

A bullish MACD crossover on the bricks opens a long when price is above a trend SMA by a buffer. Exits come from a bearish Renko MACD crossover, a trend average crossunder, a trailing stop that activates after a set gain and a portfolio-level emergency stop. Position size uses margin and leverage.

Details

Published by

PETERSAMUELOPS12 on GitHub

Code credit

Gotrade, as written in the script's header

Draws

On the price chart

Markets

Indices

Timeframes

H4 and above

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Auto brick size (ATR-based)booltrueuseAtrBrick
ATR period for brick sizeint14atrRenkoPeriod
ATR multiplier (brick = ATR × mult)float1.0atrBrickMult
Fixed brick size (when ATR OFF)float10.0fixedBrickSize
Fast EMAint12macdFast
Slow EMAint26macdSlow
Signal EMAint9macdSignal
Only enter when price above trend MAbooltrueuseTrendFilter
Trend MA period (SMA)int100trendMAPeriod
Min % above trend MA to enterfloat1.0trendMABuffer
Size as % of equitybooltrueuseEquityPct
Margin % of equity per tradefloat0.2marginEquityPct
Show all 19 settings
SettingTypeDefaultVariable
Fixed margin (when % mode OFF)float2000marginAmt
Leverage (x)int1000leverage
Trailing stop % from peakfloat5.0trailPct
Activate trail after X% profitfloat8.0trailActivatePct
Emergency stop: X% loss of peak equityfloat50.0portfolioStopPct
Exit on Renko MACD bearish crossoverbooltrueuseRenkoBearExit
Exit on trend MA crossunderbooltrueuseTrendExit
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
228 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

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 Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers