Strategy · Pine Script v5 · On the chart

SassizStocEMA-Lazy Bear

by sassiz-root· code credited to Sassiz

SassizStocEMA-Lazy Bear is a Pine Script strategy that plots on the price chart and combines a stochastic oscillator with near and far exponential moving averages.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code200
Settings22inputs
LicenceMIT
Last update3 years ago23 Feb 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

200 lines of Pine Script v5 from Lazy Bear v1.6 2022-06-13(trail-stoploss).pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

Lazy Bear v1.6 2022-06-13(trail-stoploss).pine
//  _,-""`""-~`)
//(`~_,=========\
// |---,___.-.__,\
// |        o     \ ___  _,,,,_     _.--.
//  \      `^`    /`_.-"~      `~-;`     \
//   \_      _  .'                 `,     |
//     |`-                           \'__/ 
//    /                      ,_       \  `'-. 
//   /    .-""~~--.            `"-,   ;_    /
//  |              \               \  | `""`
//   \__.--'`"-.   /_               |'
//              `"`  `~~~---..,     |
//    Lazy Bear                \ _.-'`-.
//  Author: Sassiz              \       \
//    Trade Robot                '.     /
//      V1.5  Trail Stop Price     `"~"`

//_____/\\\\\\\\\\\_______/\\\\\\\\\________/\\\\\\\\\\\_______/\\\\\\\\\\\____/\\\\\\\\\\\__/\\\\\\\\\\\\\\\______________/\\\\\\\\\___________/\\\\\____________/\\\\\_______/\\\\\\\\\\\\\\\_        
// ___/\\\/////////\\\___/\\\\\\\\\\\\\____/\\\/////////\\\___/\\\/////////\\\_\/////\\\///__\////////////\\\_____________/\\\///////\\\_______/\\\///\\\________/\\\///\\\____\///////\\\/////__       
//  __\//\\\______\///___/\\\/////////\\\__\//\\\______\///___\//\\\______\///______\/\\\_______________/\\\/_____________\/\\\_____\/\\\_____/\\\/__\///\\\____/\\\/__\///\\\________\/\\\_______      
//   ___\////\\\_________\/\\\_______\/\\\___\////\\\___________\////\\\_____________\/\\\_____________/\\\/_______________\/\\\\\\\\\\\/_____/\\\______\//\\\__/\\\______\//\\\_______\/\\\_______     
//    ______\////\\\______\/\\\\\\\\\\\\\\\______\////\\\___________\////\\\__________\/\\\___________/\\\/_________________\/\\\//////\\\____\/\\\_______\/\\\_\/\\\_______\/\\\_______\/\\\_______    
//     _________\////\\\___\/\\\/////////\\\_________\////\\\___________\////\\\_______\/\\\_________/\\\/___________________\/\\\____\//\\\___\//\\\______/\\\__\//\\\______/\\\________\/\\\_______   
//      __/\\\______\//\\\__\/\\\_______\/\\\__/\\\______\//\\\___/\\\______\//\\\______\/\\\_______/\\\/_____________________\/\\\_____\//\\\___\///\\\__/\\\_____\///\\\__/\\\__________\/\\\_______  
//       _\///\\\\\\\\\\\/___\/\\\_______\/\\\_\///\\\\\\\\\\\/___\///\\\\\\\\\\\/____/\\\\\\\\\\\__/\\\\\\\\\\\\\\\___________\/\\\______\//\\\____\///\\\\\/________\///\\\\\/___________\/\\\_______ 
//        ___\///////////_____\///________\///____\///////////_______\///////////_____\///////////__\///////////////____________\///________\///_______\/////____________\/////_____________\///________


// Lazy Bear v1.4 1401-03-03
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sassiz

//@version=5
strategy("SassizStocEMA-Lazy Bear v1.4", overlay=true,shorttitle="LazyBear",initial_capital=1000,currency=currency.USD,pyramiding=1,commission_type=strategy.commission.percent,commission_value=0.1,default_qty_type=strategy.percent_of_equity ,default_qty_value=100)

