Strategy · Pine Script v5 · On the chart

FRAMA & CPMA Strategy [CSM]

by wynnforthework· code credited to chhagansinghmeena

The FRAMA & CPMA Strategy overlay script combines a Fractal Adaptive Moving Average (FRAMA) and a custom CPMA indicator imported from an external library.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code110
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Oct 2025

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

110 lines of Pine Script v5 from 策略/新建文件夹 (2)/FRAMA & CPMA策略[CSM].txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

FRAMA & CPMA策略[CSM].txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chhagansinghmeena

//@version=5
strategy("FRAMA & CPMA Strategy [CSM]", shorttitle = "CSM's => FRAMA + CPMA", overlay=true, margin_long=100, margin_short=100)
import chhagansinghmeena/BankNifty_CSM/3 as CM

src = input.source(title = "FRAMA Source", defval = close, group = "Requirements")
length = input.int(title='FRAMA Length', defval=21, minval=1, maxval=200, group = "Requirements")
fracDim = input.float(title='Fractal Dimension', defval=0.8, minval=0.1, maxval=2.0, group = "Requirements")
CPMA_length = input.int(title='CPMA Length', defval=21, minval=1, maxval=200, group = "Requirements")
enableEngulfingFilter = input.bool(title = "Enable Engulfing Candle Filter", defval = false, group = "Requirements")

longTakeProfit = input.float(10, 'Long Take Profit Amount', minval=0.05, step=0.05,group = "Stoploss/Target") 
shortTakeProfit = input.float(10, 'Short Take Profit Amount', minval=0.05, step=0.05,group = "Stoploss/Target") 
trailingTakeProfit = input.float(0.5, 'Trailing Take Profit Amount', minval=0.01, maxval=100, step=0.01,group = "Stoploss/Target") 
LossstratA = input.float(defval=100, minval=0, maxval=10000, title="Stop Loss", step=5,group="Stoploss/Target")
start = input.time(title='Start Date', defval=timestamp('01 Jan 2023 03:30 +0000'), group='Backtesting', tooltip='Date & time to begin trading from')
finish = input.time(title='End Date', defval=timestamp('1 Jan 2099 15:30 +0000'), group='Backtesting', tooltip='Date & time to stop trading')

window() =>
    time >= start and time <= finish ? true : false

// Get various price types
[Open, price, High, Low , HL2, HLC3, HLCC4, OHLC4 ] = request.security(syminfo.tickerid, timeframe.period, [open, close, high, low, hl2, hlc3, hlcc4, ohlc4])
//Get CPMA from Library
CPMA = CM.CSM_CPMA(length = CPMA_length, price = price, HL2 = HL2, Open = Open , High = High, Low = Low, OHLC4 = OHLC4, HLC3 = HLC3, HLCC4 = HLCC4)
//Get FRAMA from Library
FRAMA = CM.frama_Calculation(src = src, length = length, mult = fracDim)

plot(CPMA, color=color.orange, linewidth=2, title="CPMA")
plot(FRAMA, color=color.blue, linewidth=2, title="FRAMA")

// Detect bullish and bearish engulfing patterns
bullishEngulfing = CM.candlepatternbullish()
bearishEngulfing = CM.candlepatternbearish()

longCondition = (ta.cross(close, FRAMA) and close > FRAMA) or (ta.cross(close, CPMA) and close > CPMA ) 
shortCondition = (ta.cross(close, FRAMA) and close < FRAMA) or (ta.cross(close, CPMA) and close < CPMA) 

Signal = 0
if enableEngulfingFilter
    longCondition := bullishEngulfing and (longCondition or ta.crossover(FRAMA, CPMA))
    shortCondition := bearishEngulfing and (shortCondition or ta.crossunder(FRAMA, CPMA))
else 
    Signal := longCondition  ? 1 : shortCondition  ? -1 : nz(Signal[1])
    isDifferentSignalType = ta.change(Signal)  
    longCondition := longCondition and isDifferentSignalType
    shortCondition := shortCondition and isDifferentSignalType

longTakeProfitPerc = longTakeProfit/close
shortTakeProfitPerc = shortTakeProfit/close
trailingTakeProfitPerc =  trailingTakeProfit == 0.01 ? syminfo.mintick/close : trailingTakeProfit/close 

bool longIsActive = longCondition or strategy.position_size > 0
bool shortIsActive = shortCondition or strategy.position_size < 0

longIsActive := longCondition or strategy.position_size > 0
shortIsActive := shortCondition or strategy.position_size < 0

