Strategy · Pine Script v5 · On the chart

SRP Strategy [ZCrypto]

by veo555· code credited to TZack88

This strategy implements a dollar-cost averaging (DCA) trading framework using Volume-Weighted Moving Average (VWMA) values and price percentage changes.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code283
Settings24inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago23 Nov 2023

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

283 lines of Pine Script v5 from data/1.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

1.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TZack88

//@version=5
strategy("SRP Strategy  [ ZCrypto ]", 
   overlay=true,
   max_labels_count = 500,
   pyramiding = 5,
   default_qty_type = strategy.cash,
   initial_capital = 1000,
   commission_type = strategy.commission.percent,
   commission_value = 0.07,
   default_qty_value = 100
   )

  //

   
// inputs 
color bgray                                  = color.rgb(128, 223, 236, 81)
color WHITE                                  = color.rgb(210, 210, 210)
color red                                    = color.rgb(128, 49, 49, 67)
color white                                  = color.rgb(248, 248, 248, 14)
color olive                                  = color.olive
color blue                                   = color.rgb(23, 43, 77)
color Yellow                                 = color.rgb(255, 186, 75)
color BG                                     = color.from_gradient(close,low,high ,color.rgb(16, 194, 167),color.rgb(240, 141, 71))
string s_group                               = " Strategy Settings"
string visual                                = "Visuals" 
int offset                                   = 15
var int glb_dealstart_bar_time               = 0
int Length                                   = 14
float ChangePercentage                       = input.float(title='SRP %',defval=1.4,group='SRP Settings',inline = "00",step=0.1)
float core                                   = ta.vwma(hlc3, Length)  
float below                                  = input(55,title="⬇️",group='SRP Settings',inline = "00")
float above                                  = input(100,title="⬆️",group='SRP Settings',inline = "00")
bool mintpbool                               = input.bool(true,"Minimal TP❓➔ ",group = s_group,inline="01")
float mintp                                  = input.float(2.0,"",step= 0.1 , group = s_group,inline="01")/100
float minSOchange                            = input.float(title='Price change %', defval=2.0, step=0.1, group = s_group,inline="01")
float base                                   = input.float(title='$ Base order', defval=100, step=1, group = s_group,inline="01")
float safety                                 = input.float(title='DCA Multi', defval=1.5, step=1, group = s_group,inline="01",tooltip = "It Multiply the position size by this value")
int sonum                                    = input.int(title='DCA Count', defval=4, step=1, group = s_group,inline="01",tooltip = "How Many DCA orders Do you want ?!")+1
bool DCATYPE                                 = input.string("Volume Multiply",title ="DCA TYPE",options = ["Volume Multiply","Base Multiply"],group = s_group,inline="01") == "Volume Multiply"


bool limit_date_range                        = input.bool(title='Backtest Date', defval=true, group="Backtest Date")
int start_time                               = input.time(defval=timestamp('11 OCT 2022 00:00 +0000'), title='Start Time', group="Backtest Date")
int end_time                                 = input.time(defval=timestamp('31 Dec 2080 00:00 +0000'), title='End Time', group="Backtest Date")