trendIsLong= input.bool(false,title="UpTrend",group = "Trend Type",inline="Trend",confirm=true)
trendIsShort= input.bool(false,title="DownTrend",group = "Trend Type",inline="Trend",confirm=true)
slLong = input.float(1,title="Long Stop Loss (%)   ",minval=0.0, step=0.1,group = "SL",inline="TpSl",confirm=true) * 0.01//input.float(0.985,title="SL-Long",step=0.01)
slShort = input.float(1,title="Short Stop Loss  (%)   ",minval=0.0, step=0.1,group = "SL",inline="TpSl",confirm=true) * 0.01//input.float(1.015,title="SL-Short",step=0.01)
tpLong = input.float(1.5,title="Long Take Profit 1 (%)",minval=0.0, step=0.1,group = "TP",inline="TpSl",confirm=true) * 0.01//input.float(1.03,title="TP-Long",step=0.01)
tpShort = input.float(1.5,title="Short Take Profit 1(%)",minval=0.0, step=0.1,group = "TP",inline="TpSl",confirm=true) * 0.01//input.float(0.97,title="TP-Short",step=0.01)
tpLong2 = input.float(2,title="Long Take Profit 2 (%)",minval=0.0, step=0.1,group = "TP",inline="TpSl",confirm=true) * 0.01
tpShort2 = input.float(2,title="Short Take Profit 2 (%)",minval=0.0, step=0.1,group = "TP",inline="TpSl",confirm=true) * 0.01
//TP1_Ratio = input(title="Sell Postion Size % @ TP1", type=input.float, defval=50, step=1, group="TP & SL", tooltip="Example: 50 closing 50% of the position once TP1 is reached")/100

upperBand1 = input.int(80,title="Upper-Band",confirm=true)
lowerBand1 = input.int(20,title="Lower-Band",confirm=true)

isBiggerTF= input.bool(false,title="Bigger-TF",group = "Bigger TimeFrame",inline="BTF",confirm=true)
biggerTF = input.timeframe('30', "Bigger-Resolution", options=['30', '60','120', '240'],group = "Bigger TimeFrame",inline="BTF",confirm=true)

//trade time zone
StartTime = input.time(defval=timestamp('14 May 2022 00:00 +0000'), title='Start Time',group = "Strategy Time Range",confirm=true)
EndTime = input.time(defval=timestamp('30 Jun 2022 23:59 +0000'), title='End Time',group = "Strategy Time Range",confirm=true)
InDateRange = time>=StartTime and time<=EndTime
bgcolor(color=InDateRange?color.new(color.blue,95):na)

//ema 100 and ema 200
lenEmaNear = input.int(100, minval=1, title="Near Length",confirm=true,group = "Options",inline="ema")
lenFarNear = input.int(200, minval=1, title="Far Length",confirm=true,group = "Options",inline="ema")
src = input.source(close, title="Source",group = "Options")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500,confirm=true,group = "Options")
outNearEma = ta.ema(src, lenEmaNear)
outFarEma = ta.ema(src, lenFarNear)


btc_close_30M = request.security('',biggerTF,src)
btc30Ema50 = ta.ema(btc_close_30M,50)
btc30Ema100 = ta.ema(btc_close_30M,100)
btc30Ema200 = ta.ema(btc_close_30M,200)
plot(isBiggerTF?btc30Ema50:na, title="BTF-50", color=color.green, offset=offset)
plot(isBiggerTF?btc30Ema100:na, title="BTF-100", color=color.red, offset=offset)
plot(isBiggerTF?btc30Ema200:na, title="BTF-200", color=color.orange, offset=offset)
plot(outNearEma, title="EMA-Fast", color=color.white, offset=offset)
plot(outFarEma, title="EMA-Slow", color=color.blue, offset=offset)

//stoch
periodK = input.int(14, title="%K Length", minval=1,confirm=true,group = "Options")
smoothK = input.int(1, title="%K Smoothing", minval=1,confirm=true,group = "Options")
periodD = input.int(3, title="%D Smoothing", minval=1,confirm=true,group = "Options")
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
// plot(k, title="%K", color=#2962FF)
// plot(d, title="%D", color=#FF6D00)
// h0 = hline(80, "Upper Band", color=#787B86)
// h1 = hline(20, "Lower Band", color=#787B86)

//begin strategy
CrossBars = input.int(1,minval=0,title="Number of Bars to Confirm Cross")
CrossOverConfirm(x,y) =>
 ta.barssince(ta.crossover(x,y)) == CrossBars and x>=y
CrossUnderConfirm(x,y) =>
 ta.barssince(ta.crossunder(x,y)) == CrossBars and x<=y
biggerEmaLong = isBiggerTF?btc30Ema200<btc30Ema100 and btc30Ema100<btc30Ema50:true
biggerEmaShort = isBiggerTF?btc30Ema200>btc30Ema100 and btc30Ema100>btc30Ema50:true
PK_X_PD =
 //long                                                                                                                                 (30 M Trend is positive)                            (ema 100 slope positive)
 k>d and ((k<lowerBand1 and d<lowerBand1) or (k[1]<lowerBand1 and d[1]<lowerBand1) or (k[2]<lowerBand1 and d[2]<lowerBand1)) and (outNearEma>outFarEma) and (high>close[1] and high>close[2]) and (open==low) and biggerEmaLong?1
 //short                                                                                                                                        (30 M Trend is negetive)                                 (ema 100 slope positive)
 :k<d and ((k>upperBand1 and d>upperBand1) or (k[1]>upperBand1 and d[1]>upperBand1) or (k[2]>upperBand1 and d[2]>upperBand1)) and (outNearEma<outFarEma) and (low<close[1] and low<close[2]) and (open==high) and biggerEmaShort?-1
 :0