//Long Stop Loss added
float longStopLossprice = na
longStopLossprice := if longIsActive 
    if longCondition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)
        low - LossstratA
    else
        nz(longStopLossprice[1], low - LossstratA)
else
    na
 
//Long Take Profir Added
float longTakeProfitPrice = na
longTakeProfitPrice := if longIsActive 
    if longCondition and not (strategy.position_size > 0)
        close * (1 + longTakeProfitPerc)
    else
        nz(longTakeProfitPrice[1], high * (1 - longTakeProfitPerc))
else
    na

//Short StopLoss added
float shortStopLossprice = na
shortStopLossprice := if shortIsActive 
    if shortCondition and not (strategy.position_size < 0)
        high + LossstratA
    else
        nz(shortStopLossprice[1], high + LossstratA)
else
    na

//Short Take profit added
float shortTakeProfitPrice = na
shortTakeProfitPrice := if shortIsActive 
    if shortCondition and not (strategy.position_size < 0)
        close * (1 - shortTakeProfitPerc)
    else
        nz(shortTakeProfitPrice[1], close * (1 - shortTakeProfitPrice))
else
    na
 
float longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick
float shortTrailingTakeProfitStepTicks = shortTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick

if window()
    switch
        longCondition=> strategy.entry("Long",strategy.long)
        shortCondition=> strategy.entry("Short", strategy.short)

    strategy.exit(id = 'Long TP/SL', from_entry = 'Long', trail_price = longTakeProfitPrice , trail_offset = longTrailingTakeProfitStepTicks, stop = longStopLossprice)
    strategy.exit(id = 'Short TP/SL', from_entry = 'Short', trail_price = shortTakeProfitPrice, trail_offset = shortTrailingTakeProfitStepTicks, stop = shortStopLossprice)

Overview

FRAMA & CPMA Strategy [CSM] generates long and short trading signals when price crosses above or below either moving average line. Traders can optionally enable an engulfing candle pattern filter to require bullish or bearish confirmation before entering trades. The strategy includes adjustable fixed stop-loss levels, profit targets, trailing stop parameters, and a custom backtesting date window. Both indicator lines are plotted directly on the main price chart.

Details

Published by

wynnforthework on GitHub

Code credit

chhagansinghmeena, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Candlestick patterns

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
FRAMA Sourcesourceclosesrc
FRAMA Lengthint21length
Fractal Dimensionfloat0.8fracDim
CPMA Lengthint21CPMA_length
Enable Engulfing Candle FilterboolfalseenableEngulfingFilter
Long Take Profit Amountfloat10longTakeProfit
Short Take Profit Amountfloat10shortTakeProfit
Trailing Take Profit Amountfloat0.5trailingTakeProfit
Stop Lossfloat100LossstratA
Start Datetimetimestamp('01 Jan 2023 03:30 +0000')start
End Datetimetimestamp('1 Jan 2099 15:30 +0000')finish
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

Pin Bar Magic v1

by Alorse
330 stars

This strategy trades price action pin bar patterns aligned with moving average trend alignment on the main price chart. It defines uptrends or downtrends using a fan arrangement of three moving averages (6 EMA, 18 EMA, and 50 SMA). Entry conditions require a b

Strategy v4 Candlestick patternsTrend
Updated 2 months ago · None stated GitHub repository of Pin Bar Magic v1
257 stars

This overlay strategy marks short-term turning points on the price chart and enters SPY option-style trades from them. It plots simple moving averages of highs and lows, draws up and down reversal arrows, and colors bars when a short-term extreme coincides wit

Strategy v5 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of SPY Options Trading - Alert

This strategy calculates and plots smoothed Heikin-Ashi candles directly onto the main price chart using exponential moving averages of open, high, low, and close prices. It enters a long position after three consecutive bullish smoothed candles with sequentia

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of Abdoli's Heikin Ashi Smoothed Buy & Sell Strategy Rev.4

DI Engulfing A002

by ruckard
13 stars

This strategy executes trades based on candlestick engulfing patterns aligned with a 200-period exponential moving average trend filter. It enters long positions when a bullish engulfing candle follows three consecutive bearish candles while price trades above

Strategy v5 Candlestick patternsTrend
Updated 1 year ago · None stated GitHub repository of DI Engulfing A002
7 stars

This strategy combines Ichimoku Kinko Hyo components, a Stochastic oscillator, and specific candlestick patterns to generate trade signals. It identifies Kumo twists and range breakouts while evaluating candle body shapes using Fibonacci threshold filters. Tra

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · MIT GitHub repository of Soulevement / Ressaut 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