bool show_table                              = input(true,title= "Show Table ❓",inline = "001",group = visual)
string position                              = input.string("Top Right", options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"],title = 'Position',inline = "001",group = visual)
color textcolos                              = input.color(Yellow,title = "Text Color",inline = "001",group = visual)
bool showdeals                               = input(true,"Deal lines❓",inline = "002",group =visual )
color profitcolor                            = input.color(bgray,"",inline = "002",group =visual )  
color socolor                                = input.color(red,"",inline = "002",group =visual )  
color avgcolor                               = input.color(white,"",inline = "002",group =visual )
bool showBG                                  = input(false,"Deal BG Color❓",inline = "003",group =visual ) 
color bgcolor                                = input.color(blue,"",inline = "003",group =visual )  
bool showpnllabel                            = input(true,"PNL Label❓",inline = "004",group =visual )
color pnlcolor                               = input.color(olive,"",inline = "004",group =visual ) 



string table_name                            ='SRP Strategy [ZCrypto]'
var int socounter = 0
var int dealcount = 0

// Core calculation ---------{

in_date_range = true
if limit_date_range
    in_date_range := time >= start_time and time <= end_time
    
else
    in_date_range := true


vwma_above = core * (1 + (ChangePercentage / 100))
vwma_below = core * (1 - (ChangePercentage / 100))

//
up = ta.rma(math.max(ta.change(close), 0), 7)
down = ta.rma(-math.min(ta.change(close), 0), 7)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
mf = ta.mfi(hlc3, 7)
rsi_mfi = math.abs(rsi+mf/2)

long = low <= vwma_below and (rsi_mfi < below)
short = high >= vwma_above and (rsi_mfi > above)

table_position() =>
    switch position
        "Middle Right" => position.middle_right
        "Top Center" => position.top_center
        "Top Right" => position.top_right
        "Middle Left" => position.middle_left
        "Middle Center" => position.middle_center
        "Bottom Left" => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right" => position.bottom_right      
      
var summary_table          = table.new(table_position(), 15, 33, frame_color=color.rgb(58, 58, 59, 38), frame_width=3,border_width = 2)
change_color(con)=>
    con ? color.rgb(0, 149, 77) : color.rgb(152, 46, 46)    

table_cell(table,_row,in1,in2)=>
    
    table.cell(table, 0, _row, 
     in1, 
     text_color=textcolos,
     bgcolor = color.rgb(58, 58, 59, 38),
     text_size = size.small,
     text_halign = text.align_left
     )
    table.cell(table, 1, _row, str.tostring(in2), text_color=WHITE,text_size = size.small,bgcolor =color.rgb(120, 123, 134, 38) )

//------------}
calcNextSOprice(pcnt) =>
    if strategy.position_size > 0
        strategy.position_avg_price - (math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick)) * syminfo.mintick
    else if strategy.position_size < 0
        strategy.position_avg_price + (math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick)) * syminfo.mintick
    else
        na
calcChnagefromlastdeal() =>
    last_deal = strategy.opentrades.entry_price(strategy.opentrades - 1)
    math.abs(((close - (last_deal)  ) /close )  * 100 )


Calcprofitpercent() =>
    math.abs(((close - strategy.position_avg_price  ) /close )  * 100 )


// def calculate(base, SO):
    
//     return so_size    
SO = base * safety
CapitalCalculation() =>
    float total = 0.0

    for x= 1 to sonum - 1 by 1
        so_size = SO * math.pow(safety, x-1)
        total+= so_size


    total + base

// plot(SO,"?111!") 
// plot(CapitalCalculation(),"?!")    
calculateSO(num)=>
    SOv = base * math.pow(safety,num)
    SOv

SOconditions()=>
    (calcChnagefromlastdeal() > minSOchange ) and (close < calcNextSOprice(minSOchange))
   

mintpclogic()=> 

   (close > (strategy.position_avg_price * (1 + mintp)))

get_timestring_from_seconds(seconds) =>
    if seconds >= 86400
        string _string = str.tostring(math.round(seconds / 86400, 1)) + ' days'
    else if seconds >= 3600
        string _string = str.tostring(math.round(seconds / 3600, 1)) + ' hours'
    else
        string _string = str.tostring(math.round(seconds / 60, 1)) + ' mins'

get_timespan_string(start_time, end_time) =>
    _seconds_diff = (end_time - start_time) / 1000
    get_timestring_from_seconds(_seconds_diff)

Calcprofit()=>
    (( close * strategy.position_size ) - (strategy.position_avg_price * strategy.position_size))
// var label t = na , label.delete(t) , t:= label.new(bar_index,high,str.tostring(mintpclogic()))

// plot(strategy.netprofit,"?!",display = display.data_window)

PNLlabel()=>    
          
    message = ""    
    message += "PNL :  " +str.tostring(math.round(Calcprofit(), 2)) + '  ' + str.tostring(syminfo.currency) + '\n'
    message += "Time:  " +get_timespan_string(glb_dealstart_bar_time, time)+ '\n'
    message += "PNL%:  " + str.tostring(math.round(Calcprofitpercent(),2))+ " %"
    topy = high + (high* 0.04)  
    label.new(bar_index + 1,
     topy, 
     text=message,
     yloc=yloc.price, 
     size=size.normal, 
     style=label.style_label_lower_left, 
     textcolor=color.black, 
     textalign = text.align_left,
     color=pnlcolor
     ) 