PK_X_PD_Long = PK_X_PD>0
PK_X_PD_Short = PK_X_PD<0



if(InDateRange)
    //strategy long
    strategy.entry('buy',strategy.long,when=PK_X_PD_Long and trendIsLong and strategy.position_size ==0)
    //strategy short
    strategy.entry('short',strategy.short,when=PK_X_PD_Short and trendIsShort and strategy.position_size ==0)

//alertcondition(PK_X_PD_Short or PK_X_PD_Long, "SStochEma Signal Alert",  "Go Trade with SStochEma Signal")

inTrade = strategy.position_size //if <0 trade position is short and if >0 trade postion is long and if = 0 no postion 


stopPrice = 0.0
longProfitPrice = 0.0
shortProfitPrice = 0.0
changeStopPrice = false

if strategy.position_size < 0
    shortProfitPrice := strategy.position_avg_price * (1-tpShort2)
    stopPrice := if (strategy.position_size < 0)
        stopValue = strategy.position_avg_price * (1 + slShort)
        if stopPrice[1] !=0 and low < stopPrice[1] * (1-(slShort* 2))
            changeStopPrice := true
            stopPrice[1] * (1-slShort)
        else if stopPrice[1] > 0
            math.min(stopValue,stopPrice[1])
        else 
            stopValue
    else
        0
else if strategy.position_size > 0
    longProfitPrice := strategy.position_avg_price * (1+tpLong2)
    stopPrice := if (strategy.position_size > 0)
        stopValue = strategy.position_avg_price * (1 - slLong)
        if stopPrice[1] !=0 and high > stopPrice[1] * (1+(slLong* 2))
            changeStopPrice := true
            stopPrice[1] * (1+slLong)

        else if stopPrice[1] > 0
            math.max(stopValue,stopPrice[1])
        else 
            stopValue
    else
        0

if changeStopPrice
    alertsyntax_change_stop = '{' + '\"method\":\"changeStop\",\"changeStopPrice\":\"' + str.tostring(stopPrice) +'\",\"market\":\"' + syminfo.ticker + '\"}'
    alert(message=alertsyntax_change_stop, freq=alert.freq_once_per_bar_close)
        

strategy.exit("TP3Short",from_entry="short",stop=stopPrice != 0? stopPrice:strategy.position_avg_price * (1 + slShort))
    
strategy.exit("TP2Buy",from_entry="buy",stop=stopPrice!=0?stopPrice:strategy.position_avg_price * (1 - slLong))

plotshape(PK_X_PD_Long and inTrade==0,title="Signal Long",style=shape.triangleup,color=color.green,location=location.bottom,size=size.small)
plotshape(PK_X_PD_Short and inTrade==0,title="Signal Short",style=shape.triangledown,color=color.red,location=location.top,size=size.small)

//alert for call robot webhook
if PK_X_PD_Long and trendIsLong
    enteryPriceCalculated = (close + open)/2
    //alertsyntax_golong = '{' + '\"price\":\"' + str.tostring(strategy.position_avg_price) + '\",\"stoploss\":\"' + str.tostring(strategy.position_avg_price * slLong) + '\",\"takeprofit\":\"' + str.tostring(strategy.position_avg_price * tpLong) + '\",\"side\":2' + ',\"market\":\"' + syminfo.ticker + '\"}'
    alertsyntax_golong = '{' + '\"price\":\"' + str.tostring(enteryPriceCalculated) + '\",\"stoploss\":\"' + str.tostring(enteryPriceCalculated * (1-slLong)) + '\",\"takeprofit\":\"' + str.tostring(enteryPriceCalculated * (1+tpLong2)) + '\",\"riskfree\":\"' + str.tostring(enteryPriceCalculated * (1+slLong)) + '\",\"takeprofit1\":\"' +  str.tostring(enteryPriceCalculated * (1+tpLong)) + '\",\"takeprofit1\":\"' + str.tostring(enteryPriceCalculated * (1+tpLong)) + '\",\"side\":2' + ',\"market\":\"' + syminfo.ticker + '\"}'
    alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close)
if PK_X_PD_Short and trendIsShort
    enteryPriceCalculated = (close + open)/2
    //alertsyntax_goshort = '{' + '\"price\":\"' + str.tostring(strategy.position_avg_price) + '\",\"stoploss\":\"' + str.tostring(strategy.position_avg_price * slShort) + '\",\"takeprofit\":\"' + str.tostring(strategy.position_avg_price * tpShort) + '\",\"side\":1' + ',\"market\":\"' + syminfo.ticker + '\"}'
    alertsyntax_goshort = '{' + '\"price\":\"' + str.tostring(enteryPriceCalculated) + '\",\"stoploss\":\"' + str.tostring(enteryPriceCalculated * (1+slShort)) + '\",\"takeprofit\":\"' + str.tostring(enteryPriceCalculated * (1-tpShort2)) +  '\",\"riskfree\":\"' + str.tostring(enteryPriceCalculated * (1-slShort)) +  '\",\"takeprofit1\":\"' + str.tostring(enteryPriceCalculated * (1-tpShort)) + '\",\"side\":1' + ',\"market\":\"' + syminfo.ticker + '\"}'
    alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close)


//for sell and buy show risk/reward
entery = plot(inTrade<0 ? strategy.position_avg_price :strategy.position_avg_price,color=color.purple,style=plot.style_circles,title="entery",trackprice=false)
//profit = plot(inTrade<0 ? strategy.position_avg_price * (1-tpShort):strategy.position_avg_price * (1+tpLong),color=color.green,style=plot.style_circles,title="TP1",trackprice=false)
profit2 = plot(inTrade<0 ? stopPrice<shortProfitPrice?stopPrice:shortProfitPrice:stopPrice>longProfitPrice?stopPrice:longProfitPrice,color=color.green,style=plot.style_circles,title="TP2",trackprice=false)
//riskFree = plot(inTrade<0 ? strategy.position_avg_price * (1-slShort):strategy.position_avg_price * (1+slLong),color=color.yellow,style=plot.style_circles,title="Risk Free",trackprice=false)
stop = plot(inTrade<0 ? strategy.position_avg_price * (1+slShort):strategy.position_avg_price * (1-slLong),color=color.red,style=plot.style_circles,title="SL",trackprice=false)
stop2 = plot(inTrade<0?stopPrice:stopPrice,color=color.yellow,style=plot.style_circles,title="SL2",trackprice=false)
fill(entery,profit2,title="Reward",color= color.new(color.green,65))
fill(entery,stop,title="Risk",color= color.new(color.red,65))

tableColumn = 2
tableRow = 6
var table panel = table.new(position.top_right, tableColumn, tableRow)
table.cell(panel, 0, 0, "Hello Sassiz", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 0, "Lazy Bear", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 0, 1, "Net Profit", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 1,str.tostring(strategy.netprofit), bgcolor=color.new(color.black,65), text_color=strategy.netprofit>0?color.green:color.red)
table.cell(panel, 0, 2, "Winning Trade", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 2,str.tostring(strategy.wintrades), bgcolor=color.new(color.black,65), text_color=color.green)
table.cell(panel, 0, 3, "Loss Trade", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 3,str.tostring(strategy.losstrades), bgcolor=color.new(color.black,65), text_color=color.red)
table.cell(panel, 0, 4, "Max Down", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 4,str.tostring(strategy.max_drawdown), bgcolor=color.new(color.black,65), text_color=color.red)
table.cell(panel, 0, 5, "R&R", bgcolor=color.new(color.black,65), text_color=color.white)
table.cell(panel, 1, 5,str.tostring(tpLong2/slLong), bgcolor=color.new(color.black,65), text_color=color.red)

Overview

SassizStocEMA-Lazy Bear is aimed at crypto markets. Long and short directions can be enabled separately, and crosses are confirmed over a set number of bars. Entries use percentage stop loss and two take-profit targets. Optional higher-timeframe data, stochastic band levels, EMA lengths, and a start-to-end date window change the signals. The visible code does not describe exit logic beyond those percentage targets.

Details

Published by

sassiz-root on GitHub

Code credit

Sassiz, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Moving averages

Markets

Crypto

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
UpTrendboolfalsetrendIsLong
DownTrendboolfalsetrendIsShort
Long Stop Loss (%) float1slLong
Short Stop Loss (%) float1slShort
Long Take Profit 1 (%)float1.5tpLong
Short Take Profit 1(%)float1.5tpShort
Long Take Profit 2 (%)float2tpLong2
Short Take Profit 2 (%)float2tpShort2
Upper-Bandint80upperBand1
Lower-Bandint20lowerBand1
Bigger-TFboolfalseisBiggerTF
Bigger-Resolutiontimeframe30biggerTF
Show all 22 settings
SettingTypeDefaultVariable
Start Timetimetimestamp('14 May 2022 00:00 +0000')StartTime
End Timetimetimestamp('30 Jun 2022 23:59 +0000')EndTime
Near Lengthint100lenEmaNear
Far Lengthint200lenFarNear
Sourcesourceclosesrc
Offsetint0offset
%K Lengthint14periodK
%K Smoothingint1smoothK
%D Smoothingint3periodD
Number of Bars to Confirm Crossint1CrossBars
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

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average

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
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

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