var float removed = na

Opentrade()=>
    strategy.opentrades > 0 ? 1 : 0

PNLpercentage()=> ((close - strategy.position_avg_price  ) /close )  * 100 

//--------------------------------------------------------------------------
//                        # Strategy Inputs #                              |
//--------------------------------------------------------------------------

// plot(strategy.opentrades,display = display.data_window,title = "OpenSZ")

if (long) and strategy.opentrades == 0 and in_date_range
    socounter := 0
    dealcount+=1
    dealcount
    glb_dealstart_bar_time      := time
    strategy.entry("LONG", strategy.long,comment = "D # " + str.tostring(dealcount),qty = base/close )
    alert("New LONG DEAL for {{ticker}}",freq = alert.freq_once_per_bar_close)
    removed:= strategy.netprofit / close

if (long) and  SOconditions() and strategy.opentrades > 0 and strategy.opentrades < sonum
    
    socounter+=1
    socounter
    strategy.entry('LONG' , strategy.long,qty = DCATYPE ? (strategy.position_size*safety) : calculateSO(socounter)/close,comment = "SO # "+str.tostring(socounter))
    alert("New DCA DEAL for {{ticker}}",freq = alert.freq_once_per_bar_close)
    
if strategy.position_size > 0 and short and (mintpbool ? mintpclogic() : true) and in_date_range
    strategy.close("LONG",comment = " ")
    alert("DEAL Close for {{ticker}}",freq = alert.freq_once_per_bar_close)
    if showpnllabel
        PNLlabel()







// hp= plot(vwma_above, color=color.new(color.red, 0))
// lp= plot(vwma_below, color=color.new(color.green, 0))
// plotshape(long and not long[1],title="Buy",style=shape.labelup,color=color.rgb(53, 141, 56),location= location.belowbar ,size=size.tiny,text= "B",textcolor = color.white)
// plotshape(short,title="Sell",style=shape.labeldown,color=color.rgb(146, 18, 13),location= location.abovebar ,size=size.tiny,text = "S",textcolor = color.white)
   
avg = plot(showdeals? strategy.position_avg_price : na, 'AVG Price',color= avgcolor, style=plot.style_linebr,editable = false)
sl = plot(showdeals ? calcNextSOprice(minSOchange): na, 'SO change %', color.orange, style=plot.style_linebr,editable = false)   
tp = plot(showdeals ? strategy.position_avg_price * (1 + mintp): na, 'SO change %', color.rgb(3, 233, 245), style=plot.style_linebr,editable = false)    
   
fill(tp, avg, color =profitcolor)
fill(avg, sl, color = socolor)
bgcolor(showBG and strategy.position_size > 0 ? color.new(bgcolor,90): na)   

statusOpen()=>
    Opentrade() == 0 ? str.tostring(Opentrade()) : str.tostring(Opentrade()) + "\n" + "------" + "\n" +  str.tostring(syminfo.currency) + " :" + "$" + str.tostring(math.round(strategy.openprofit,2))+ "\n" 
         + "------" + "\n" + "% " + " :" + str.tostring(math.round(PNLpercentage(),2))+ " %"

// if barstate.isconfirmed
//     _row = 1
//     p_row = 1
//     if show_table
//         text_color = show_table ? color.rgb(210, 210, 210) : color.black
//         table.cell(summary_table, 0, 0, table_name,
//          bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167),
//          color.rgb(240, 141, 71)),
//          text_size = size.small,
//          text_font_family=font.family_default)
//         table.cell(summary_table, 1, 0, "",
//          bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167),
//           color.rgb(240, 141, 71)),
//           text_halign = text.align_left)
//         table.merge_cells(summary_table, 0, 0, 1, 0)
//         table.cell(summary_table, 0, 1, 'Deal Status', bgcolor=color.rgb(58, 58, 59, 38),text_color = textcolos,text_size = size.small,text_font_family=font.family_default,text_halign = text.align_left)
//         table.cell(summary_table, 1, 1, statusOpen() , bgcolor=color.rgb(120, 123, 134, 38),text_color = WHITE,text_size = size.small,text_font_family=font.family_default)
//         _row += 1
//         table_cell(summary_table,_row, "Required Capital",CapitalCalculation())
//         // _row += 1
//         // table_cell(summary_table,_row, "Total PNL",close>open ? "True" : "False")
//         _row += 1
//         table_cell(summary_table,_row, "Total PNL",strategy.netprofit)


///
//

Overview

SRP Strategy [ZCrypto] enters an initial base order and places up to a configurable number of safety orders as price declines by set percentage thresholds. Positions exit once reaching a minimal take-profit percentage target. Users can customize base position size, safety order multipliers, DCA count, and backtesting date ranges. Drawn directly on the price chart, it renders deal lines, average entry price levels, PnL labels, and a performance table. The strategy operates without a hard stop-loss mechanism.

Details

Published by

veo555 on GitHub

Code credit

TZack88, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Moving averages, Screeners & dashboards

Markets

Crypto

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • 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
SRP %float1.4ChangePercentage
⬇️int55below
⬆️int100above
Minimal TP❓➔ booltruemintpbool
mintpfloat2.0mintp
Price change %float2.0minSOchange
$ Base orderfloat100base
DCA Multifloat1.5safety
DCA Countint4sonum
DCA TYPEstringVolume MultiplyDCATYPE
Backtest Datebooltruelimit_date_range
Start Timetimetimestamp('11 OCT 2022 00:00 +0000')start_time
Show all 24 settings
SettingTypeDefaultVariable
End Timetimetimestamp('31 Dec 2080 00:00 +0000')end_time
Show Table ❓booltrueshow_table
PositionstringTop Rightposition
Text ColorcolorYellowtextcolos
Deal lines❓booltrueshowdeals
profitcolorcolorbgrayprofitcolor
socolorcolorredsocolor
avgcolorcolorwhiteavgcolor
Deal BG Color❓boolfalseshowBG
bgcolorcolorbluebgcolor
PNL Label❓booltrueshowpnllabel
pnlcolorcolorolivepnlcolor
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

AC- MY SCRIPT1

by hasnocool
106 stars

This strategy plots an Optimized Trend Tracker and a selectable moving-average support line on the price chart. It builds the average as SMA, EMA, WMA, TMA, VAR, WWMA, ZLEMA, or TSF, then offsets long and short stops by a percent of that average. Optional mark

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of AC- MY SCRIPT1
104 stars

This overlay strategy combines a machine-learning distance model with a MACD oscillator to open trades on the price chart. It compares recent history using cosine similarity or Euclidean and Lorentzian distance, then filters direction with selectable moving-av

Strategy v5 AI / machine learningOscillators & momentum
Updated 3 years ago · MIT GitHub repository of MLCEL and MACD Strategy

Calculates a custom moving average (MaMA) by modifying the source price with price momentum, acceleration, and psychological win-rate probability before applying an EMA or SMA. Plots the adjusted moving average directly on the price chart alongside optional re

Strategy v5 Moving averagesTrend
Updated 4 years ago · None stated GitHub repository of Momentum Adjusted Moving Average by DGT

This long-only trend-following strategy combines Ichimoku Kinko Hyo components with higher timeframe moving average filters. It triggers long entries when price trades above a higher timeframe EMA and a bullish Tenkan-Sen cross above Kijun-Sen occurs under fav

Strategy v5 TrendOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of Ichimoku Kinko Hyo Momentum Strategy

Daily Loss Limit [Lab]

by mitchell-917
4 stars

This strategy example enforces a daily loss limit. It detects a new trading day, stores starting equity, and tracks the day's highest and lowest equity. Trading permission depends on whether the loss from the day's starting equity stays inside a percentage of

Strategy v5 Moving averagesSessions & time
Updated 11 months ago · Custom licence GitHub repository of Daily Loss Limit [Lab]
4 stars

This strategy enters a long position when a short RSI falls below a user threshold and price is above a simple moving average trend filter. It closes the long when RSI rises above a second threshold and does not set a stop loss. Position size defaults to full

Strategy v6 Oscillators & momentumMoving averages
Updated 13 days ago · MIT GitHub repository of RSI(2) pullback + TokIO check

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