name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Maximized Moving Average Crossing (by Coinrule) | https://www.tradingview.com/script/U8616A9S-Maximized-Moving-Average-Crossing-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 360 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © relevantLeader16058
//@version=4
strategy(shorttitle='Maximized Moving Average Crossing ',title='Maximized Moving Average Crossing (by Coinrule)', overlay=true, initial_capital=1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
//MA inputs and calculations
inlong=input(50, title='MA long period')
inshort=input(9, title='MA short period')
MAlong = sma(close, inlong)
MAshort= sma(close, inshort)
// RSI inputs and calculations
lengthRSI = (14)
RSI = rsi(close, lengthRSI)
RSI_Signal = input(55, title = 'RSI Trigger', minval=1)
//Entry and Exit
bullish = crossover(MAshort, MAlong)
bearish = crossunder(MAshort, MAlong)
strategy.entry(id="long", long = true, when = bullish and RSI > RSI_Signal and window())
strategy.close(id="long", when = bearish and window())
plot(MAshort, color=color.purple, linewidth=2)
plot(MAlong, color=color.red, linewidth=2) |
CHOP Zone Entry Strategy + DMI/PSAR Exit | https://www.tradingview.com/script/GrP0zABg-CHOP-Zone-Entry-Strategy-DMI-PSAR-Exit/ | IronCasper | https://www.tradingview.com/u/IronCasper/ | 1,015 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// Title: "CHOP Zone Entry Strategy + DMI/PSAR Exit"
// Revision: 1.2
// Author: © IronCasper
//@version=4
strategy("CHOP Zone Entry Strategy + DMI/PSAR Exit", shorttitle="CHOP Zone Strategy", default_qty_value=1, overlay=false)
//-----------------------//
// Inputs //
//-----------------------//
showChopAs = input(title="Show Chop Index as", defval="Colored Line (PSAR)", options=["Line", "Colored Line (MOM)", "Colored Line (PSAR)", "Columns"])
lookbackPeriod = input(14, title="Lookback Period", minval=1)
smoothLength = input(4, title="Smooth Length", minval=1)
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
tradeType = input(title="Strategy Direction", defval="Follow Trend", options=["Short Only", "Long Only", "Both", "Follow Trend"])
sensitivity = input(title="Alert Sensitivity", type=input.integer, defval=1, minval=1, maxval=10)
colorBg = input(true, title="Color Background to CHOP State", type=input.bool)
colorBars = input(true, title="Color Candles to CHOP State", type=input.bool)
enableDMI = input(true, title="════ Enable Directional Movement Index ════", type=input.bool)
adxLen = input(14, title="ADX Smoothing")
diLen = input(14, title="DI Length")
adxKeyLevel = input(25, title="Key Level for ADX", type=input.integer, minval=1, maxval=100)
enablePSAR = input(true, title="════ Enable Parabolic Stop and Reverse ════", type=input.bool)
psarStart = input(defval=0.015, title="Start", type=input.float, step=0.015, minval=0)
psarIncr = input(defval=0.001, title="Increment", type=input.float, step=0.001, minval=0)
psarMax = input(defval=0.2, title="Max Value", type=input.float, step=0.2, minval=0)
//---------------------------------------------------------------------------------------//
// Calculate Chop //
// ... derived from TradingView Reference Manual //
// https://www.tradingview.com/support/solutions/43000501980-choppiness-index-chop //
//---------------------------------------------------------------------------------------//
sumAtrOverLookback = sum(atr(1), lookbackPeriod) // sum of the Avg True Range over past n bars
maxHi = highest(high >= close[1] ? high : close[1], lookbackPeriod) // highest high over past n bars
minLo = lowest(low <= close[1] ? low : close[1], lookbackPeriod) // lowest low over past n bars
chopIndex = 100 * log10( sumAtrOverLookback / ( maxHi - minLo ) ) / log10(lookbackPeriod)
// Smooth (average) Chop Index if user selected option
chopIndex := sma(chopIndex, smoothLength) // a value of 1 has the same effect as disabiling the smooth feature
//----------------------------//
// Determine Chop conditions //
//----------------------------//
condChopIndex38minus = chopIndex <= 38.2 and close[1] > close ? true : false // 38.2-
condChopIndex38to45 = chopIndex >= 38.2 and chopIndex < 45 ? true : false // 38.2 to 45
condChopIndex45to55 = chopIndex >= 45 and chopIndex < 55 ? true : false // 45 to 55
condChopIndex55to61 = chopIndex >= 55 and chopIndex < 61.8 ? true : false // 55 to 61.8
condChopIndex61plus = chopIndex >= 61.8 and close[1] < close ? true : false // 61.8+
// Extra conditions for chop zone background color
condChopIndex30minus = chopIndex <= 30 and close[1] > close ? true : false // 30-
condChopIndex30to38 = chopIndex > 30 and chopIndex < 38.2 ? true : false // 30 to 38.2
condChopIndex61to70 = chopIndex >= 61.8 and chopIndex < 70 ? true : false // 61.8 to 70
condChopIndex70plus = chopIndex >= 70 and close[1] < close ? true : false // 70+
//-----------------------------------------------------------//
// Compute Momentum State for Trend Line and Entry Determination //
//-----------------------------------------------------------//
// Borrowed from script by LazyBear
val = linreg(close - avg(avg(highest(high, lookbackPeriod), lowest(low, lookbackPeriod)), ema(close, lookbackPeriod)), lookbackPeriod, 0)
// Determine Momenteum State
curr_momUpTrend = val > nz(val[1])
curr_momDnTrend = val < nz(val[1])
// Determine Momentum Line Color
momentumLineColor = curr_momUpTrend ? color.green : (curr_momDnTrend ? color.maroon : na)
//-----------------------------------------------------------------------//
// Calculate Parabolic SAR for Trend Line and Entry/Exit Determination //
//-----------------------------------------------------------------------//
// Use built-in parabolic sar function
psar = sar(psarStart, psarIncr, psarMax)
// Determine psar trending state
psarTrendState = psar < close ? "up" : "dn"
// Determine PSAR Line Color
psarLineColor = psarTrendState == "up" ? color.green : (psarTrendState == "dn" ? color.maroon : na)
//------------------------------------------------------//
// Color Candles & Chop Index Line based on Chop State //
//------------------------------------------------------//
// Create user defined chop limit
hli1 = hline(showChopAs != "Columns" ? 38.2 : na, linestyle=hline.style_dotted, editable=false) // Loose Chop Lower Limit
hli2 = hline(showChopAs != "Columns" ? 61.8 : na, linestyle=hline.style_dotted, editable=false) // Loose Chop Upper Limit
fill(hli1, hli2, color=color.yellow, transp=95, editable=false)
// Plot Chop Index Line
lineColor = showChopAs == "Colored Line (PSAR)" ? psarLineColor : (showChopAs == "Colored Line (MOM)" ? momentumLineColor : color.gray)
plot(showChopAs != "Columns" ? chopIndex : na, style=plot.style_linebr, linewidth=2, color=lineColor, offset=offset, editable=false)
// Plot bars to match chop state
var color candleColor = na
candleColor := condChopIndex38minus ? #800080 : candleColor // Short
candleColor := condChopIndex38to45 ? color.yellow : candleColor // Loose Chop
candleColor := condChopIndex45to55 ? #000000 : candleColor // Tight Chop
candleColor := condChopIndex55to61 ? color.yellow : candleColor // Loose Chop
candleColor := condChopIndex61plus ? #0000FF : candleColor // Long
barcolor(colorBars ? candleColor : na, editable=false)
//-----------------------//
// Plot Chop Zone //
//-----------------------//
var color chopZoneColor = na
chopZoneColor := condChopIndex30minus ? #800080 : chopZoneColor // Dark Purple
chopZoneColor := condChopIndex30to38 ? color.purple : chopZoneColor
chopZoneColor := condChopIndex38to45 ? color.yellow : chopZoneColor
chopZoneColor := condChopIndex45to55 ? #000000 : chopZoneColor // Black
chopZoneColor := condChopIndex55to61 ? color.yellow : chopZoneColor
chopZoneColor := condChopIndex61to70 ? color.blue : chopZoneColor
chopZoneColor := condChopIndex70plus ? #0000FF : chopZoneColor // Dark Blue
// Plot columns vs bgcolor if Chop Index is not shown
plot(showChopAs == "Columns" ? 1 : na, color=chopZoneColor, style=plot.style_columns, transp=70, editable=false)
// Plot as bgcolor if selected in Line view
chopZoneColor := colorBg and showChopAs != "Columns" ? chopZoneColor : na
bgcolor(color=chopZoneColor, transp=80, editable=false)
//-----------------------------------------------------------------------------------------//
// Compute DMI //
// ... derived from TradingView Reference Manual //
// https://www.tradingview.com/chart/?solution=43000502250 //
// //
// This is the same script as used in my DMI study //
// https://www.tradingview.com/script/9OoEHrv5-Directional-Movement-Index-DMI-Alerts //
//-----------------------------------------------------------------------------------------//
// Part 1 - Calculate +DI and -DI
dirmov(diLen) =>
// Determine Directional Movement
upMove = change(high) // current high - previous high
downMove = -change(low) // current low - previous low
// Determine +DM and -DI by High, Low, and Close for each period
plusDI = upMove > downMove and upMove > 0 ? upMove : 0
minusDI = downMove > upMove and downMove > 0 ? downMove : 0
// Update DM based on the number of user defined periods
trueRange = ema(tr, diLen)
plusDI := fixnan(100 * ema(plusDI, diLen) / trueRange)
minusDI := fixnan(100 * ema(minusDI, diLen) / trueRange)
[plusDI, minusDI] // Return
// Part 2 - Calculate ADX
adx(diLen, adxLen) =>
[plusDI, minusDI] = dirmov(diLen)
// Determine the ADX
tmp = abs((plusDI - minusDI) / (plusDI + minusDI))
adx = fixnan(100 * ema(tmp, adxLen))
[adx, plusDI, minusDI] // Return
// Get ADX and DI from function
[adxSignal, plusDI, minusDI] = adx(diLen, adxLen)
//-------------------------------------------------------//
// Determine Trade State for Long/Short Entry //
//-------------------------------------------------------//
// Establish long and short actions
goLong = condChopIndex61plus and not(condChopIndex61plus[sensitivity]) and (enableDMI ? adxSignal > adxKeyLevel : true)
goShort = condChopIndex38minus and not(condChopIndex38minus[sensitivity]) and (enableDMI ? adxSignal > adxKeyLevel : true)
// Increment to user selected sensitivity to only trigger actions on the n-th candle
if sensitivity != 1 and (goLong or goShort) // bypass if sensitivity equals one or no active go
for i = 1 to sensitivity-1
// Update long action based on past states
if( condChopIndex61plus[i] != condChopIndex61plus )
goLong := false
//break // break loop if any candles aren't in a long state
//bool(na) // required to trick compiler to return from loop
// Update short action based on past states
if( condChopIndex38minus[i] != condChopIndex38minus )
goShort := false//, break, bool(na)
// Clear action if it doesn't follow the trend, if user selected
if tradeType == "Follow Trend"
goLong := showChopAs == "Colored Line (Momentum)" ? (curr_momUpTrend ? goLong : na) : (psarTrendState == "up" ? goLong : na)
goShort := showChopAs == "Colored Line (Momentum)" ? (curr_momDnTrend ? goShort : na) : (psarTrendState == "dn" ? goShort : na)
//-------------------------------------------------------//
// Determine Trade State for Exit and Reverse //
//-------------------------------------------------------//
// Declare Active Position Identifiers
var bool activeLong = false
var bool activeShort = false
// Determine DMI Close Trade Action, if applicable
dmiCloseLong = enableDMI ? adxSignal < adxKeyLevel and minusDI > plusDI : false
dmiCloseShort = enableDMI ? adxSignal < adxKeyLevel and plusDI > minusDI : false
// Determine PSAR Close Trade Action, if applicable
psarCloseLong = enablePSAR ? psarTrendState == "dn" and psarTrendState[1] == "up" : false
psarCloseShort = enablePSAR ? psarTrendState == "up" and psarTrendState[1] == "dn" : false
// Determine Default Close Trade Action (Chop Index Reversal), if PSAR or DMI not selected
chopCloseLong = enablePSAR or enableDMI ? false : chopIndex < 38.2
chopCloseShort = enablePSAR or enableDMI ? false : chopIndex > 61.8
// Consolidate close actions to a single variable
closeLongState = activeLong and (psarCloseLong or dmiCloseLong or chopCloseLong or goShort)
closeShortState = activeShort and (psarCloseShort or dmiCloseShort or chopCloseShort or goLong)
// Determine if in a Reverse Position State
goReverse = (closeLongState and goShort) or (closeShortState and goLong) ? true : false
// Determine new close action based on reverse state
goClose = not(goReverse) and (closeLongState or closeShortState) ? true : false
//--------------------------------//
// Plot Entry and Exits //
//--------------------------------//
// Determine User Selected Trade Types
longSelected = tradeType == "Both" or tradeType == "Follow Trend" ? true : tradeType == "Long Only" ? true : false
shortSelected = tradeType == "Both" or tradeType == "Follow Trend" ? true : tradeType == "Short Only" ? true : false
reverseAllowed = tradeType == "Both" or tradeType == "Follow Trend"
// Identify series for when plotting shapes at the absolute location
plotSeries = showChopAs != "Columns" ? chopIndex : 0
// Plot Long and Short Indicators only on first entering state (i.e., position not already active)
plotshape(not(activeLong) and longSelected and goLong and not(goReverse) ? plotSeries : na
, style=shape.circle, location=location.absolute, size=size.tiny, color=color.lime, text="Long", title="Long")
plotshape(not(activeShort) and shortSelected and goShort and not(goReverse) ? plotSeries : na
, style=shape.circle, location=location.absolute, size=size.tiny, color=color.red, text="Short", title="Short")
// Consolidate active actions to one variable
active = activeLong or activeShort
// Plot Close Indicator
plotshape(active and goClose ? plotSeries : na
, style=shape.xcross, location=location.absolute, size=size.tiny, color=color.olive, text="Close", title="Close")
// Plot Reverse Indicator
plotshape(active and reverseAllowed and goReverse ? plotSeries : na
, style=shape.diamond, location=location.absolute, size=size.tiny, color=color.blue, text="Reverse", title="Reverse")
//-------------------------------------//
// Chop Alerts + Strategy //
//-------------------------------------//
// Create Long/Short/Close/Reverse Strategies with Custom Alert Messages
// ... and log active long and short positions to prevent pyramiding before a close or reverse
if not(activeLong) and longSelected and goLong and not(goReverse)
strategy.entry("Long", strategy.long, alert_message="Buy {{ticker}} from Chop Zone Strategy") // Open Long
activeLong := true
if not(activeShort) and shortSelected and goShort and not(goReverse)
strategy.entry("Short", strategy.short, alert_message="Sell {{ticker}} from Chop Zone Strategy") // Open Short
activeShort := true
if active and reverseAllowed
if goLong and goReverse
strategy.entry("Long", strategy.long, alert_message="Reverse {{ticker}} from Chop Zone Strategy") // Reverse Short to Long
activeLong := true
activeShort := false
if goShort and goReverse
strategy.entry("Short", strategy.short, alert_message="Reverse {{ticker}} from Chop Zone Strategy") // Reverse Long to Short
activeShort := true
activeLong := false
strategy.close("Long", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Long
strategy.close("Short", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Short
if goClose
activeLong := false
activeShort := false |
VBand Strategy | https://www.tradingview.com/script/PuCNgwvG-VBand-Strategy/ | Saravanan_Ragavan | https://www.tradingview.com/u/Saravanan_Ragavan/ | 208 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Saravanan_Ragavan
// This is purely base on the vwap and atr14. This is very simple strategy
// Updates
// 1) Changed Entry and Exit Labels and added Buy, Sell and Exit Symbols in the bottom
//@version=4
strategy("VBand Strategy", overlay=true)
// showing Vwap line
plot(vwap, color=color.black)
// showing vwap + atr (14) line
aboveline= vwap + atr(14)
// showing vwap - atr (14) line
belowline= vwap - atr(14)
//showing above atr and below atr and fill the gap
a1 = plot(aboveline, color=color.green)
b1 = plot(belowline, color=color.red)
fill(a1, b1, color.blue)
// Buy above Buy Line
if (crossover(close,aboveline))
strategy.entry("Buy", strategy.long, comment="Buy")
// Exit Long Below Vwap
strategy.close("Buy", when = close<vwap)
// Sell above Buy Line
if (crossunder(close,belowline))
strategy.entry("Sell", strategy.short, comment="Sell")
// Exit Short above Vwap
strategy.close("Sell", when = close>vwap)
plotchar(crossover(close,aboveline) and strategy.opentrades==0, title="Buy Signal", char="▲", location = location.bottom, color=color.green, transp=5, text="Buy", textcolor=color.green)
plotchar(crossunder(close,vwap) and strategy.opentrades!=0, title="Buy Exit", char="◼", location = location.bottom, color=color.black, transp=5, text="B Exit", textcolor=color.black)
plotchar(crossunder(close,belowline) and strategy.opentrades==0, title="Sell Signal", char="▼", location = location.bottom, color=color.red, transp=5, text="Sell", textcolor=color.red)
plotchar(crossover(close,vwap) and strategy.opentrades!=0, title="Sell Exit", char="◼", location = location.bottom, color=color.black, transp=5, text="S Exit", textcolor=color.black)
|
OBV Pyr | https://www.tradingview.com/script/sAP5k4bs-OBV-Pyr/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 669 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni
//@version=4
strategy(title = " OBV Pyr", overlay = true, pyramiding=5,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 20, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.075)
strat_dir_input = input(title="Strategy Direction", defval="long", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
//
fastLength = input(250, title="Fast filter length ", minval=1)
slowLength = input(500,title="Slow filter length", minval=1)
source=close
v1=ema(source,fastLength)
v2=ema(source,slowLength)
//
filter=true
src = close
LengthOBV = input(20)
nv = change(src) > 0 ? volume : change(src) < 0 ? -volume : 0*volume
c = cum(nv)
c_tb = c - sma(c,LengthOBV)
// Conditions
longCond = crossover(c_tb,0)
//shortCond =crossunder(cnv_tb,0)
//
longsignal = (v1 > v2 or filter == false ) and longCond
//shortsignal = (v1 < v2 or filter == false ) and shortCond
//set take profit
ProfitTarget_Percent = input(3)
Profit_Ticks = close * (ProfitTarget_Percent / 100) / syminfo.mintick
//set take profit
LossTarget_Percent = input(10)
Loss_Ticks = close * (LossTarget_Percent / 100) / syminfo.mintick
////Order Placing
//
strategy.entry("Entry 1", strategy.long, when=strategy.opentrades == 0 and longsignal)
//
strategy.entry("Entry 2", strategy.long, when=strategy.opentrades == 1 and longsignal)
//
strategy.entry("Entry 3", strategy.long, when=strategy.opentrades == 2 and longsignal)
//
strategy.entry("Entry 4", strategy.long, when=strategy.opentrades == 3 and longsignal)
//
strategy.entry("Entry 5", strategy.long, when=strategy.opentrades == 4 and longsignal)
//
strategy.entry("Entry 6", strategy.long, when=strategy.opentrades == 5 and longsignal)
//
strategy.entry("Entry 7", strategy.long, when=strategy.opentrades == 6 and longsignal)
//
//
//
if strategy.position_size > 0
strategy.exit(id="Exit 1", from_entry="Entry 1", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 2", from_entry="Entry 2", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 3", from_entry="Entry 3", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 4", from_entry="Entry 4", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 5", from_entry="Entry 5", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 6", from_entry="Entry 6", profit=Profit_Ticks, loss=Loss_Ticks)
strategy.exit(id="Exit 7", from_entry="Entry 7", profit=Profit_Ticks, loss=Loss_Ticks)
|
Relative Returns Strategy | https://www.tradingview.com/script/QmcsP9Z0-Relative-Returns-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 168 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Relative Returns Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
index_ticker=input("XJO")
Loopback = input(40, step=20)
useStopAndIndexReturns = input(true)
useStopAndIndexReturnsMa = input(true)
useDifference = not useStopAndIndexReturns
MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
MALength = input(10, minval=10,step=10)
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
f_secureSecurity(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on)
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
index = f_secureSecurity(index_ticker, '1D', close, 0)
stock_return = (close - close[Loopback])*100/close
index_return = (index - index[Loopback])*100/index
stock_return_ma = f_getMovingAverage(stock_return, MAType, MALength)
index_return_ma = f_getMovingAverage(index_return, MAType, MALength)
relativeReturns = stock_return - index_return
relativeReturns_ma = f_getMovingAverage(relativeReturns, MAType, MALength)
plot(useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma : stock_return : na, title="StockReturn", color=color.green, linewidth=1)
plot(useStopAndIndexReturns ? useStopAndIndexReturnsMa ? index_return_ma : index_return : na, title="IndexReturn", color=color.red, linewidth=1)
plot(useDifference?relativeReturns:na, title="Relative-Returns", color=color.blue, linewidth=1)
plot(useDifference?relativeReturns_ma:na, title="MA", color=color.red, linewidth=1)
buyCondition = (useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma > index_return_ma : stock_return > index_return : relativeReturns > relativeReturns_ma)
closeBuyCondition = (useStopAndIndexReturns ? useStopAndIndexReturnsMa ? stock_return_ma < index_return_ma : stock_return < index_return : relativeReturns < relativeReturns_ma)
strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca", oca_type=strategy.oca.cancel)
strategy.close("Buy", when=closeBuyCondition) |
Stop loss and Take Profit in $$ example | https://www.tradingview.com/script/IHVPG6TS-Stop-loss-and-Take-Profit-in-example/ | adolgov | https://www.tradingview.com/u/adolgov/ | 2,741 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov
// @description
//
//@version=4
strategy("Stop loss and Take Profit in $$ example", overlay=true)
// random entry condition
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
moneyToSLPoints(money) =>
strategy.position_size !=0 ? (money / syminfo.pointvalue / abs(strategy.position_size)) / syminfo.mintick : na
p = moneyToSLPoints(input(200, title = "Take Profit $$"))
l = moneyToSLPoints(input(100, title = "Stop Loss $$"))
strategy.exit("x", profit = p, loss = l)
// debug plots for visualize SL & TP levels
pointsToPrice(pp) =>
na(pp) ? na : strategy.position_avg_price + pp * sign(strategy.position_size) * syminfo.mintick
pp = plot(pointsToPrice(p), style = plot.style_linebr )
lp = plot(pointsToPrice(-l), style = plot.style_linebr )
avg = plot( strategy.position_avg_price, style = plot.style_linebr )
fill(pp, avg, color = color.green)
fill(avg, lp, color = color.red) |
Daily Open Strategy (DOS) | https://www.tradingview.com/script/0yqWAi1B-Daily-Open-Strategy-DOS/ | xtradernet | https://www.tradingview.com/u/xtradernet/ | 58 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=4
strategy("Daily Open Strategy", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 10000)
PrevRange = input(0.0100, type=input.float, title="Previous Candle Range")
TP = input(200, title="Take Profit in pips")
SL = input(1000, title="Stop Loss in pips")
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2015, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer,
defval=31, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=12, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2020, minval=1800, maxval=2100)
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
longTrigger = (open-close) > PrevRange and close<open
shortTrigger = (close-open) > PrevRange and close>open
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
strategy.entry(id = "Long", long = true, when = (longTrigger and not isShort and inDateRange))
strategy.exit("Exit Long", "Long", loss=SL, profit=TP)
strategy.entry(id = "Short", long = false, when = (shortTrigger and not isLong and inDateRange))
strategy.exit("Exit Short", "Short", loss=SL, profit=TP)
|
Pyramiding Entries On Early Trends (by Coinrule) | https://www.tradingview.com/script/7NNJ0sXB-Pyramiding-Entries-On-Early-Trends-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 358 | strategy | 3 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=3
strategy(shorttitle='Pyramiding Entry On Early Trends',title='Pyramiding Entry On Early Trends (by Coinrule)', overlay=false, pyramiding= 7, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 20, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month")
fromDay = input(defval = 10, title = "From Day")
fromYear = input(defval = 2020, title = "From Year")
thruMonth = input(defval = 1, title = "Thru Month")
thruDay = input(defval = 1, title = "Thru Day")
thruYear = input(defval = 2112, title = "Thru Year")
showDate = input(defval = true, title = "Show Date Range")
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
//MA inputs and calculations
inSignal=input(9, title='MAfast')
inlong1=input(100, title='MAslow')
inlong2=input(200, title='MAlong')
MAfast= sma(close, inSignal)
MAslow= sma(close, inlong1)
MAlong= sma(close, inlong2)
Bullish = crossover(close, MAfast)
longsignal = (Bullish and MAfast > MAslow and MAslow < MAlong and window())
//set take profit
ProfitTarget_Percent = input(3)
Profit_Ticks = (close * (ProfitTarget_Percent / 100)) / syminfo.mintick
//set take profit
LossTarget_Percent = input(3)
Loss_Ticks = (close * (LossTarget_Percent / 100)) / syminfo.mintick
//Order Placing
strategy.entry("Entry 1", strategy.long, when = (strategy.opentrades == 0) and longsignal)
strategy.entry("Entry 2", strategy.long, when = (strategy.opentrades == 1) and longsignal)
strategy.entry("Entry 3", strategy.long, when = (strategy.opentrades == 2) and longsignal)
strategy.entry("Entry 4", strategy.long, when = (strategy.opentrades == 3) and longsignal)
strategy.entry("Entry 5", strategy.long, when = (strategy.opentrades == 4) and longsignal)
strategy.entry("Entry 6", strategy.long, when = (strategy.opentrades == 5) and longsignal)
strategy.entry("Entry 7", strategy.long, when = (strategy.opentrades == 6) and longsignal)
if (strategy.position_size > 0)
strategy.exit(id="Exit 1", from_entry = "Entry 1", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 2", from_entry = "Entry 2", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 3", from_entry = "Entry 3", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 4", from_entry = "Entry 4", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 5", from_entry = "Entry 5", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 6", from_entry = "Entry 6", profit = Profit_Ticks, loss = Loss_Ticks)
strategy.exit(id="Exit 7", from_entry = "Entry 7", profit = Profit_Ticks, loss = Loss_Ticks)
|
Escaping of Rate from Avarage By Mustafa OZVER Strategy | https://www.tradingview.com/script/r96Oekwq/ | Mustafaozver | https://www.tradingview.com/u/Mustafaozver/ | 78 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mustafaozver
//@version=4
strategy("Escaping of Rate from Avarage By Mustafa OZVER", "EoRfA", overlay=false)
//strategy("Escaping of Rate from Avarage By Mustafa OZVER", "EoRfA", overlay=false)
src = input(ohlc4,"Source")
FPrice = wma(src,3)
len = input(17,"Length")
stdev = stdev(FPrice,len)
ema2 = ema(FPrice,len)
Rate1 = (FPrice - ema2) / stdev
//bgcolor(color=((stdev/ema)>0.0015)?color.green:#00000000,transp=80)
colorG = color.lime
colorR = color.red
hline(0,linestyle=hline.style_solid,editable=false)
hline1=hline(1,linestyle=hline.style_dotted,editable=false)
hlinen1=hline(-1,linestyle=hline.style_dotted,editable=false)
fill(hline1,hlinen1,color=color.silver,transp=85,editable=true)
//plot(Rate,color=(Rate>0?colorG:colorR),transp=75,style=plot.style_area,editable=false)
plot(Rate1,title="ESC1",color=(Rate1>0?colorG:colorR),style=plot.style_line,linewidth=1,editable=true)
BUYSIGNAL = Rate1 < -1 and change(Rate1) > 0
SELLSIGNAL = Rate1 > 1 and change(Rate1) < 0
if (BUYSIGNAL)
strategy.order("LONG1",true)
//strategy.close("SHORT1")
if (SELLSIGNAL)
// strategy.order("SHORT1",false)
strategy.close("LONG1") |
RSI of Ultimate Oscillator [SHORT Selling] Strategy | https://www.tradingview.com/script/bHXZkpzl-RSI-of-Ultimate-Oscillator-SHORT-Selling-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 336 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="RSI of Ultimate Oscillator [SHORT Selling] Strategy", shorttitle="RSIofUO" , overlay=false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
//Ultimate Oscillator logic copied from TradingView builtin indicator
/////////////////////////////////////////////////////////////////////////////////
length1 = input(5, minval=1), length2 = input(10, minval=1), length3 = input(15, minval=1)
rsiUOLength = input(5, title="RSI UO length", minval=1)
sellLine = input (60, title="Sell at RSIofUO")
coverLine = input (75, title="Cover at RSIofUO")
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(3,title="Stop Loss",minval=1)
showUO=input(false, "show Ultimate Oscialltor")
average(bp, tr_, length) => sum(bp, length) / sum(tr_, length)
high_ = max(high, close[1])
low_ = min(low, close[1])
bp = close - low_
tr_ = high_ - low_
avg7 = average(bp, tr_, length1)
avg14 = average(bp, tr_, length2)
avg28 = average(bp, tr_, length3)
out = 100 * (4*avg7 + 2*avg14 + avg28)/7
//Ultimate Oscillator
/////////////////////////////////////////////////////////////////////////////////
//Willimas Alligator copied from TradingView built in Indicator
/////////////////////////////////////////////////////////////////////////////////
smma(src, length) =>
smma = 0.0
smma := na(smma[1]) ? sma(src, length) : (smma[1] * (length - 1) + src) / length
smma
//moving averages logic copied from Willimas Alligator -- builtin indicator in TradingView
sma1=smma(hl2,10)
sma2=smma(hl2,20)
sma3=smma(hl2,50)
//Willimas Alligator
/////////////////////////////////////////////////////////////////////////////////
//drawings
/////////////////////////////////////////////////////////////////////////////////
hline(sellLine, title="Middle Line 60 [Short Here]", color=color.red , linestyle=hline.style_solid)
obLevelPlot = hline(75, title="Overbought", color=color.blue , linestyle=hline.style_dashed)
osLevelPlot = hline(25, title="Oversold", color=color.blue, linestyle=hline.style_dashed)
fill(obLevelPlot, osLevelPlot, title="Background", color=color.blue, transp=90)
rsiUO = rsi(out,rsiUOLength)
ultPlot=plot(showUO==true? out : na, color=color.green, title="Oscillator")
plot(rsiUO, title = "rsiUO" , color=color.purple)
//drawings
/////////////////////////////////////////////////////////////////////////////////
//Strategy Logic
/////////////////////////////////////////////////////////////////////////////////
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
strategy.entry(id="SERSIofUO", long=false, qty=qty1, when = sma1<=sma2 and sma2 < sma3 and close<sma2 and crossunder(rsiUO,sellLine) )
//strategy.entry(id="SERSiofUO", long=false, when = sma1< sma2 and crossunder(rsiUO,60) )
barcolor(abs(strategy.position_size)>=1 ? color.purple : na )
bgcolor(abs(strategy.position_size)>=1 ? color.purple : na , transp=70)
//partial exit
strategy.close(id="SERSIofUO", comment="PExit", qty=strategy.position_size/3, when=abs(strategy.position_size)>=1 and close< strategy.position_avg_price and crossover(rsiUO,30) )
strategy.close(id="SERSIofUO", comment="CloseAll", when=abs(strategy.position_size)>=1 and crossover(rsiUO,coverLine) )
//Strategy Logic
/////////////////////////////////////////////////////////////////////////////////
|
Multi MA MTF SandBox Strategy | https://www.tradingview.com/script/rilO9l18-Multi-MA-MTF-SandBox-Strategy/ | dman103 | https://www.tradingview.com/u/dman103/ | 417 | strategy | 5 | CC-BY-SA-4.0 | // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/
// © dman103
// A moving averages SandBox strategy where you can experiment with two moving averages (like KAMA, ALMA, HMA, JMA, VAMA, and more) on different time frames to generate BUY and SELL signals, when they cross.
// Great sandbox for experimenting with different moving averages and different time frames.
//
// == How to use ==
// We select two types of moving averages on two different time frames:
//
// First is the FAST moving average which should be at the same time frame or higher.
// Second is the SLOW moving average that should be on the same time frame or higher.
// When FAST moving average cross over the SLOW moving average we have a BUY signal (for LONG)
// When FAST moving average cross under the SLOW moving average we have a SELL signal (for SHORT)
// WARNING: Using a lower time frame than your chart time frame will result in unrealistic results in your backtesting and bar replay.
// == NOTES ==
// You can select BOTH, LONG and SHORT in the strategy settings.
// You can also enable Stop Loss and Take Profit.
// More sandboxes to come, Follow to get notified.
// Can also act as an indicator by settings 'Act as indicator' to true.
//@version=5
strategy('Multi MA MTF SandBox Strategy', 'Multi MA SandBox', overlay=true, default_qty_type=strategy.cash, default_qty_value=3500, initial_capital=10000)
tradeType = input.string('LONG', title='What trades should be taken:', options=['LONG', 'SHORT', 'BOTH'])
act_like_indicator = input.bool(false,'Act as indicator (will disable strategy functionality)')
start_date = input.time(title='Start Date', defval=timestamp('1 JAN 2020 09:30:00 +0000'))
end_date = input.time(title='End Date', defval=timestamp('1 JAN 2030 09:30:00 +0000'))
window() =>
time_close >= start_date and time_close <= end_date ? true : false
ma_select1 = input.string(title='First Slow moving average', defval='EMA', options=['SMA', 'EMA', 'WMA', 'HMA', 'JMA', 'KAMA', 'TMA', 'VAMA', 'SMMA', 'DEMA', 'VMA', 'WWMA', 'EMA_NO_LAG', 'TSF', 'ALMA'],group="Moving Average 1 (Blue)")
resma_fast = input.timeframe(title='First Time Frame', defval='',group="Moving Average 1 (Blue)")
lenma_fast = input(title='First MA Length', defval=6,group="Moving Average 1 (Blue)")
ma_select2 = input.string(title='Second Fast moving average', defval='JMA', options=['SMA', 'EMA', 'WMA', 'HMA', 'JMA', 'KAMA', 'TMA', 'VAMA', 'SMMA', 'DEMA', 'VMA', 'WWMA', 'EMA_NO_LAG', 'TSF', 'ALMA'],group="Moving Average 2 (Yellow)")
resma_slow = input.timeframe(title='Second time frame', defval='',group="Moving Average 2 (Yellow)")
lenma_slow = input(title='Second MA length', defval=14,group="Moving Average 2 (Yellow)")
lineWidth = input(2, title='Line Width', group="Visual Settings")
color_fast = input(title='Fast Line Color (or Buy)', defval=color.new(#26c6da, 40), group="Visual Settings")
color_slow = input(title='Slow Line Color (or Sell)', defval=color.new(color.yellow, 40), group="Visual Settings")
change_line_color = input.bool(true, title='Change line color based on signal', tooltip='Change line color based on Buy or Sell Signal. Effected by Fast/Slow Line Color settings above.', group="Visual Settings")
fillColor = input(title='Fill Color', defval=true, group="Visual Settings")
offset = input.float(title='Alma Offset (only for ALMA)', defval=0.85, step=0.05, group="Moving Average Parameters")
volatility_lookback = input(title='Volatility lookback (only for VAMA)', defval=12, group="Moving Average Parameters")
i_fastAlpha = input.float(1.25, 'KAMA\'s alpha (only for KAMA)', minval=1, step=0.25, group="Moving Average Parameters")
fastAlpha = 2.0 / (i_fastAlpha + 1)
slowAlpha = 2.0 / 31
///////Moving Averages
MA_selector(src, length, ma_select) =>
ma = 0.0
if ma_select == 'SMA'
ma := ta.sma(src, length)
ma
if ma_select == 'EMA'
ma := ta.ema(src, length)
ma
if ma_select == 'WMA'
ma := ta.wma(src, length)
ma
if ma_select == 'HMA'
ma := ta.hma(src, length)
ma
if ma_select == 'JMA'
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = beta
tmp0 = 0.0
tmp1 = 0.0
tmp2 = 0.0
tmp3 = 0.0
tmp4 = 0.0
tmp0 := (1 - alpha) * src + alpha * nz(tmp0[1])
tmp1 := (src - tmp0[0]) * (1 - beta) + beta * nz(tmp1[1])
tmp2 := tmp0[0] + tmp1[0]
tmp3 := (tmp2[0] - nz(tmp4[1])) * (1 - alpha) * (1 - alpha) + alpha * alpha * nz(tmp3[1])
tmp4 := nz(tmp4[1]) + tmp3[0]
ma := tmp4
ma
if ma_select == 'KAMA'
momentum = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
efficiencyRatio = volatility != 0 ? momentum / volatility : 0
smoothingConstant = math.pow(efficiencyRatio * (fastAlpha - slowAlpha) + slowAlpha, 2)
var kama = 0.0
kama := nz(kama[1], src) + smoothingConstant * (src - nz(kama[1], src))
ma := kama
ma
if ma_select == 'TMA'
ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
ma
if ma_select == 'VMA'
valpha = 2 / (length + 1)
vud1 = src > src[1] ? src - src[1] : 0
vdd1 = src < src[1] ? src[1] - src : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz((vUD - vDD) / (vUD + vDD))
VAR = 0.0
VAR := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(VAR[1])
ma := VAR
ma
if ma_select == 'WWMA'
wwalpha = 1 / length
WWMA = 0.0
WWMA := wwalpha * src + (1 - wwalpha) * nz(WWMA[1])
ma := WWMA
ma
if ma_select == 'EMA_NO_LAG'
EMA1 = ta.ema(src, length)
EMA2 = ta.ema(EMA1, length)
Difference = EMA1 - EMA2
ma := EMA1 + Difference
ma
if ma_select == 'TSF'
lrc = ta.linreg(src, length, 0)
lrc1 = ta.linreg(src, length, 1)
lrs = lrc - lrc1
TSF = ta.linreg(src, length, 0) + lrs
ma := TSF
ma
if ma_select == 'VAMA' // Volatility Adjusted from @fractured
mid = ta.ema(src, length)
dev = src - mid
vol_up = ta.highest(dev, volatility_lookback)
vol_down = ta.lowest(dev, volatility_lookback)
ma := mid + math.avg(vol_up, vol_down)
ma
if ma_select == 'SMMA'
smma = float(0.0)
smaval = ta.sma(src, length)
smma := na(smma[1]) ? smaval : (smma[1] * (length - 1) + src) / length
ma := smma
ma
if ma_select == 'DEMA'
e1 = ta.ema(src, length)
e2 = ta.ema(e1, length)
ma := 2 * e1 - e2
ma
if ma_select == 'ALMA'
ma := ta.alma(src, length, offset, 6)
ma
ma
// Calculate EMA
ma_fast = MA_selector(close, lenma_fast, ma_select1)
ma_slow = MA_selector(close, lenma_slow, ma_select2)
maFastStep = request.security(syminfo.tickerid, resma_fast, ma_fast)
maSlowStep = request.security(syminfo.tickerid, resma_slow, ma_slow)
colors = ma_fast > ma_slow ? color.new(color.green, 70) : color.new(color.red, 70)
colors_setting = ma_fast > ma_slow ? color_fast : color_slow
ma1_plot = plot(maFastStep, color=change_line_color == false ? color_fast : colors_setting, linewidth=lineWidth)
ma2_plot = plot(maSlowStep, color=change_line_color == false ? color_slow : colors_setting, linewidth=lineWidth)
fill(ma1_plot, ma2_plot, color=fillColor ? colors : na)
closeStatus = strategy.openprofit > 0 ? 'win' : 'lose'
////////Long Rules
long = ta.crossover(maFastStep, maSlowStep) and (tradeType == 'LONG' or tradeType == 'BOTH')
longClose = ta.crossunder(maFastStep, maSlowStep) //and falling(maSlowStep,1)
///////Short Rules
short = ta.crossunder(maFastStep, maSlowStep) and (tradeType == 'SHORT' or tradeType == 'BOTH')
shortClose = ta.crossover(maFastStep, maSlowStep)
longShape = ta.crossover(maFastStep, maSlowStep) and act_like_indicator
shortShape = ta.crossunder(maFastStep, maSlowStep) and act_like_indicator
plotshape(longShape, style=shape.triangleup, location=location.belowbar, color=color.new(color.lime, 0), size=size.small)
plotshape(shortShape, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.small)
// === Stop LOSS ===
useStopLoss = input(false, title='Use Stop Loss',group="Stop Loss")
sl_inp = input.float(2.5, title='Stop Loss %', step=0.1, group="Stop Loss") // / 100
useTakeprofit = input(false, title='Use Take Profit',group="Take Profit")
tp_inp = input.float(5, title='Take Profit %', step=0.1,group="Take Profit") // / 100
percentToTicks(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
float stop_level = percentToTicks(sl_inp)
float take_level = percentToTicks(tp_inp)
if long and window() and act_like_indicator==false
strategy.entry('long', strategy.long)
if short and window() and act_like_indicator==false
strategy.entry('short', strategy.short)
if (longClose)
strategy.close('long', comment=closeStatus)
if (shortClose)
strategy.close('short', comment=closeStatus)
if useStopLoss or useTakeprofit
if (useTakeprofit and useStopLoss==false)
strategy.exit('Take Profit', profit=take_level, comment='tp '+closeStatus)
if (useTakeprofit==false and useStopLoss)
strategy.exit('Stop loss', loss=stop_level, comment='sl')
if (useTakeprofit and useStopLoss)
strategy.exit('Take Profit/Stop Loss', profit=take_level,loss=stop_level, comment_profit ='tp '+closeStatus,comment_loss='sl')
|
MACD Strategy with trailing ATR stop | https://www.tradingview.com/script/2jDHQAJc-MACD-Strategy-with-trailing-ATR-stop/ | Wunderbit | https://www.tradingview.com/u/Wunderbit/ | 1,792 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Deobald
//@version=5
strategy('MACD Strategy', overlay=true, pyramiding=2, commission_type=strategy.commission.percent, commission_value=0.04, initial_capital=100, default_qty_type=strategy.cash, default_qty_value=100, currency=currency.USD)
// FUNCTIONS
Ema(src, p) =>
ema = 0.
sf = 2 / (p + 1)
ema := nz(ema[1] + sf * (src - ema[1]), src)
ema
Sma(src, p) =>
a = ta.cum(src)
(a - a[math.max(p, 0)]) / math.max(p, 0)
Atr(p) =>
atr = 0.
Tr = math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
atr := nz(atr[1] + (Tr - atr[1]) / p, Tr)
atr
/// TREND
ribbon_period = input.int(34, 'Period', step=1)
leadLine1 = ta.ema(close, ribbon_period)
leadLine2 = ta.sma(close, ribbon_period)
p3 = plot(leadLine1, color=color.new(#53b987, 50), title='EMA', linewidth=1)
p4 = plot(leadLine2, color=color.new(#eb4d5c, 50), title='SMA', linewidth=1)
fill(p3, p4, color=leadLine1 > leadLine2 ? #53b987 : #eb4d5c, transp=60)
// MACD
fast_length = input(title='Fast Length', defval=3)
slow_length = input(title='Slow Length', defval=5)
src = input(title='Source', defval=close)
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=50, defval=2)
sma_source = input(title='Simple MA(Oscillator)', defval=false)
sma_signal = input(title='Simple MA(Signal Line)', defval=true)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? Sma(src, fast_length) : Ema(src, fast_length)
slow_ma = sma_source ? Sma(src, slow_length) : Ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? Sma(macd, signal_length) : Ema(macd, signal_length)
hist = macd - signal
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )
// plot(macd, title="MACD", color=col_macd, transp=0)
// plot(signal, title="Signal", color=col_signal, transp=0)
// TAKE PROFIT AND STOP LOSS
long_tp1_inp = input.float(1, title='Long Take Profit 1 %', step=0.1) / 100
long_tp1_qty = input.int(10, title='Long Take Profit 1 Qty', step=1)
long_tp2_inp = input.float(5, title='Long Take Profit 2%', step=0.1) / 100
long_tp2_qty = input.int(50, title='Long Take Profit 2 Qty', step=1)
long_take_level_1 = strategy.position_avg_price * (1 + long_tp1_inp)
long_take_level_2 = strategy.position_avg_price * (1 + long_tp2_inp)
// Stop Loss
multiplier = input.float(2.2, 'SL Mutiplier', minval=1, step=0.1)
ATR_period = input.int(17, 'ATR period', minval=1, step=1)
// Strategy
entry_long = ta.crossover(macd, signal) and leadLine2 < leadLine1
entry_price_long = ta.valuewhen(entry_long, close, 0)
SL_floating_long = entry_price_long - multiplier * Atr(ATR_period)
exit_long = close < SL_floating_long
///// BACKTEST PERIOD ///////
testStartYear = input(2018, 'Backtest Start Year')
testStartMonth = input(1, 'Backtest Start Month')
testStartDay = input(1, 'Backtest Start Day')
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)
testStopYear = input(9999, 'Backtest Stop Year')
testStopMonth = input(12, 'Backtest Stop Month')
testStopDay = input(31, 'Backtest Stop Day')
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
if testPeriod()
strategy.entry('long', strategy.long, comment='Long', when=entry_long)
strategy.exit('TP1', 'long', qty_percent=long_tp1_qty, limit=long_take_level_1) //, trail_points=entry_price_long * long_trailing / syminfo.mintick, trail_offset=entry_price_long * long_trailing / syminfo.mintick)
strategy.exit('TP2', qty_percent=long_tp2_qty, limit=long_take_level_2) //, trail_points=entry_price_long * long_trailing / syminfo.mintick, trail_offset=entry_price_long * long_trailing / syminfo.mintick)
strategy.close('long', when=exit_long, comment='exit long')
// LONG POSITION
plot(strategy.position_size > 0 ? long_take_level_1 : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='1st Long Take Profit')
plot(strategy.position_size > 0 ? long_take_level_2 : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='2nd Long Take Profit')
plot(strategy.position_size > 0 ? SL_floating_long : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Long Stop Loss')
|
Optimized RSI Strategy - Buy The Dips (by Coinrule) | https://www.tradingview.com/script/Pm1WAtyI-Optimized-RSI-Strategy-Buy-The-Dips-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 696 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=4
strategy(shorttitle='Optimized RSI Strategy',title='Optimized RSI Strategy - Buy The Dips (by Coinrule)', overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
// RSI inputs and calculations
lengthRSI = (14)
RSI = rsi(close, lengthRSI)
RSI_entry = input(35, title = 'RSI Entry', minval=1)
RSI_exit = input(65, title = 'RSI Close', minval=1)
//Calculate Moving Averages
movingaverage_signal = sma(close, input(100))
//Entry
strategy.entry(id="long", long = true, when = RSI< RSI_entry and close < movingaverage_signal and window())
//Exit
//RSI
strategy.close("long", when = RSI > RSI_exit and window())
plot (movingaverage_signal)
|
MA Strength Strategy | https://www.tradingview.com/script/7KDTSTD3-MA-Strength-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 81 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("MA Strength Strategy", overlay=false, initial_capital = 20000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
MAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
LookbackPeriod = input(10, step=10)
IndexMAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
IndexMAPeriod = input(200, step=10)
considerTrendDirection = input(true)
considerTrendDirectionForExit = input(true)
offset = input(1, step=1)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0.0
upwardScore := close > ma5? upwardScore+1.10:upwardScore
upwardScore := ma5 > ma10? upwardScore+1.10:upwardScore
upwardScore := ma10 > ma20? upwardScore+1.10:upwardScore
upwardScore := ma20 > ma30? upwardScore+1.10:upwardScore
upwardScore := ma30 > ma50? upwardScore+1.15:upwardScore
upwardScore := ma50 > ma100? upwardScore+1.20:upwardScore
upwardScore := ma100 > ma200? upwardScore+1.25:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
trendStrength = upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 6? 0.5: upwardScore < 2?-0.5:upwardScore>4?0.25:-0.25) : 0
[trendStrength, upwardScore]
includePartiallyAligned = true
[trendStrength, upwardScore] = f_getMaAlignment(MAType, includePartiallyAligned)
upwardSum = sum(upwardScore, LookbackPeriod)
indexSma = f_getMovingAverage(upwardSum,IndexMAType,IndexMAPeriod)
plot(upwardSum, title="Moving Average Strength", color=color.green, linewidth=2, style=plot.style_linebr)
plot(indexSma, title="Strength MA", color=color.red, linewidth=1, style=plot.style_linebr)
buyCondition = crossover(upwardSum,indexSma) and (upwardSum > upwardSum[offset] or not considerTrendDirection)
sellCondition = crossunder(upwardSum,indexSma) and (upwardSum < upwardSum[offset] or not considerTrendDirection)
exitBuyCondition = crossunder(upwardSum,indexSma)
exitSellCondition = crossover(upwardSum,indexSma)
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when= inDateRange and buyCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.close("Buy", when = considerTrendDirectionForExit? sellCondition : exitBuyCondition)
strategy.entry("Sell", strategy.short, when= inDateRange and sellCondition, oca_name="oca_sell", oca_type=strategy.oca.cancel)
strategy.close( "Sell", when = considerTrendDirectionForExit? buyCondition : exitSellCondition)
|
RSI of VWAP [SHORT selling] | https://www.tradingview.com/script/ZjjlKjxs-RSI-of-VWAP-SHORT-selling/ | mohanee | https://www.tradingview.com/u/mohanee/ | 390 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="RSI of VWAP [SHORT selling]", overlay=false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
rsiLength=input(11,title="RSI Length", minval=1, maxval=50)
osLevel=input(25,title="RSI Oversold (SHORT sell Line)", minval=1, maxval=100)
obLevel=input(70,title="RSI Overbought (SHORT Exit/cover Line)", minval=1, maxval=100)
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(5,title="Stop Loss",minval=1)
partialExit=input(true,title="Allow Partial exit / take profits")
showWeeklyVwapRSI=input(true,title="Show Weekly VWAP RSI")
checkVIXRSI=input(true,title="Check VIX RSI , ===when this setting is selected , strategy doenst look for whether price is under ema200 or not ! It only checks RSI reading of VIX=== ")
myVwap=vwap
vwapRsi=rsi(vwap,rsiLength)
ema200=ema(close,200)
//signalLine=ema(vwapRsi,9)
vwapWeeklyRSI=rsi(security(syminfo.tickerid, "W", vwap), rsiLength)
signalLine=ema(vwapRsi,50)
vixVal = security("CBOE:VIX",timeframe.period,hlc3)
vixRsi=rsi(vixVal,14)
plot(vwapRsi, title="RSI of VWAP", linewidth=2, color=color.purple)
plot( checkVIXRSI == true ? vwapWeeklyRSI : na, title="RSI of VWAP weekly", linewidth=2, color=color.blue)
//plot(signalLine, title="signal line", linewidth=2, color=color.red)
plot(checkVIXRSI == true ? vixRsi : na, title="VIX RSI", linewidth=2, color=color.red)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevelPlot = hline(obLevel, title="Overbought", linestyle=hline.style_dotted)
osLevelPlot = hline(osLevel, title="Oversold", linestyle=hline.style_dotted)
fill(obLevelPlot, osLevelPlot, title="Background", color=#9915FF, transp=90)
//plot(ema200, title="EMA 200", color=color.orange, transp=25)
//plot(myVwap, title="VWAP", color=color.purple, transp=25)
//plot(close)
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//more than 80%
strategy.entry(id="SE", comment="Short Entry", long=false, qty=qty1, when= myVwap < ema200 and checkVIXRSI==false and ( crossunder(vwapRsi,osLevel) or crossunder(vwapWeeklyRSI,obLevel) ) ) //original when publshed
strategy.entry(id="SE", comment="Short Entry", long=false, qty=qty1, when= checkVIXRSI==true and crossover(vixRsi,60) and ( crossunder(vwapRsi,osLevel) or crossunder(vwapWeeklyRSI,obLevel) )) //check VIX RSI reading
//19.25 Net Profit 77.08 2.59 factor drawdon 3.7 only
//11 , 25 setting 40.75% net profit 56 trades and 87.5% winrate 6.2 profit factor drawdown 3.17 and 47 bars
//strategy.entry(id="SE", comment="Short Entry", long=false, qty=qty1, when= checkVix==false and ( crossover(vixRsi,60) or crossover(vixRsi,70) ) and ( crossunder(vwapRsi,osLevel) or crossunder(vwapWeeklyRSI,obLevel) ))
// 78.13 2.6 factor drawdon 5.81y
// 11 , 25 setting 30.5 net profit 65 trades and 80% winrate 2.77 profit factor drawdown 4.79 46 bars
//strategy.entry(id="SE", comment="Short Entry", long=false, qty=qty1, when= checkVIXRSI==true and vixRsi>60 and ( crossunder(vwapRsi,osLevel) or crossunder(vwapWeeklyRSI,obLevel) )) // 77.08 2.59 factor drawdon 3.7 only
//strategy.entry(id="SE", comment="Short Entry", long=false, qty=qty1, when= vixRsi > 70 and vwapRsi < vixRsi and vwapRsi<30)
//stoploss
stopLossVal= abs(strategy.position_size)>=1 ? (strategy.position_avg_price * (1+(stopLoss*0.01) )) : (strategy.position_avg_price * 2)
//draw initil stop loss
//plot(abs(strategy.position_size)>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
bgcolor(abs(strategy.position_size)>=1?color.blue:na, transp=80)
barcolor(abs(strategy.position_size)>=1?color.blue: na)
//possible re entries
bgcolor(crossunder(vwapRsi,osLevel) and myVwap < ema200 ? color.yellow:na, transp=50)
barcolor(crossunder(vwapRsi,osLevel) and myVwap < ema200 ? color.yellow:na )
if(partialExit==true)
strategy.close(id="SE",comment="Exit Partial (points="+tostring(close - strategy.position_avg_price, "####.##")+")",qty=strategy.position_size/3, when=close < strategy.position_avg_price and crossover(vwapRsi,osLevel) ) //and close>ema200
strategy.close_all(comment="Exit All (points="+tostring( strategy.position_avg_price - close , "####.##")+")", when=crossover(vwapRsi,obLevel) ) //and close>ema200
//close all on stop loss
strategy.close_all(comment="SL Exit (points="+tostring(strategy.position_avg_price - close, "####.##")+")", when=close > stopLossVal ) //and close>ema200
|
MACD 50x Leveraged Long Strategy Results with Real Equity | https://www.tradingview.com/script/WwUaqcLg-MACD-50x-Leveraged-Long-Strategy-Results-with-Real-Equity/ | Noldo | https://www.tradingview.com/u/Noldo/ | 181 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Noldo
//@version=4
strategy(title="MACD LONG STRATEGY REAL EQUITY WITH 50X LEVERAGE",shorttitle = "MACD LONG 50X REAL EQUITY", overlay=true,
initial_capital=100,
linktoseries = false,
default_qty_type=strategy.cash,
default_qty_value=1,
commission_type=strategy.commission.percent,
commission_value=0.0,
calc_on_order_fills = false,
calc_on_every_tick = true,
max_bars_back = 5000,
pyramiding = 0,
precision = 3)
// Variables
src = close
fromyear = input(2016, defval = 2009, minval = 2000, maxval = 2100, title = "From Year")
toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
frommonth = input(04, defval = 04, minval = 01, maxval = 12, title = "From Month")
tomonth = input(12, defval = 12, minval = 01, maxval = 12, title = "To Month")
fromday = input(01, defval = 01, minval = 01, maxval = 31, title = "From day")
today = input(31, defval = 31, minval = 01, maxval = 31, title = "To day")
term = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59))
// STRATEGY COMPONENTS
// SL values
// STOP VALUE ==>
//The 50x leverage explodes at just 2% below the current entry price and the current position size melts.
//2% below the entry price is determined as the liquidation point so that the transaction is guaranteed.
stop_value = valuewhen(strategy.position_size != 0 and strategy.position_size[1] == 0,strategy.position_avg_price * 0.98 , 0)
//
// LEVERAGE ==> 50X
leverage = 50
// POSITION SIZE ==> %1 (0.01)
possize = 1
// MACD
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ema(close, fastLength) - ema(close, slowlength)
aMACD = ema(MACD, MACDLength)
delta = MACD - aMACD
// STRATEGY
if (crossover(delta, 0) and term)
strategy.entry("MacdLE",true, comment="LONG" , qty = possize)
if (crossunder(delta, 0))
strategy.close("MacdLE", true, comment="CLOSE")
if(low <= stop_value and delta > 0 and term )
strategy.close("MacdLE",true)
if time > timestamp(toyear, tomonth, today, 23, 59)
strategy.close_all()
// REAL LEVERAGE SIMULATION ---
_longmovement = strategy.position_size != 0 and strategy.position_size[1] == 0
_exitmovement = strategy.position_size[1] != 0 and strategy.position_size == 0
// MODE : Indicating a situation for winners and losers, just like in the martingale system, to know if the strategy is losing or gaining.
float mode = na
mode := change(strategy.wintrades) > 0 ? 1 : change(strategy.losstrades) > 0 ? -1 : nz(mode[1], 1)
float capital = 0.00
chg = change(strategy.position_size)
_b = valuewhen(_longmovement,strategy.position_avg_price,0)
_s = valuewhen(_exitmovement,open,0)
pips = ((_s - _b) / _b) * 100
//If we are in profit, how much will this affect all of our capital with leverage?
//If we are already at a loss, all of our position size will be gone.
// Now let's put this into expression :
capital := _longmovement ? nz(capital[1], 0) - chg : _exitmovement and mode == 1 ? (capital[1] - chg) + ((-chg * leverage * pips)/100) :
_exitmovement and mode != 1 ? capital[1] : capital[1]
// NET CAPITAL
capita = 100 + capital
float netcapital = na
netcapital := netcapital[1] <= 0 ? 0 : capita
// Now, if we are ready, it's time to see the facts:
//If we had made a strategy using 1% position size and 50x leverage, that is, our entry point would be less than 2% liquidation point, the change in our capital would be in the form of a blue-colored area.
//The result will not surprise:
//We have 0!
// The first moment we switch to - is the moment we run out of cash and the game is over.
// NOTE: It is recommended to use as chart bottom indicator.
plot(netcapital , color = color.blue , linewidth = 2)
|
BBofVWAP with entry at Pivot Point | https://www.tradingview.com/script/rpyX1mx4-BBofVWAP-with-entry-at-Pivot-Point/ | ediks123 | https://www.tradingview.com/u/ediks123/ | 478 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ediks123
//@version=4
strategy("BBofVWAP with entry at Pivot Point", overlay=false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
ch = 0
if(res == 'Y')
t = year(time('D'))
ch := change(t) != 0 ? 1 : 0
else
t = time(res)
ch := change(t) != 0 ? 1 : 0
ch
//variables BEGIN
//smaLength=input(200,title="Slow MA Length")
bbLength=input(50,title="BB Length")
//bbsrc = input(close, title="BB Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
pp_period = input(title = "Pivot Period", type=input.string, defval="Week", options = ['Day', 'Week'])
pp_res = pp_period == 'Day' ? 'D' : pp_period == 'Week' ? 'W' : pp_period == 'Month' ? 'M' : 'Y'
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(5,title="Stop Loss",minval=1)
partialExitOnIndicator=input(title = "Partial Exit with VWAP or Fib R3", defval="VWAP_crossunder_upperBB", options = ['VWAP_crossunder_upperBB', 'VWAP_crossover_FibR3','VWAP_crossunder_FibR3'])
sma200=sma(close,200)
plot(sma200, title="SMA 200", color=color.orange)
myVwap=vwap(hlc3)
//weekly vwap
//myVwap=security(syminfo.tickerid, 'W', vwap)
//bollinger calculation
basis = sma(myVwap, bbLength)
dev = mult * stdev(myVwap, bbLength)
upperBand = basis + dev
lowerBand = basis - dev
//plot bb
plot(basis, "Basis", color=color.teal, style=plot.style_circles , offset = offset)
p1 = plot(upperBand, "Upper", color=color.teal, offset = offset)
p2 = plot(lowerBand, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=color.teal, transp=95)
plot(myVwap, title="VWAP", color=color.purple)
//plot(myVwapW, title="VWAPWeekly", color=color.orange)
//pivot points
// Calc High
high_cur = 0.0
high_cur := is_newbar(pp_res) ? high : max(high_cur[1], high)
phigh = 0.0
phigh := is_newbar(pp_res) ? high_cur[1] : phigh[1]
// Calc Low
low_cur = 0.0
low_cur := is_newbar(pp_res) ? low : min(low_cur[1], low)
plow = 0.0
plow := is_newbar(pp_res) ? low_cur[1] : plow[1]
// Calc Close
pclose = 0.0
pclose := is_newbar(pp_res) ? close[1] : pclose[1]
// CALCULATE fibonacci pivots //
vPP = (phigh + plow + pclose) / 3
//vPP = (phigh + plow + pclose) / 3
vR1 = vPP + (phigh - plow) * 0.382
vS1 = vPP - (phigh - plow) * 0.382
vR2 = vPP + (phigh - plow) * 0.618
vS2 = vPP - (phigh - plow) * 0.618
vR3 = vPP + (phigh - plow) * 1.000
vS3 = vPP - (phigh - plow) * 1.000
// CALCULATE fibonacci pivots //
//pivot points
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
strategy.entry(id="BB_VWAP_PP",long=true, qty=qty1, when= crossover(myVwap,basis) and close>=vPP )
bgcolor(strategy.position_size>=1?color.blue:na, transp=75)
barcolor(strategy.position_size>=1?color.green:na)
stopLossVal= strategy.position_size>=1 ? close * (1 - (stopLoss*0.01) ) : 0.00
//partial exit
//strategy.close(id="BBofVwap", qty=strategy.position_size/3, when=crossunder(myVwap,upperBand) and strategy.position_size>=1 ) //and close>strategy.position_avg_price)
//exit on lowerband or stoploss
if(partialExitOnIndicator=="VWAP_crossunder_upperBB")
strategy.close(id="BB_VWAP_PP", comment="PExtonVWAP" , qty=strategy.position_size/3, when= crossunder(myVwap,upperBand) and strategy.position_size>=1 and close>strategy.position_avg_price) //
else if (partialExitOnIndicator=="VWAP_crossover_FibR3")
strategy.close(id="BB_VWAP_PP", comment="PExtonFibR3" , qty=strategy.position_size/3, when= crossover(myVwap,vR3) and strategy.position_size>=1 and close>strategy.position_avg_price) // or (close[1]<vR3[1] and close>vR3[1] )
else if (partialExitOnIndicator=="VWAP_crossunder_FibR3")
strategy.close(id="BB_VWAP_PP", comment="PExtonFibR3" , qty=strategy.position_size/3, when= crossunder(myVwap,vR3) and strategy.position_size>=1 and close>strategy.position_avg_price) //
strategy.close(id="BB_VWAP_PP", comment="Exit All", when=crossunder(myVwap,lowerBand) and strategy.position_size>=1 )
//strategy.close(id="BBofVwapWithFibPivot", comment="Exit All", when=crossunder(close,vPP) and strategy.position_size>=1 )
strategy.close(id="BB_VWAP_PP", comment="Stop Loss Exit", when=crossunder(close,stopLossVal) and strategy.position_size>=1 ) |
Momentum Explosion 2CCI RSI | https://www.tradingview.com/script/QFGEQDWL-Momentum-Explosion-2CCI-RSI/ | capam | https://www.tradingview.com/u/capam/ | 72 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capam
//BUY
//EMA 8 crosses upward SMA 26.
//CCI 34 periods > 0
//CCI 55 periods > 0
//RSI 26 > 48.
//Sell
//EMA 8 crosses downward SMA 26.
//CCI 34 periods < 0
//CCI 55 periods < 0
//RSI 26 < 48.
//@version=4
strategy("Momentum Explosion 2CCI RSI", overlay=true)
ema8 = ema(close,8)
sma26 = sma(close,26)
cci34 = cci(close,34)
cci55 = cci(close,55)
rsi26 = rsi(close,26)
//plot(ema8)
//plot(sma26)
//plot(cci34,color=color.green)
//plot(cci55,color=color.orange)
//plot(rsi26,color=color.red)
longCondition = crossover(ema8, sma26) and mom(sma26,5)>0 and cci34>0 and cci55>0 and rsi26>48
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(ema8, sma26) and mom(sma26,5)<0 and cci34<0 and cci55<0 and rsi26<48
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short) |
VWAP_X_EMA | https://www.tradingview.com/script/DP1S7S5j-VWAP-X-EMA/ | justvishu91 | https://www.tradingview.com/u/justvishu91/ | 486 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © justvishu91
//@version=4
strategy(title="VWAP_EMA", shorttitle="VWAP_EMA", overlay=true, commission_type=strategy.commission.percent,commission_value=0.075, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
vwapval = vwap(close)
emaval = ema(close,50)
ema200 = ema(close,200)
plot(vwapval, color=color.black, title="vwapval")
plot(emaval, color=color.green, title="emaval")
start1 = timestamp(2018, 10, 1, 0, 0)
end1 = timestamp(2020, 10, 30, 0, 0)
if time >= start1
if close > vwapval and close > emaval and close > ema200
strategy.entry("Buy", strategy.long,10 ,oca_name="VWAP", oca_type=strategy.oca.cancel)
else
strategy.cancel(id="Buy")
if close < vwapval and close < emaval
strategy.entry("Sell", strategy.short, 10,oca_name="VWAP", oca_type=strategy.oca.cancel)
else
strategy.cancel(id="Sell") |
Forex SWING Trader | https://www.tradingview.com/script/AUgQ6Ggd-Forex-SWING-Trader/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 335 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("gbpnzd 1h", overlay=true)
src = close
useCurrentRes = input(true, title="Use Current Chart Resolution?")
resCustom = input(title="Use Different Timeframe? Uncheck Box Above", type=input.resolution, defval="60")
len = input(28, title="Moving Average Length - LookBack Period")
//periodT3 = input(defval=7, title="Tilson T3 Period", minval=1)
factorT3 = input(defval=7, title="Tilson T3 Factor - *.10 - so 7 = .7 etc.", minval=0)
atype = input(2,minval=1,maxval=8,title="1=SMA, 2=EMA, 3=WMA, 4=HullMA, 5=VWMA, 6=RMA, 7=TEMA, 8=Tilson T3")
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
res = useCurrentRes ? timeframe.period : resCustom
resCustom2 = input(title="plm", type=input.resolution, defval="D")
res2 = resCustom2
//hull ma definition
hullma = wma(2*wma(src, len/2)-wma(src, len), round(sqrt(len)))
//TEMA definition
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
tema = 3 * (ema1 - ema2) + ema3
//Tilson T3
factor = factorT3 *.10
gd(src, len, factor) => ema(src, len) * (1 + factor) - ema(ema(src, len), len) * factor
t3(src, len, factor) => gd(gd(gd(src, len, factor), len, factor), len, factor)
tilT3 = t3(src, len, factor)
avg = atype == 1 ? sma(src,len) : atype == 2 ? ema(src,len) : atype == 3 ? wma(src,len) : atype == 4 ? hullma : atype == 5 ? vwma(src, len) : atype == 6 ? rma(src,len) : atype == 7 ? 3 * (ema1 - ema2) + ema3 : tilT3
out = avg
ema20 = security(syminfo.tickerid, res, out)
plot3 = security(syminfo.tickerid, res2, ema20)
plot33 = security(syminfo.tickerid, res, ema20)
plot(plot3,linewidth=2,color=color.red)
plot(plot33,linewidth=2,color=color.white)
// longC = crossover(close[2], plot3) and close[1] > close[2] and close > close[1]
// shortc = crossunder(close[2],plot3) and close[1] < close[2] and close < close[1]
volumeMA=input(24)
ema_1 = ema(volume, volumeMA)
timeinrange(res, sess) => time(res, sess) != 0
//entrytime = timeinrange(timeframe.period, "0900-0915")
myspecifictradingtimes = input('0900-2300', type=input.session, title="My Defined Hours")
entrytime = time(timeframe.period, myspecifictradingtimes) != 0
longC = crossover(plot33,plot3) and time_cond and entrytime
shortc = crossunder(plot33,plot3) and time_cond and entrytime
// exitlong = crossunder(plot33,plot3)
// exitshort = crossover(plot33,plot3)
distanta=input(1.0025)
exitshort = plot33/plot3 > distanta
exitlong = plot3/plot33 > distanta
inverse = input(true)
exit = input(false)
if(inverse==false)
strategy.entry("long",1,when=longC)
strategy.entry("short",0,when=shortc)
if(inverse)
strategy.entry("long",1,when=shortc)
strategy.entry("short",0,when=longC)
if(exit)
strategy.close("long",when=exitlong)
strategy.close("short",when=exitshort)
// if(dayofweek==dayofweek.friday)
// strategy.close_all()
risk = input(25)
strategy.risk.max_intraday_loss(risk, strategy.percent_of_equity) |
Higher TF - Repainting + Limiting backtest results | https://www.tradingview.com/script/P8NIR0uQ-Higher-TF-Repainting-Limiting-backtest-results/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 71 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Higher TF - Repainting", overlay=true, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01, calc_on_order_fills = true)
HTFMultiplier = input(4, minval=1, step=1)
AtrMAType = input(title="Moving Average Type", defval="rma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
SupertrendMult = input(1)
SupertrendPd = input(4, minval=4, step=4)
backtestBars = input(title="Backtest from ", defval=10, minval=1, maxval=30)
backtestFrom = input(title="Timeframe", defval="years", options=["days", "months", "years"])
repaintOption = input(title="Repaint", defval="Yes - lookahead : true and merge : true",
options=[
"Yes - lookahead : true and merge : true",
"Yes - lookahead : true and merge : false",
"Yes - lookahead/merge false",
"Minimal - use custom f_security",
"Minimal - use custom f_secureSecurity",
"No - do not use security"]
)
usePreviousBar = input(false)
f_multiple_resolution(HTFMultiplier) =>
target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 7. * 24. * 60. :
timeframe.ismonthly ? 30.417 * 24. * 60. : na)
target_Res_In_Min <= 0.0417 ? "1S" :
target_Res_In_Min <= 0.167 ? "5S" :
target_Res_In_Min <= 0.376 ? "15S" :
target_Res_In_Min <= 0.751 ? "30S" :
target_Res_In_Min <= 1440 ? tostring(round(target_Res_In_Min)) :
tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"
f_getBackTestTimeFrom(backtestFrom, backtestBars)=>
byDate = backtestFrom == "days"
byMonth = backtestFrom == "months"
byYear = backtestFrom == "years"
date = dayofmonth(timenow)
mth = month(timenow)
yr = year(timenow)
leapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,29)
nonleapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,28)
restMonths = array.new_int(10,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,30)
array.set(leapYearDaysInMonth,2,31)
array.set(leapYearDaysInMonth,3,30)
array.set(leapYearDaysInMonth,4,31)
array.set(leapYearDaysInMonth,5,31)
array.set(leapYearDaysInMonth,6,30)
array.set(leapYearDaysInMonth,7,31)
array.set(leapYearDaysInMonth,8,30)
array.set(leapYearDaysInMonth,9,31)
array.concat(leapYearDaysInMonth,restMonths)
array.concat(nonleapYearDaysInMonth,restMonths)
isLeapYear = yr % 4 == 0 and (year%100 != 0 or year%400 == 0)
numberOfDaysInCurrentMonth = isLeapYear ? array.get(leapYearDaysInMonth, mth-2) : array.get(nonleapYearDaysInMonth, mth-2)
if(byDate)
mth := (date - backtestBars) < 0 ? mth - 1 : mth
yr := mth < 1 ? yr - 1 : yr
mth := mth < 1 ? 1 : mth
date := (date - backtestBars) < 0 ? numberOfDaysInCurrentMonth - backtestBars + date + 1 : date - backtestBars + 1
if(byMonth)
date := 1
yr := (mth - (backtestBars%12)) < 0 ? yr - int(backtestBars/12) - 1 : yr - int(backtestBars/12)
mth := mth - (backtestBars%12) + 1
if(byYear)
date := 1
mth := 1
yr := yr - backtestBars
[date, mth, yr]
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
f_security(_symbol, _res, _src, _repaint) => security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1]
f_getSupertrend(HTFMultiplier, AtrMAType, SupertrendMult, SupertrendPd, wicks, useSecureSecurity, repaint)=>
hHigh = useSecureSecurity? f_secureSecurity(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), high) : f_security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), high, repaint)
hLow = useSecureSecurity? f_secureSecurity(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), low) : f_security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), low, repaint)
hOpen = useSecureSecurity? f_secureSecurity(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), open) : f_security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), open, repaint)
hClose = useSecureSecurity? f_secureSecurity(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), close) : f_security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), close, repaint)
truerange = max(hHigh, hClose[1]) - min(hLow, hClose[1])
averagetruerange = f_getMovingAverage(truerange, AtrMAType, SupertrendPd)
atr = averagetruerange * SupertrendMult
dir = -1
longStop = hClose - atr
longStopPrev = nz(longStop[1], longStop)
longStop := nz(dir[1], dir) == -1 ? max(longStop, longStopPrev) : longStop
shortStop = hClose + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := nz(dir[1], dir) == 1 ? min(shortStop, shortStopPrev) : shortStop
lowToHigh = (wicks ? hHigh : hClose) > shortStopPrev
highToLow = (wicks ? hLow : hClose) < longStopPrev
dir := nz(dir[1], dir)
dir := dir == 1 and lowToHigh ? -1 : dir == -1 and highToLow ? 1 : dir
trailingStop = dir == -1? longStop : shortStop
[trailingStop, dir]
repaint = repaintOption == "Yes - lookahead : true and merge : true"
useLookAheadButNotMerge = repaintOption == "Yes - lookahead : true and merge : false"
useSecurityLookahead = repaintOption == "Yes - lookahead/merge false"
useCustomSecurity = repaintOption == "Minimal - use custom f_security"
useCustomSecureSecurity = repaintOption == "Minimal - use custom f_secureSecurity"
[SupertrendRepaint, DirRepaint] = security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), supertrend(SupertrendMult, SupertrendPd), lookahead = true, gaps=true)
[SupertrendLookahead, DirLookahead] = security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), supertrend(SupertrendMult, SupertrendPd), lookahead = true, gaps=false)
[SupertrendNoLookahead, DirNoLookahead] = security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), supertrend(SupertrendMult, SupertrendPd), lookahead = false, gaps=false)
[SupertrendSecure1, DirSecure1] = f_getSupertrend(HTFMultiplier, AtrMAType, SupertrendMult, SupertrendPd, false, false, false)
[SupertrendSecure2, DirSecure2] = f_getSupertrend(HTFMultiplier, AtrMAType, SupertrendMult, SupertrendPd, false, true, false)
[SupertrendRegular, DirRegular] = supertrend(SupertrendMult, SupertrendPd)
[date, mth, yr] = f_getBackTestTimeFrom(backtestFrom, backtestBars)
inDateRange = time >= timestamp(syminfo.timezone, yr, mth, date, 0, 0)
offset = usePreviousBar? 1 : 0
longCondition = repaint ? DirRepaint[offset] == -1 :
useSecurityLookahead? DirNoLookahead[offset] == -1 :
useLookAheadButNotMerge? DirLookahead[offset] == -1 :
useCustomSecurity? DirSecure1 == -1 :
useCustomSecureSecurity? DirSecure2 == -1 :
DirRegular == -1
shortCondition = repaint ? DirRepaint[offset] == 1 :
useSecurityLookahead? DirNoLookahead[offset] == 1 :
useLookAheadButNotMerge? DirLookahead[offset] == 1 :
useCustomSecurity? DirSecure1 == 1 :
useCustomSecureSecurity? DirSecure2 == 1 :
DirRegular == 1
strategy.entry("Buy", strategy.long, when=longCondition and inDateRange)
strategy.entry("Sell", strategy.short, when=shortCondition and inDateRange)
|
BuyHighSellLow - Pivot points | https://www.tradingview.com/script/QH80tb5z-BuyHighSellLow-Pivot-points/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 230 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("BuyHighSellLow - Pivot points", overlay=true, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
Source = input(close)
resolution = input("4D", type=input.resolution)
HTFMultiplier = input(4, title="Higher Timeframe multiplier (Used when resolution is set to Same as Symbol)", minval=2, step=1)
//ppType = input(title="Pivot points type", defval="classic", options=["classic", "fib"])
ppType = "fib"
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
backtestBars = input(title="Backtest from ", defval=10, minval=1, maxval=30)
backtestFrom = input(title="Timeframe", defval="years", options=["days", "months", "years"])
hideBands = input(true)
f_multiple_resolution(HTFMultiplier) =>
target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 7. * 24. * 60. :
timeframe.ismonthly ? 30.417 * 24. * 60. : na)
target_Res_In_Min <= 0.0417 ? "1S" :
target_Res_In_Min <= 0.167 ? "5S" :
target_Res_In_Min <= 0.376 ? "15S" :
target_Res_In_Min <= 0.751 ? "30S" :
target_Res_In_Min <= 1440 ? tostring(round(target_Res_In_Min)) :
tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"
f_getBackTestTimeFrom(backtestFrom, backtestBars)=>
byDate = backtestFrom == "days"
byMonth = backtestFrom == "months"
byYear = backtestFrom == "years"
date = dayofmonth(timenow)
mth = month(timenow)
yr = year(timenow)
leapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,29)
nonleapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,28)
restMonths = array.new_int(10,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,30)
array.set(leapYearDaysInMonth,2,31)
array.set(leapYearDaysInMonth,3,30)
array.set(leapYearDaysInMonth,4,31)
array.set(leapYearDaysInMonth,5,31)
array.set(leapYearDaysInMonth,6,30)
array.set(leapYearDaysInMonth,7,31)
array.set(leapYearDaysInMonth,8,30)
array.set(leapYearDaysInMonth,9,31)
array.concat(leapYearDaysInMonth,restMonths)
array.concat(nonleapYearDaysInMonth,restMonths)
isLeapYear = yr % 4 == 0 and (year%100 != 0 or year%400 == 0)
numberOfDaysInCurrentMonth = isLeapYear ? array.get(leapYearDaysInMonth, mth-2) : array.get(nonleapYearDaysInMonth, mth-2)
if(byDate)
mth := (date - backtestBars) < 0 ? mth - 1 : mth
yr := mth < 1 ? yr - 1 : yr
mth := mth < 1 ? 1 : mth
date := (date - backtestBars) < 0 ? numberOfDaysInCurrentMonth - backtestBars + date + 1 : date - backtestBars + 1
if(byMonth)
date := 1
yr := (mth - (backtestBars%12)) < 0 ? yr - int(backtestBars/12) - 1 : yr - int(backtestBars/12)
mth := mth - (backtestBars%12) + 1
if(byYear)
date := 1
mth := 1
yr := yr - backtestBars
[date, mth, yr]
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
f_getClassicPivots(HIGHprev, LOWprev, CLOSEprev)=>
PP = (HIGHprev + LOWprev + CLOSEprev) / 3
R1 = PP * 2 - LOWprev
S1 = PP * 2 - HIGHprev
R2 = PP + (HIGHprev - LOWprev)
S2 = PP - (HIGHprev - LOWprev)
R3 = PP * 2 + (HIGHprev - 2 * LOWprev)
S3 = PP * 2 - (2 * HIGHprev - LOWprev)
R4 = PP * 3 + (HIGHprev - 3 * LOWprev)
S4 = PP * 3 - (3 * HIGHprev - LOWprev)
R5 = PP * 4 + (HIGHprev - 4 * LOWprev)
S5 = PP * 4 - (4 * HIGHprev - LOWprev)
[R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5]
f_getFibPivots(HIGHprev, LOWprev, CLOSEprev)=>
PP = (HIGHprev + LOWprev + CLOSEprev) / 3
R1 = PP + 0.382 * (HIGHprev - LOWprev)
S1 = PP - 0.382 * (HIGHprev - LOWprev)
R2 = PP + 0.618 * (HIGHprev - LOWprev)
S2 = PP - 0.618 * (HIGHprev - LOWprev)
R3 = PP + (HIGHprev - LOWprev)
S3 = PP - (HIGHprev - LOWprev)
R4 = PP + 1.41 * (HIGHprev - LOWprev)
S4 = PP - 1.41 * (HIGHprev - LOWprev)
R5 = PP + 1.65 * (HIGHprev - LOWprev)
S5 = PP - 1.65 * (HIGHprev - LOWprev)
[R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5]
f_getPivotPoints(HTFMultiplier, resolution, ppType)=>
derivedResolution = resolution == ""? f_multiple_resolution(HTFMultiplier) : resolution
HIGHprev = f_secureSecurity(syminfo.tickerid, derivedResolution, high)
LOWprev = f_secureSecurity(syminfo.tickerid, derivedResolution, low)
CLOSEprev = f_secureSecurity(syminfo.tickerid, derivedResolution, close)
[R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5] = f_getClassicPivots(HIGHprev, LOWprev, CLOSEprev)
[Rf5, Rf4, Rf3, Rf2, Rf1, PPf, Sf1, Sf2, Sf3, Sf4, Sf5] = f_getFibPivots(HIGHprev, LOWprev, CLOSEprev)
[R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5]
f_getState(Source, R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5)=>
state =
Source > R5 ? 5 :
Source > R4 ? 4 :
Source > R3 ? 3 :
Source > R2 ? 2 :
Source > R1 ? 1 :
Source > PP ? 0 :
Source > S1 ? -1 :
Source > S2 ? -2 :
Source > S3 ? -3 :
Source > S4 ? -4 :
Source > S5 ? -5 : -6
state
[R5, R4, R3, R2, R1, PP, S1, S2, S3, S4, S5] = f_getPivotPoints(HTFMultiplier, resolution, ppType)
[date, mth, yr] = f_getBackTestTimeFrom(backtestFrom, backtestBars)
inDateRange = time >= timestamp(syminfo.timezone, yr, mth, date, 0, 0)
BBU5 = plot(not hideBands ? R5: na, title="R5", color=color.orange, linewidth=1, transp=50, style=plot.style_linebr)
BBU4 = plot(not hideBands ? R4: na, title="R4", color=color.yellow, linewidth=1, transp=50, style=plot.style_linebr)
BBU3 = plot(not hideBands ? R3: na, title="R3", color=color.navy, linewidth=1, transp=50, style=plot.style_linebr)
BBU2 = plot(not hideBands ? R2: na, title="R2", color=color.olive, linewidth=1, transp=50, style=plot.style_linebr)
BBU1 = plot(not hideBands ? R1: na, title="R1", color=color.lime, linewidth=1, transp=50, style=plot.style_linebr)
BBM4 = plot(not hideBands ? PP:na, title="PP", color=color.black, linewidth=2, style=plot.style_linebr)
BBL1 = plot(not hideBands ? S1: na, title="S1", color=color.lime, linewidth=1, transp=50, style=plot.style_linebr)
BBL2 = plot(not hideBands ? S2: na, title="S2", color=color.olive, linewidth=1, transp=50, style=plot.style_linebr)
BBL3 = plot(not hideBands ? S3: na, title="S3", color=color.navy, linewidth=1, transp=50, style=plot.style_linebr)
BBL4 = plot(not hideBands ? S4: na, title="S4", color=color.yellow, linewidth=1, transp=50, style=plot.style_linebr)
BBL5 = plot(not hideBands ? S5: na, title="S5", color=color.orange, linewidth=1, transp=50, style=plot.style_linebr)
fill(BBU5, BBU4, title="RZ5", color=color.green, transp=90)
fill(BBU4, BBU3, title="RZ4", color=color.lime, transp=90)
fill(BBU3, BBU2, title="RZ3", color=color.olive, transp=90)
fill(BBU2, BBU1, title="RZ2", color=color.navy, transp=90)
fill(BBU1, BBM4, title="RZ1", color=color.yellow, transp=90)
fill(BBM4, BBL1, title="SZ1", color=color.orange, transp=90)
fill(BBL1, BBL2, title="SZ2", color=color.red, transp=90)
fill(BBL2, BBL3, title="SZ3", color=color.maroon, transp=90)
fill(BBL3, BBL4, title="SZ4", color=color.maroon, transp=90)
fill(BBL4, BBL5, title="SZ5", color=color.maroon, transp=90)
strategy.risk.allow_entry_in(tradeDirection)
longCondition = crossover(Source[1],R1) and inDateRange
shortCondition = crossunder(Source[1], S2) and inDateRange
strategy.entry("Buy", strategy.long, when=longCondition, oca_name="oca", oca_type=strategy.oca.cancel)
strategy.entry("Sell", strategy.short, when=shortCondition, oca_name="oca", oca_type=strategy.oca.cancel)
|
IFR2 - RSI2 | https://www.tradingview.com/script/n1e8MLFl-IFR2-RSI2/ | jocker.soad | https://www.tradingview.com/u/jocker.soad/ | 61 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jocker.soad
//@version=4
strategy("My Script", overlay=true, initial_capital=10000, default_qty_value=100)
min = input(title="Valor minimo de entrada", defval=25)
qtdAtivos = input(title="Quantidade de ações", defval=200)
// overBuyLine = hline(80)
// overSellLine = hline(min)
var comprado = false
var valorComprado = 0.0
var qtdDiasComprado = 0
var valorLucro = 0.0
valueRsi = rsi(close, 2)
valueSma = sma(close, 200)
valueEma = ema(close, 200)
lastHighPrice = high[2]
buyValidation = valueRsi <= min
sellValidation = close >= lastHighPrice
// plot(lastHighPrice, trackprice=true, offset=-99999, color=color.olive, linewidth=3, style=plot.style_area)
// plot(valueRsi)
// plot(valueSma)
// plot(valueEma)
// plotshape(sellValidation, style=shape.triangledown, color=color.blue)
// plotshape(comprado, style=shape.triangledown, color=color.blue)
startDate = input(title="Inicio Dia", type=input.integer, defval=1, minval=1, maxval=31)
startMonth = input(title="Inicio Mes", type=input.integer, defval=1, minval=1, maxval=12)
startYear = input(title="Inicio Ano", type=input.integer, defval=2018, minval=1800, maxval=2100)
endDate = input(title="Final Dia", type=input.integer, defval=1, minval=1, maxval=31)
endMonth = input(title="Final Mes", type=input.integer, defval=12, minval=1, maxval=12)
endYear = input(title="Final Ano", type=input.integer, defval=2020, minval=1800, maxval=2100)
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
if inDateRange
if close >= valueEma
if comprado == false and buyValidation
qtdDiasComprado := 0
comprado := true
valorComprado := close
strategy.order("buy", true, qtdAtivos, when=buyValidation)
if sellValidation and comprado == true
comprado := false
valorLucro := valorLucro + (close - valorComprado)
valorComprado := 0
strategy.order("sell", false, qtdAtivos, when=sellValidation)
if comprado == true and sellValidation == false
qtdDiasComprado := qtdDiasComprado + 1
// plot(valorLucro, color=color.lime)
|
Guerilla Fear/Greed Index Strategy | https://www.tradingview.com/script/P1e5S99o-Guerilla-Fear-Greed-Index-Strategy/ | calebsandfort | https://www.tradingview.com/u/calebsandfort/ | 366 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © calebsandfort
//@version=4
strategy(title = "Guerilla Fear/Greed Index Strategy", shorttitle = "GFGI Strat", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, calc_on_every_tick=true)
maLength = input(title="MA Length", defval=10)
/////////////////////NAAIM Component/////////////////////
naaim_weight = input(title="NAAIM Weight", defval=50) / 100
naaim_fear_threshold = input(title="NAAIM Fear Threshold", defval=50)
naaim_greed_threshold = input(title="NAAIM Greed Threshold", defval=90)
naaim = security("QUANDL:NAAIM/NAAIM", "W", close)
naaimMa = ema(naaim, maLength)
naaimComponent = (naaimMa < naaim_fear_threshold ? 0 : naaimMa > naaim_greed_threshold ? 100 : ((naaimMa - naaim_fear_threshold)/(naaim_greed_threshold - naaim_fear_threshold)) * 100) * naaim_weight
/////////////////////Equity Put/Call Ratio Component/////////////////////
pcce_weight = input(title="EPCR Weight", defval=50) / 100
pcce_fear_threshold = input(title="EPCR Fear Threshold", defval=.7)
pcce_greed_threshold = input(title="EPCR Greed Threshold", defval=.55)
pcce = security ("USI:PCCE", "D", close)
pcceMa = ema(pcce, maLength)
pcceComponent = (pcceMa > pcce_fear_threshold ? 0 : pcceMa < pcce_greed_threshold ? 100 : ((pcce_fear_threshold - pcceMa)/(pcce_fear_threshold - pcce_greed_threshold)) * 100) * pcce_weight
/////////////////////Guerilla Fear/Greed Index/////////////////////
buyLevel = input(title="Buy Level", defval=40)
sellLevel = input(title="Sell Level", defval=65)
buyHline = hline(buyLevel, color = color.gray, linestyle = hline.style_dashed)
sellHline = hline(sellLevel, color = color.gray, linestyle = hline.style_dashed)
gfgi = naaimComponent + pcceComponent
color1 = #ff0000
color2 = #ff6400
color3 = #ff9900
color4 = #ffc700
color5 = #fff200
color6 = #d3e100
color7 = #a9cf00
color8 = #7fbd00
color9 = #54aa00
color10 = #1e9600
gfgiColor = gfgi < 10 ? color1 : gfgi < 20 ? color2 : gfgi < 30 ? color3 : gfgi < 40 ? color4 :gfgi < 50 ? color5 :gfgi < 60 ? color6 :gfgi < 70 ? color7 : gfgi < 80 ? color8 : gfgi < 90 ? color9 : color10
plot(gfgi, color=gfgiColor, linewidth = 2)
gfgiMaLength = input(title="GFGI MA Length", defval=21)
gfgiMa = ema(gfgi, gfgiMaLength)
gfgiMaColor = gfgiMa < 10 ? color1 : gfgiMa < 20 ? color2 : gfgiMa < 30 ? color3 : gfgiMa < 40 ? color4 :gfgiMa < 50 ? color5 :gfgiMa < 60 ? color6 :gfgiMa < 70 ? color7 : gfgiMa < 80 ? color8 : gfgiMa < 90 ? color9 : color10
plot(gfgiMa, color=gfgiMaColor, style=plot.style_circles)
startDate = input(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", defval=2015, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
useCloseDate = input(title="Use Close Date", defval=true)
closeDay = input(title="Close Day", defval=20, minval=1, maxval=31)
closeMonth = input(title="Close Month", defval=11, minval=1, maxval=12)
closeYear = input(title="Close Year", defval=2020, minval=1800, maxval=2100)
// See if this bar's time happened on/after end date
afterEndDate = year == closeYear and month == closeMonth and dayofmonth == closeDay
Bull = gfgiMa[1] < buyLevel and (gfgiMa[0] > gfgiMa[1]) and (gfgiMa[2] > gfgiMa[1])
Bear = gfgiMa[1] > sellLevel and (gfgiMa[0] < gfgiMa[1]) and (gfgiMa[2] < gfgiMa[1])
///Entries and Exits//
if (Bull and afterStartDate)
strategy.entry("Long", strategy.long, comment = "LE")
if ((afterStartDate and Bear) or (useCloseDate and afterEndDate))
strategy.close("Long", qty_percent=100, comment="close") |
BTC 15 min | https://www.tradingview.com/script/xGk5K4DE-BTC-15-min/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 928 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni
//@version=4
strategy(title = " BTC 15 min", overlay = true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 20, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.075)
strat_dir_input = input(title="Strategy Direction", defval="all", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
price = close
length8 = input(30,title = 'length of channel')
upmult = input(title = 'upper percent',type=input.float, step=0.1, defval=5)
lowmult = input(title = 'lower percent',type=input.float, step=0.1, defval=5)
basis = sma(close, length8)
vup = upmult * price / 100
vlow = lowmult * price / 100
upper = basis + vup
lower = basis - vlow
plot(basis, color=color.red)
//
fastLength = input(3, title="Fast filter length ", minval=1)
slowLength = input(21,title="Slow filter length", minval=1)
source=close
v1=ema(source,fastLength)
v2=ema(source,slowLength)
//
leng=1
p1=close[1]
len55 = 10
//taken from https://www.tradingview.com/script/Ql1FjjfX-security-free-MTF-example-JD/
HTF = input("1D", type=input.resolution)
ti = change( time(HTF) ) != 0
T_c = fixnan( ti ? close : na )
vrsi = rsi(cum(change(T_c) * volume), leng)
pp=wma(vrsi,len55)
d=(vrsi[1]-pp[1])
len100 = 10
x=ema(d,len100)
//
zx=x/-1
col=zx > 0? color.lime : color.orange
//
tf10 = input("1", title = "Timeframe", type = input.resolution, options = ["1", "5", "15", "30", "60","120", "240","360","720", "D", "W"])
length = input(50, title = "Period", type = input.integer)
shift = input(1, title = "Shift", type = input.integer)
hma(_src, _length)=>
wma((2 * wma(_src, _length / 2)) - wma(_src, _length), round(sqrt(_length)))
hma3(_src, _length)=>
p = length/2
wma(wma(close,p/3)*3 - wma(close,p/2) - wma(close,p),p)
b =security(syminfo.tickerid, tf10, hma3(close[1], length)[shift])
//plot(a,color=color.gray)
//plot(b,color=color.yellow)
close_price = close[0]
len = input(25)
linear_reg = linreg(close_price, len, 0)
buy=crossover(linear_reg, b)
sell=crossunder(linear_reg, b) or crossunder(close[1],upper)
//
src2=low
src3=high
Min =input(15)
leni = timeframe.isintraday and timeframe.multiplier >= 1 ?
Min / timeframe.multiplier * 7 :
timeframe.isintraday and timeframe.multiplier < 60 ?
60 / timeframe.multiplier * 24 * 7 : 7
l1 = wma(src2,leni)
h1 = wma(src3,leni)
//
m=(h1+l1)/2
//
len5 = 100
src5=m
//
multi = 2
mean = ema(src5, len5)
stddev = multi * stdev(src5, len5)
b5 = mean + stddev
s5 = mean - stddev
var bool long = na
var bool short = na
long :=crossover(src5, s5)
short := crossunder(src5, b5)
var float last_open_long = na
var float last_open_short = na
last_open_long := long ? close : nz(last_open_long[1])
last_open_short := short ? close : nz(last_open_short[1])
entry_value =last_open_long
entry_value1=last_open_short
r=100
//
highb = highest(entry_value1, r)
lowb = lowest(entry_value, r)
d5 = highb - lowb
me = (highb + lowb) / 2
h4 = highb - d5 * 0.236
c3 = highb - d5 * 0.382
c4 = highb - d5 * 0.618
l4 = highb - d5 * 0.764
//
col2 = close >= me ? color.lime : color.red
p5 = plot(upper, color=col2)
p2 = plot(lower, color=col2)
fill(p5, p2,color=col2)
// Conditions
longCond = bool(na)
shortCond = bool(na)
longCond := crossover(zx,0) or buy
shortCond := sell
// Count your long short conditions for more control with Pyramiding
sectionLongs = 0
sectionLongs := nz(sectionLongs[1])
sectionShorts = 0
sectionShorts := nz(sectionShorts[1])
if longCond
sectionLongs := sectionLongs + 1
sectionShorts := 0
sectionShorts
if shortCond
sectionLongs := 0
sectionShorts := sectionShorts + 1
sectionShorts
// Pyramiding
pyrl = 1
// These check to see your signal and cross references it against the pyramiding settings above
longCondition = longCond and sectionLongs <= pyrl
shortCondition = shortCond and sectionShorts <= pyrl
// Get the price of the last opened long or short
last_open_longCondition = float(na)
last_open_shortCondition = float(na)
last_open_longCondition := longCondition ? open : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? open : nz(last_open_shortCondition[1])
// Check if your last postion was a long or a short
last_longCondition = float(na)
last_shortCondition = float(na)
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition
// Take profit
isTPl = true
//isTPs = input(false, "Take Profit Short")
tp = input(2, "Exit Profit %", type=input.float)
long_tp = isTPl and crossover(high, (1 + tp / 100) * last_open_longCondition) and longCondition == 0 and in_longCondition == 1
//short_tp = isTPs and crossunder(low, (1 - tp / 100) * last_open_shortCondition) and
//shortCondition == 0 and in_shortCondition == 1
// Stop Loss
isSLl = input(true,"buy Loss Long")
//isSLs = input(false, "buy Loss Short")
sl = 0.0
sl := input(5, " rebuy %", type=input.float)
long_sl = isSLl and crossunder(low, (1 - sl / 100) * last_open_longCondition) and
longCondition == 0 and in_longCondition == 1
//short_sl = isSLs and crossover(high, (1 + sl / 100) * last_open_shortCondition) and
//shortCondition == 0 and in_shortCondition == 1
//
// Conditions
longCond5 = bool(na)
shortCond5 = bool(na)
longCond5 := longCondition
shortCond5 := long_tp
//
sectionLongs5 = 0
sectionLongs5 := nz(sectionLongs5[1])
sectionShorts5 = 0
sectionShorts5 := nz(sectionShorts5[1])
if longCond5
sectionLongs5 := sectionLongs5 + 1
sectionShorts5 := 0
sectionShorts5
if shortCond5
sectionLongs5 := 0
sectionShorts5 := sectionShorts5 + 1
sectionShorts5
//
pyr5 = 1
longCondition5 = longCond5 and sectionLongs5 <= pyr5
shortCondition5 = shortCond5 and sectionShorts5 <= pyr5
// Get the price of the last opened long or short
last_open_longCondition5 = float(na)
last_open_shortCondition5 = float(na)
last_open_longCondition5 := longCondition5 ? open : nz(last_open_longCondition5[1])
last_open_shortCondition5 := shortCondition5 ? open : nz(last_open_shortCondition5[1])
last_longCondition5 = float(na)
last_shortCondition5 = float(na)
last_longCondition5 := longCondition5 ? time : nz(last_longCondition5[1])
last_shortCondition5 := shortCondition5 ? time : nz(last_shortCondition5[1])
in_longCondition5 = last_longCondition5 > last_shortCondition5
in_shortCondition5 = last_shortCondition5 > last_longCondition5
//
filter=input(true)
g(v, p) => round(v * (pow(10, p))) / pow(10, p)
risk = input(100)
leverage = input(1)
c = g((strategy.equity * leverage / open) * (risk / 100), 4)
//
l =(v1 > v2 or filter == false ) and longCondition or long_sl
//
//l = longCondition or long_sl
s=shortCondition5
if l
strategy.entry("buy", strategy.long,c)
if s
strategy.entry("sell", strategy.short,c)
per(pcnt) =>
strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
stoploss=input(title=" stop loss", defval=5, minval=0.01)
los = per(stoploss)
q1=input(title=" qty_percent1", defval=50, minval=1)
q2=input(title=" qty_percent2", defval=50, minval=1)
tp10=input(title=" Take profit1", defval=1, minval=0.01)
tp20=input(title=" Take profit2", defval=2, minval=0.01)
strategy.exit("x1", qty_percent = q1, profit = per(tp10), loss = los)
strategy.exit("x2", qty_percent = q2, profit = per(tp20), loss = los)
|
test_%_down_up | https://www.tradingview.com/script/ePXObTe3-test-down-up/ | luboremenar | https://www.tradingview.com/u/luboremenar/ | 12 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © luboremenar
//@version=4
strategy("test_%_down_up", overlay = false, initial_capital = 1000, pyramiding = 0, default_qty_value = 1000,
default_qty_type = strategy.cash, precision = 8, commission_type = strategy.commission.percent, commission_value = 0.1)
// inputs
range_of_tops = input(title="Range of candles to find highest value from.", defval=90, type=input.integer, minval=1 )
basis_points = input(title="Basis points, if asset has two decimals use 100, three decimals 1000, etc.", defval=100, type=input.integer, minval=1)
retrace_percent = input(title="Percent value retrace from the top.", type=input.integer, defval=3, minval = 1, maxval=99)
take_profit_percent = input(title="Percent value of take profit from entry price.", type=input.integer, defval=6, minval=1)
// strategy definition
three_months_top = highest(range_of_tops)
longCondition1 = (close <= float((three_months_top*(1-(take_profit_percent/100)))) and strategy.position_size == 0)
if (longCondition1)
strategy.entry("Long1", strategy.long, qty = strategy.equity/close)
strategy.exit(id="TP1", from_entry="Long1", profit=((close*(1 + take_profit_percent/100)-close)*basis_points),
when= crossover(strategy.position_size, 0))
// plot
plot(strategy.equity)
// for testing, debugging
//test=0.0
//if(crossover(strategy.position_size, 0))
// test := (close*1.06-close)*basis_points
//plot(test) |
BTC bot | https://www.tradingview.com/script/DPBeZbMP-BTC-bot/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 2,006 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni
// © theCrypster 2020
//@version=4
strategy(title = "BTC bot", overlay = true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.075)
strat_dir_input = input(title="Strategy Direction", defval="long", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
//INPUTS
higherTF = input("W", type=input.resolution)
pc = security(syminfo.tickerid, higherTF, close[1], lookahead=true)
ph = security(syminfo.tickerid, higherTF, high[1], lookahead=true)
pl = security(syminfo.tickerid, higherTF, low[1], lookahead=true)
PP = 0.0,R1 = 0.0, R2 = 0.0, R3 = 0.0,S1 = 0.0, S2 = 0.0, S3 = 0.0
PP := (ph + pl + pc) / 3
R1 := PP + (PP - pl)
S1 := PP - (ph - PP)
R2 := PP + (ph - pl)
S2 := PP - (ph - pl)
factor=input(2)
R3 := ph + factor * (PP - pl)
S3 := pl - 2 * (ph - PP)
//
length=input(21)
//
p = close
vrsi = rsi(p, length)
pp=ema(vrsi,length)
d=(vrsi-pp)*5
cc=(vrsi+d+pp)/2
//
low1=crossover(cc,0)
sell=crossover(close[1],R3)
//
l = low1
s=sell
if l
strategy.entry("buy", strategy.long)
if s
strategy.entry("sell", strategy.short)
per(pcnt) =>
strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
stoploss=input(title=" stop loss", defval=15, minval=0.01)
los = per(stoploss)
q1=input(title=" qty_percent1", defval=25, minval=1)
q2=input(title=" qty_percent2", defval=25, minval=1)
q3=input(title=" qty_percent3", defval=25, minval=1)
tp1=input(title=" Take profit1", defval=3, minval=0.01)
tp2=input(title=" Take profit2", defval=5, minval=0.01)
tp3=input(title=" Take profit3", defval=7, minval=0.01)
tp4=input(title=" Take profit4", defval=10, minval=0.01)
strategy.exit("x1", qty_percent = q1, profit = per(tp1), loss = los)
strategy.exit("x2", qty_percent = q2, profit = per(tp2), loss = los)
strategy.exit("x3", qty_percent = q3, profit = per(tp3), loss = los)
strategy.exit("x4", profit = per(tp4), loss = los)
|
Swing/Daytrading strategy with reversal option | https://www.tradingview.com/script/MEPX6LRn-Swing-Daytrading-strategy-with-reversal-option/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 463 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("CLOSE HIGH T3",overlay=true)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
timeinrange(res, sess) => time(res, sess) != 0
Length = input(9, minval=1)
xPrice = close
xe1 = ema(xPrice, Length)
xe2 = ema(xe1, Length)
xe3 = ema(xe2, Length)
xe4 = ema(xe3, Length)
xe5 = ema(xe4, Length)
xe6 = ema(xe5, Length)
b = 0.7
c1 = -b*b*b
c2 = 3*b*b+3*b*b*b
c3 = -6*b*b-3*b-3*b*b*b
c4 = 1+3*b+b*b*b+3*b*b
nT3Average = c1 * xe6 + c2 * xe5 + c3 * xe4 + c4 * xe3
plot(nT3Average, color=color.blue, title="T3")
myspecifictradingtimes = input('1000-1900', type=input.session, title="My Defined Hours")
//myspecifictradingtimes2 = input('1000-1900', type=input.session, title="My Defined Hours")
exittime = input('2100-2115', type=input.session, title="exit time")
optionmacd=true
entrytime = time(timeframe.period, myspecifictradingtimes) != 0
exiton = time(timeframe.period, exittime) != 0
//entrytime2 = time(timeframe.period, myspecifictradingtimes2) != 0
// long =time_cond and (entrytime or entrytime2) and close > high[1] and close > nT3Average
// short =time_cond and (entrytime or entrytime2) and close < low[1] and close < nT3Average
long =time_cond and (entrytime ) and close > high[1] and close > nT3Average
short =time_cond and (entrytime) and close < low[1] and close < nT3Average
tp = input(0.01)
sl = input(0.01)
modified=input(true)
inverse=input(true)
exit = input(false)
if(modified)
if(not exiton)
if(inverse)
strategy.entry("long",1,when=short)
strategy.entry("short",0,when=long)
/// strategy.exit("xlong","long",profit=200, loss=200)
// strategy.exit("xshort","short",profit=200, loss=200)
if(inverse==false)
strategy.entry("long",1,when=long)
strategy.entry("short",0,when=short)
if(exit)
// strategy.close("long", when = crossover(close,nT3Average))
// strategy.close("short", when = crossunder(close,nT3Average))
strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong")
strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
if(modified==false)
if(inverse)
strategy.entry("long",1,when=short)
strategy.entry("short",0,when=long)
/// strategy.exit("xlong","long",profit=200, loss=200)
// strategy.exit("xshort","short",profit=200, loss=200)
if(inverse==false)
strategy.entry("long",1,when=long)
strategy.entry("short",0,when=short)
// if(exit)
// // strategy.close("long", when = crossover(close,nT3Average))
// // strategy.close("short", when = crossunder(close,nT3Average))
// strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong")
// strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
//strategy.close_all(when =exiton )
//gbpnzd 10-20
//gbpcad 10-19
//gbpaud 07-19
//euruad 10-19 / 16-20
//eurnzd 08-21 / 10-20
//eurchf 08-20
//gbpchf 06-18
// 18-19settings entry gbp aud, gbpcad gbpnzd ??? 1 entry only big spread
//test |
BuyHigh-SellLow Strategy | https://www.tradingview.com/script/UCbMuA9M-BuyHigh-SellLow-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 348 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("BuyHigh-SellLow Strategy", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
donchianEntryLength = input(40, step=10)
donchianExitLength = input(20, step=10)
considerNewLongTermHighLows = input(true)
shortHighLowPeriod = input(120, step=10)
longHighLowPeriod = input(180, step=10)
considerMAAlignment = input(true)
MAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
LookbackPeriod = input(40, minval=10,step=10)
atrLength = input(22)
atrMult = input(4)
exitStrategy = input(title="Exit Strategy", defval="tsl", options=["dc", "tsl"])
considerYearlyHighLow = input(true)
backtestYears = input(10, minval=1, step=1)
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getTrailingStop(atr, atrMult)=>
stop = close - atrMult*atr
stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop
stop
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
[newHigh,newLow]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
label_x = time+(60*60*24*1000*1)
[yearlyHighCondition,yearlyLowCondition]
donchian(rangeLength)=>
upper = highest(rangeLength)
lower = lowest(rangeLength)
middle = (upper+lower)/2
[middle, upper, lower]
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
[eMiddle, eUpper, eLower] = donchian(donchianEntryLength)
[exMiddle, exUpper, exLower] = donchian(donchianExitLength)
maAlignment = f_getMaAlignment(MAType, false)
[yearlyHighCondition, yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
maAlignmentLongCondition = highest(maAlignment, LookbackPeriod) == 1 or not considerMAAlignment
atr = atr(atrLength)
tsl = f_getTrailingStop(atr, atrMult)
//U = plot(eUpper, title="Up", color=color.green, linewidth=2, style=plot.style_linebr)
//D = plot(exLower, title="Ex Low", color=color.red, linewidth=2, style=plot.style_linebr)
longCondition = crossover(close, eUpper[1]) and yearlyHighCondition and newHigh and maAlignmentLongCondition
exitLongCondition = crossunder(close, exLower[1])
shortCondition = crossunder(close, eLower[1]) and yearlyLowCondition and newLow
exitShortCondition = crossover(close, exUpper[1])
strategy.entry("Buy", strategy.long, when=longCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)
strategy.exit("ExitBuyDC", "Buy", when=exitStrategy=='dc', stop=exLower)
strategy.exit("ExitBuyTSL", "Buy", when=exitStrategy=='tsl', stop=tsl)
plot(strategy.position_size > 0 ? (exitStrategy=='dc'?exLower:tsl) : na, title="Trailing Stop", color=color.red, linewidth=2, style=plot.style_linebr)
//strategy.close("Buy", when=exitLongCondition) |
ARR VWAP Intraday | https://www.tradingview.com/script/K0ozrxGi-ARR-VWAP-Intraday/ | ALLURI_RAJU | https://www.tradingview.com/u/ALLURI_RAJU/ | 364 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ALLURI_RAJU
//@version=4
strategy("ARR VWAP Intraday", overlay=true)
starHrs = input(11, title="Trade start Hours", type=input.integer)
endHrs = input(15, title="Close all trade @ Hours", type=input.integer)
rsiPreiod = input(14, title="RSI Period", type=input.integer)
rsiBuy = input(50, title="Buy when RSI above", type=input.integer)
rsiSell = input(50, title="Sell when RSI Bellow", type=input.integer)
isReversal = input(true, title="Exit on Wap Reversal", type=input.bool)
plot(vwap,color=color.black)
o=(open[1]+close[1])/2
h=max(high,close,o)
l=min(low,close,o)
c=(open+high+low+close)/4
longCondition = vwap > vwap[1] and rsi(close,rsiPreiod)>rsiBuy and hour>starHrs and hour<endHrs
if (longCondition)
strategy.entry("Buy", strategy.long)
shortCondition = vwap < vwap[1] and rsi(close,rsiPreiod)<rsiSell and hour>starHrs and hour<endHrs
if (shortCondition)
strategy.entry("Sell", strategy.short)
if(isReversal)
strategy.close("Buy", when = vwap < vwap[1] ,comment = "ExitBuy")
strategy.close("Sell", when =vwap > vwap[1], comment = "ExitSell")
strategy.close_all(when = hour == endHrs , comment = "Exit All")
|
Amazing strategy for silver -XAGUSD, XAGEUR etc | https://www.tradingview.com/script/42w6YZPi-Amazing-strategy-for-silver-XAGUSD-XAGEUR-etc/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 102 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("XAG strategy 1h",overlay=true)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2020, title = "From Year", minval = 1970)
var gica = 0
var marcel = gica+2
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
len = input(10, minval=1, title="Length")
src = input(close, title="Source")
out = sma(src, len)
//distanta = input(1.004)
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
option1=input(false)
option2=input(false)
long2 = close > open and time_cond and close > out and hist > 0 and hist > hist[1]
short2 = close < open and time_cond and close < out and hist < 0 and hist < hist[1]
long1 = (close > open ) and time_cond and close > out and hist > 0 and hist > hist[1] and high > high[1] and high[1] > high[2] and close > high[1] and close > high[2] and close > high[3]
short1 = (close < open) and time_cond and close < out and hist < 0 and hist < hist[1] and low < low[1] and low[1] < low[2] and close < low[1] and close < low[2] and close < low[3]
if(option1)
strategy.entry("long",1,when= short1)
strategy.entry("short",0,when=long1)
strategy.close_all()
if(option2)
strategy.entry("long",1,when= short2)
strategy.entry("short",0,when=long2)
strategy.close_all()
// if(strategy.openprofit < 0)
// strategy.close_all()
// if(strategy.openprofit>0)
// strategy.close("long",when = close < open )
// strategy.close("short",when = close > open)
// strategy.close("long",when= close < open)
// strategy.close("short",when= close> open)
// tp = input(0.0003)
// sl = input(0.005)
// strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong")
// strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
|
Moving Average Crossover | https://www.tradingview.com/script/2BHPV6EC/ | Muh4mm4d | https://www.tradingview.com/u/Muh4mm4d/ | 51 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © muh4mm4dm4hr
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © muh4mm4dm4hr
//@version=4
strategy("Moving Average Crossover 1", overlay= true)
ema5 = ema(close, 5)
ema20 = ema(close, 20)
long = ema5 > ema20
short = ema5 < ema20
colorBasis = ema5 >= ema20 ? color.green : color.red
pBasis = plot(ema20, linewidth=4, color=colorBasis)
strategy.entry("long", strategy.long, 1000.0, when=long)
strategy.close("long", when = short)
|
888 BOT #backtest | https://www.tradingview.com/script/futPZepe/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 1,252 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Xaviz
//@version=4
strategy(title = "888 BOT #backtest", shorttitle = "888💹", overlay = true, initial_capital = 10000, pyramiding = 10, currency = "USD",
default_qty_type = strategy.percent_of_equity, default_qty_value = 0, commission_value = 0.04)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Inputs
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Source input
src = input(hlc3, title = " SOURCE", type = input.source)
// ————— JMA inputs
Act_JMA = input(true, title = "JURIK MOVING AVERAGE", type = input.bool)
JMA_length = input(30, title = " JMA LENGTH", type = input.integer, minval = 0)
phase = input(40, title = " JMA PHASE", type = input.integer, minval = 0)
power = input(2.5, title = " JMA POWER", type = input.float, minval = 0, step = 0.5)
// ————— Range Filter inputs
Act_RF = input(true, title = "RANGE FILTER", type = input.bool)
per = input(20, title = " SAMPLING PERIOD", type = input.integer, minval = 1)
mult = input(1.7, title = " RANGE MULTIPLIER", type = input.float, minval = 0.1, step = 0.1)
// ————— ADX inputs
Act_ADX = input(true, title = "AVERAGE DIRECTIONAL INDEX", type = input.bool)
ADX_options = input("CLASSIC", title = " ADX OPTION", options = ["CLASSIC", "MASANAKAMURA"])
ADX_len = input(22, title = " ADX LENGTH", type = input.integer, minval = 1)
th = input(20, title = " ADX THRESHOLD", type = input.float, minval = 0, step = 0.5)
// ————— SAR inputs
Act_SAR = input(true, title = "PARABOLIC SAR", type = input.bool)
Sst = input (0.25, title = " SAR STAR", type = input.float, minval = 0.01, step = 0.01)
Sinc = input (0.25, title = " SAR INC", type = input.float, minval = 0.01, step = 0.01)
Smax = input (0.13, title = " SAR MAX", type = input.float, minval = 0.01, step = 0.01)
// ————— RSI with volume inputs
Act_RSI = input(true, title = "RSI VOLUME WEIGHTED", type = input.bool)
RSI_len = input(34, title = " RSI LENGHT", type = input.integer, minval = 1)
RSI_obos = input(45, title = " RSI CENTER LINE", type = input.integer, minval = 1)
// ————— MACD / MAC-Z inputs
Act_MACD = input(true, title = "MA CONVERGENCE/DIVERGENCE", type = input.bool)
MACD_options = input("MAC-Z", title = " MACD OPTION", options = ["MACD", "MAC-Z"])
fastLength = input(45, title = " MACD FAST MA LENGTH", type = input.integer, minval = 1)
slowLength = input(47, title = " MACD SLOW MA LENGTH", type = input.integer, minval = 1)
signalLength = input(13, title = " MACD SIGNAL LENGTH", type = input.integer, minval = 1)
lengthz = input(9, title = " Z-VWAP LENGTH", type = input.integer, minval = 1)
lengthStdev = input(14, title = " STDEV LENGTH", type = input.integer, minval = 1)
// ————— Volume inputs for entries condition and for calculate quantities later
Act_Vol = input(true, title = "VOLUME CONDITION", type = input.bool)
volume_f = input(1.4, title = " VOLUME FACTOR", type = input.float, minval = 0, step = 0.1)
sma_length = input(61, title = " SMA VOLUME LENGTH", type = input.integer, minval = 1)
// ————— First take profit input
tp_long0 = input(1.7, title = " TAKE PROFIT LONG %", type = input.float, minval = 0, step = 0.1)
tp_short0 = input(1.8, title = " TAKE PROFIT SHORT %", type = input.float, minval = 0, step = 0.1)
// ————— Stop Loss input
Act_sl = input(true, title = "ACTIVATE STOP LOSS 🧻", type = input.bool)
SL_options = input("NORMAL", title = " STOP LOSS OPTION", options = ["NORMAL", "ATR", "BOTH"])
sl0 = input(3.7, title = " STOP LOSS %", type = input.float, minval = 0, step = 0.1)
// ————— ATR Inputs
atrPeriod = input(13, title = " ATR SL PERIOD", type = input.integer, minval = 0)
multiplierPeriod = input(7.0, title = " ATR SL MULTIPLIER", type = input.float, minval = 0, step = 0.1)
// ————— Risk input
Risk = input(3.5, title = " % RISK ALLOWED", type = input.float, minval = 0, step = 0.5)
// ————— Confirmed Stop loss
Act_Conf_SL = input(false, title = "STOP LOSS CONFIRMED", type = input.bool)
// ————— Bollinger Bands inputs
Act_BB = input(true, title = "ACTIVATE BOLLINGER BANDS RE-ENTRY 🚀", type = input.bool)
BB_length = input(20, title = " BB LENGTH", type = input.integer, minval = 1)
BB_mult = input(1.9, title = " BB MULTIPLIER", type = input.float, minval = 0.001, step = 0.1)
bbBetterPrice = input(0.5, title = " % MINIMUM BETTER PRICE", type = input.float, minval = 0.1, step = 0.1)
Act_divide = input(false, title = "ACTIVATE DIVIDE TP", type = input.bool)
// ————— Backtest input
Act_BT = input(true, title = "BACKTEST 💹", type = input.bool)
backtest_time = input(180, title = " BACKTEST DAYS", type = input.integer, minval = 1)*24*60*60*1000
entry_Type = input("% EQUITY", title = " ENTRY TYPE", options = ["CONTRACTS","CASH","% EQUITY"])
et_Factor = (entry_Type == "CONTRACTS") ? 1 : (entry_Type == "% EQUITY") ? (100/(strategy.equity/close)) : close
quanTity = input(8.0, title = " QUANTITY (LEVERAGE 1X)", type = input.float, minval = 0, step = 0.5) / et_Factor
Max_Lev = input(8, title = " MAXIMUM LEVERAGE", type = input.integer, minval = 1, maxval = 8)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Variables
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Long/Short
var bool longCond = na, var bool shortCond = na
var int CondIni_long = 0, var int CondIni_short = 0
var bool _Final_longCondition = na, var bool _Final_shortCondition = na
var float last_open_longCondition = na, var float last_open_shortCondition = na
var float last_dynamic_Leverage_long = na, var float last_dynamic_Leverage_short = na
var int last_longCondition = na, var int last_shortCondition = na
var int last_Final_longCondition = na, var int last_Final_shortCondition = na
var int nLongs = na, var int nShorts = na
// ————— Take profit
var bool long_tp = na, var bool short_tp = na
var int last_long_tp = na, var int last_short_tp = na
var bool Final_Long_tp = na, var bool Final_Short_tp = na
// ————— Stop Loss
var int CondIni_long_sl = 0, var int CondIni_short_sl = 0
var bool Final_Long_sl0 = na, var bool Final_Short_sl0 = na
var bool Final_Long_sl = na, var bool Final_Short_sl = na
var int last_long_sl = na, var int last_short_sl = na
// ————— Indicators
var bool JMA_longCond = na, var bool JMA_shortCond = na
var bool RF_longCond = na, var bool RF_shortCond = na
var bool ADX_longCond = na, var bool ADX_shortCond = na
var bool SAR_longCond = na, var bool SAR_shortCond = na
var bool RSI_longCond = na, var bool RSI_shortCond = na
var bool MACD_longCond = na, var bool MACD_shortCond = na
var bool VOL_longCond = na, var bool VOL_shortCond = na
var bool JMA_XlongCond = na, var bool JMA_XshortCond = na
var bool RF_XlongCond = na, var bool RF_XshortCond = na
var bool ADX_XlongCond = na, var bool ADX_XshortCond = na
var bool SAR_XlongCond = na, var bool SAR_XshortCond = na
var int CondIni_long_BB = 0, var int CondIni_short_BB = 0
var bool Final_long_BB = na, var bool Final_short_BB = na
var int last_long_BB = na, var int last_short_BB = na
// ————— Average Price
var float sum_long = 0.0, var float sum_short = 0.0
var float Position_Price = 0.0
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Jurik Moving Average
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— JMA calculation
JMA(_JMA_length, _phase, _power, _src) =>
phaseRatio = _phase < -100 ? 0.5 : _phase > 100 ? 2.5 : _phase / 100 + 1.5
beta = 0.45 * (_JMA_length - 1) / (0.45 * (_JMA_length - 1) + 2)
alpha = pow(beta, _power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * _src + alpha * nz(e0[1])
e1 = 0.0
e1 := (_src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * pow(1 - alpha, 2) + pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
// ————— Defining JMA trend
JMA_Rising = JMA(JMA_length, phase, power, src) > JMA(JMA_length, phase, power, src)[1]
JMA_Falling = JMA(JMA_length, phase, power, src) < JMA(JMA_length, phase, power, src)[1]
// ————— JMA Plotting
JMA_color = JMA_Rising ? color.lime : JMA_Falling ? #e91e63 : color.orange
plot(Act_JMA ? JMA(JMA_length, phase, power, src) : na, color=JMA_color, linewidth = 2, title= "JMA")
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Range Filter
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Range Filter calculation
Range_filter(_src, _per, _mult) =>
float _upward = 0.0
float _downward = 0.0
wper = (_per*2) - 1
avrng = ema(abs(_src - _src[1]), _per)
_smoothrng = ema(avrng, wper) * _mult
_filt = _src
_filt := _src > nz(_filt[1]) ? ((_src-_smoothrng) < nz(_filt[1]) ? nz(_filt[1]) : (_src-_smoothrng)) : ((_src+_smoothrng) > nz(_filt[1]) ? nz(_filt[1]) : (_src+_smoothrng))
_upward := _filt > _filt[1] ? nz(_upward[1]) + 1 : _filt < _filt[1] ? 0 : nz(_upward[1])
_downward := _filt < _filt[1] ? nz(_downward[1]) + 1 : _filt > _filt[1] ? 0 : nz(_downward[1])
[_smoothrng,_filt,_upward,_downward]
// ————— Defining variables for include in future conditions
[smoothrng, filt, upward, downward] = Range_filter(src, per, mult)
// ————— Defining high and low bands
hband = filt + smoothrng
lband = filt - smoothrng
// ————— Range Filter Plotting
filtcolor = upward > 0 ? color.lime : downward > 0 ? color.red : color.orange
filtplot = plot(Act_RF ? filt : na, color = filtcolor, linewidth = 1, title = "RF")
hbandplot = plot(Act_RF ? hband : na, color = filtcolor, transp = 50, title = "RF High Target")
lbandplot = plot(Act_RF ? lband : na, color = filtcolor, transp = 50, title = "RF Low Target")
fill(hbandplot, lbandplot, color = filtcolor, title = "RF Target Range")
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— ADX
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Classic ADX calculating
calcADX(_len) =>
up = change(high)
down = -change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = rma(tr, _len)
_plus = fixnan(100 * rma(plusDM, _len) / truerange)
_minus = fixnan(100 * rma(minusDM, _len) / truerange)
sum = _plus + _minus
_adx = 100 * rma(abs(_plus - _minus) / (sum == 0 ? 1 : sum), _len)
[_plus,_minus,_adx]
// ————— Masanakamura ADX calculating
calcADX_Masanakamura(_len) =>
SmoothedTrueRange = 0.0
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementMinus = 0.0
TrueRange = max(max(high - low, abs(high - nz(close[1]))), abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? max(nz(low[1]) - low, 0) : 0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1]) /_len) + TrueRange
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1]) / _len) + DirectionalMovementPlus
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1]) / _len) + DirectionalMovementMinus
DIP = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIM = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = abs(DIP-DIM) / (DIP+DIM)*100
adx = sma(DX, _len)
[DIP,DIM,adx]
// ————— Defining variables for include in future conditions
[DIPlusC,DIMinusC,ADXC] = calcADX(ADX_len)
[DIPlusM,DIMinusM,ADXM] = calcADX_Masanakamura(ADX_len)
DIPlus = ADX_options == "CLASSIC" ? DIPlusC : DIPlusM
DIMinus = ADX_options == "CLASSIC" ? DIMinusC : DIMinusM
ADX = ADX_options == "CLASSIC" ? ADXC : ADXM
// ————— Plotting ADX bar colors
ADX_color = DIPlus > DIMinus and ADX > th ? color.green : DIPlus < DIMinus and ADX > th ? color.red : color.orange
barcolor(color = Act_ADX ? ADX_color : na, title = "ADX")
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— SAR
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— SAR calculation from TV
SAR = sar(Sst, Sinc, Smax)
// ————— SAR Plotting
plot(Act_SAR ? SAR : na, color = ADX_color, style = plot.style_circles, title = "SAR")
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— RSI with Volume
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— RSI with volume calculation
WiMA(_src, W_length) =>
var float MA_s = 0.0
MA_s :=(_src + nz(MA_s[1] * (W_length-1)))/W_length
MA_s
RSI_Volume(fv, _length) =>
up = iff(fv > fv[1], abs(fv - fv[1]) * volume, 0)
dn = iff(fv < fv[1], abs(fv - fv[1]) * volume, 0)
upt = WiMA(up,_length)
dnt = WiMA(dn,_length)
100 * (upt / (upt + dnt))
// ————— Defining variable for include in conditions
RSI_V = RSI_Volume(src, RSI_len)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— MACD
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— MAC-Z calculation
calc_zvwap(pds) =>
mean = sum(volume * close, pds) / sum(volume, pds)
vwapsd = sqrt(sma(pow(close - mean, 2), pds))
(close - mean ) / vwapsd
zscore = calc_zvwap(lengthz)
fastMA = sma(src, fastLength)
slowMA = sma(src, slowLength)
macd = fastMA - slowMA
macz = zscore + macd / stdev(src, lengthStdev)
signal = sma(macz, signalLength)
histmacz = macz - signal
// ————— MACD calculation
[_,_,histmacd] = macd(src, fastLength, slowLength, signalLength)
hist = MACD_options == "MACD" ? histmacd : histmacz
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Strategy
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— All indicators with long conditions and enable/disable option
JMA_longCond := (Act_JMA ? (JMA_Rising) : VOL_longCond)
RF_longCond := (Act_RF ? (high > hband and upward > 0) : JMA_longCond)
ADX_longCond := (Act_ADX ? (DIPlus > DIMinus and ADX > th) : RF_longCond)
SAR_longCond := (Act_SAR ? (SAR < close) : ADX_longCond)
RSI_longCond := (Act_RSI ? (RSI_V > RSI_obos) : SAR_longCond)
MACD_longCond := (Act_MACD ? (hist > 0) : RSI_longCond)
VOL_longCond := (Act_Vol ? (volume > sma(volume,sma_length) * volume_f) : MACD_longCond)
// ————— All indicators with short conditions and enable/disable option
JMA_shortCond := (Act_JMA ? (JMA_Falling) : VOL_shortCond)
RF_shortCond := (Act_RF ? (low < lband and downward > 0) : JMA_shortCond)
ADX_shortCond := (Act_ADX ? (DIPlus < DIMinus and ADX > th) : RF_shortCond)
SAR_shortCond := (Act_SAR ? (SAR > close) : ADX_shortCond)
RSI_shortCond := (Act_RSI ? (RSI_V < RSI_obos) : SAR_shortCond)
MACD_shortCond := (Act_MACD ? (hist < 0) : RSI_shortCond)
VOL_shortCond := (Act_Vol ? (volume > sma(volume,sma_length) * volume_f) : MACD_shortCond)
// ————— Defining long/short condition from indicators + volume
longCond := JMA_longCond and RF_longCond and ADX_longCond and SAR_longCond and RSI_longCond and MACD_longCond and VOL_longCond
shortCond := JMA_shortCond and RF_shortCond and ADX_shortCond and SAR_shortCond and RSI_shortCond and MACD_shortCond and VOL_shortCond
// ————— Avoiding confirmed long/short simultaneity
CondIni_long := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_long[1])
CondIni_short := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_short[1])
// ————— Confirmed long/short conditions
longCondition = (longCond[1] and nz(CondIni_long[1]) == -1)
shortCondition = (shortCond[1] and nz(CondIni_short[1]) == 1)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Position Price
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Last opened long/short price on unconfirmed/confirmed conditions
last_open_longCondition := longCondition or Final_long_BB[1] ? close[1] : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition or Final_short_BB[1] ? close[1] : nz(last_open_shortCondition[1])
// ————— Check if your last position was a confirmed long or a short
last_longCondition := longCondition or Final_long_BB[1] ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition or Final_short_BB[1] ? time : nz(last_shortCondition[1])
in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition
// ————— Check if your last position was a confirmed final long or short without BB
last_Final_longCondition := longCondition ? time : nz(last_Final_longCondition[1])
last_Final_shortCondition := shortCondition ? time : nz(last_Final_shortCondition[1])
// ————— Counting long & short iterations
nLongs := nz(nLongs[1])
nShorts := nz(nShorts[1])
// ————— Longs Counter
if longCondition or Final_long_BB
nLongs := nLongs + 1
nShorts := 0
sum_long := nz(last_open_longCondition) + nz(sum_long[1])
sum_short := 0.0
// ————— Shorts Counter
if shortCondition or Final_short_BB
nLongs := 0
nShorts := nShorts + 1
sum_short := nz(last_open_shortCondition) + nz(sum_short[1])
sum_long := 0.0
// ————— Calculating and Plotting the price average
Position_Price := nz(Position_Price[1])
Position_Price := longCondition or Final_long_BB ? sum_long/nLongs : shortCondition or Final_short_BB ? sum_short/nShorts : na
plot((nLongs > 1) or (nShorts > 1) ? Position_Price : na, title = "Average Price", color = in_longCondition ? color.aqua : color.orange, linewidth = 2, style = plot.style_cross)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Take Profit
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Take Profit divided by n entries
tp_long = (Act_divide and (nLongs > 1) ? tp_long0 / nLongs : tp_long0) / 100
tp_short = (Act_divide and (nShorts > 1) ? tp_short0 / nShorts : tp_short0) / 100
// ————— First TP Conditions
long_tp := high > (fixnan(Position_Price) * (1 + tp_long)) and in_longCondition
short_tp := low < (fixnan(Position_Price) * (1 - tp_short)) and in_shortCondition
// ————— Get the time of the last tp close
last_long_tp := long_tp ? time : nz(last_long_tp[1])
last_short_tp := short_tp ? time : nz(last_short_tp[1])
// ————— Final Take profit condition (never after the stop loss)
Final_Long_tp := (long_tp and last_longCondition > nz(last_long_tp[1]) and last_longCondition > nz(last_long_sl[1]))
Final_Short_tp := (short_tp and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1]))
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Stop Loss
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Stop Loss ATR calculation
ATR_SL_Long = low - atr(atrPeriod) * multiplierPeriod
ATR_SL_Short = high + atr(atrPeriod) * multiplierPeriod
longStopPrev = nz(ATR_SL_Long[1], ATR_SL_Long)
shortStopPrev = nz(ATR_SL_Short[1], ATR_SL_Short)
ATR_SL_Long := close[1] > longStopPrev ? max(ATR_SL_Long, longStopPrev) : ATR_SL_Long
ATR_SL_Short := close[1] < shortStopPrev ? min(ATR_SL_Short, shortStopPrev) : ATR_SL_Short
// ————— Calculating Sl according Risk and Initial Capital
sl = in_longCondition ?
min(sl0, (((Risk / (100 / (strategy.equity / close)))*100) / (quanTity * max(1, last_dynamic_Leverage_long) * max(1, nLongs)))) :
min(sl0, (((Risk / (100 / (strategy.equity / close)))*100) / (quanTity * max(1, last_dynamic_Leverage_short) * max(1, nShorts))))
// ————— Stop Loss long conditions
Normal_long_sl = Act_Conf_SL ? ((SL_options == "NORMAL") ? ((Act_sl and in_longCondition and close <= ((1 - (sl / 100)) * (fixnan(Position_Price))))) : na) :
((SL_options == "NORMAL") ? ((Act_sl and in_longCondition and low <= ((1 - (sl / 100)) * (fixnan(Position_Price))))) : na)
ATR_long_sl = Act_Conf_SL ? ((SL_options == "ATR") ? ((Act_sl and in_longCondition and close <= (ATR_SL_Long))) : na) :
((SL_options == "ATR") ? ((Act_sl and in_longCondition and low <= (ATR_SL_Long))) : na)
Both_long_sl = Act_Conf_SL ? ((SL_options == "BOTH") ? ((Act_sl and in_longCondition and close <= ((1 - (sl / 100)) * (fixnan(Position_Price)))) or
((Act_sl and in_longCondition and close <= (ATR_SL_Long)))) : na) :
((SL_options == "BOTH") ? ((Act_sl and in_longCondition and low <= ((1 - (sl / 100)) * (fixnan(Position_Price)))) or
((Act_sl and in_longCondition and low <= (ATR_SL_Long)))) : na)
// ————— Stop Loss short conditions
Normal_short_sl = Act_Conf_SL ? ((SL_options == "NORMAL") ? ((Act_sl and in_shortCondition and close >= ((1 + (sl / 100)) * (fixnan(Position_Price))))) : na) :
((SL_options == "NORMAL") ? ((Act_sl and in_shortCondition and high >= ((1 + (sl / 100)) * (fixnan(Position_Price))))) : na)
ATR_short_sl = Act_Conf_SL ? ((SL_options == "ATR") ? ((Act_sl and in_shortCondition and close >= (ATR_SL_Short))) : na) :
((SL_options == "ATR") ? ((Act_sl and in_shortCondition and high >= (ATR_SL_Short))) : na)
Both_short_sl = Act_Conf_SL ? ((SL_options == "BOTH") ? ((Act_sl and in_shortCondition and close >= ((1 + (sl/100)) * (fixnan(Position_Price)))) or
((Act_sl and in_shortCondition and close >= (ATR_SL_Short)))) : na) :
((SL_options == "BOTH") ? ((Act_sl and in_shortCondition and high >= ((1 + (sl/100)) * (fixnan(Position_Price)))) or
((Act_sl and in_shortCondition and high >= (ATR_SL_Short)))) : na)
// ————— Get the time of the last sl close
last_long_sl := Normal_long_sl or ATR_long_sl or Both_long_sl ? time : nz(last_long_sl[1])
last_short_sl := Normal_short_sl or ATR_short_sl or Both_short_sl ? time : nz(last_short_sl[1])
// ————— Final Stop Loss condition
Final_Long_sl := (Normal_long_sl or ATR_long_sl or Both_long_sl) and last_longCondition > nz(last_long_sl[1]) and last_longCondition > nz(last_long_tp[1]) and not Final_Long_tp
Final_Short_sl := (Normal_short_sl or ATR_short_sl or Both_short_sl) and last_shortCondition > nz(last_short_sl[1]) and last_shortCondition > nz(last_short_tp[1]) and not Final_Short_tp
//Plottin ATR SL
plot(Act_sl and (SL_options != "NORMAL") ? in_longCondition ? ATR_SL_Long[1] : ATR_SL_Short[1] : na, title = "ATR SL", color = color.purple)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Bollinger Bands Re-entry
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
BB_basis = sma(src, BB_length)
BB_dev = BB_mult * stdev(src, BB_length)
BB_upper = BB_basis + BB_dev
BB_lower = BB_basis - BB_dev
u_BB = plot(Act_BB ? BB_upper : na, title = "Upper Bollinger Band", color = #009688, linewidth = 2)
l_BB = plot(Act_BB ? BB_lower : na, title = "Lower Bollinger Band", color = #f06292, linewidth = 2)
fill(u_BB, l_BB, title = "Bollinger Band Background", color = in_longCondition ? #009688 : #f06292, transp = 95)
// ————— Initial Bollinger Bands conditions
BB_long = Act_BB and in_longCondition and not (DIPlus < DIMinus and ADX > th) and (close <= BB_lower) and (close < last_open_longCondition * (1 - (bbBetterPrice / 100)))
BB_short = Act_BB and in_shortCondition and not (DIPlus > DIMinus and ADX > th) and (close >= BB_upper) and (close > last_open_shortCondition * (1 + (bbBetterPrice / 100)))
// ————— Get the time of the last BB close
last_long_BB := BB_long ? time : nz(last_long_BB[1])
last_short_BB := BB_short ? time : nz(last_short_BB[1])
// ————— Final Bollinger Bands condition for long
Final_long_BB := BB_long and last_Final_longCondition > nz(last_long_BB[1]) and
last_longCondition > nz(last_long_tp[1]) and
last_longCondition > nz(last_long_sl[1]) and not Final_Long_sl
// ————— Final Bollinger Bands condition for short
Final_short_BB := BB_short and last_Final_shortCondition > nz(last_short_BB[1]) and
last_shortCondition > nz(last_short_tp[1]) and
last_shortCondition > nz(last_short_sl[1]) and not Final_Short_sl
// ————— Final confirmed Re-entries on long & short conditions
Final_Long_BB = Final_long_BB[1]
Final_Short_BB = Final_short_BB[1]
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Signal Plotting
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— TP Long Levels
tplLevel = (in_longCondition and
(last_longCondition > nz(last_long_tp[1])) and
(last_longCondition > nz(last_long_sl[1])) and not Final_Long_sl[1]) ?
(nLongs > 1) ?
(fixnan(Position_Price) * (1 + tp_long)) : (last_open_longCondition * (1 + tp_long)) : na
plot(tplLevel, title = "Long TP Level", style = plot.style_circles, color = color.lime, linewidth = 2)
tpsLevel = (in_shortCondition and
(last_shortCondition > nz(last_short_tp[1])) and
(last_shortCondition > nz(last_short_sl[1])) and not Final_Short_sl[1]) ?
(nShorts > 1) ?
(fixnan(Position_Price) * (1 - tp_short)) : (last_open_shortCondition * (1 - tp_short)) : na
plot(tpsLevel, title = "Short TP Level", style = plot.style_circles, color = color.red, linewidth = 2)
// ————— Weekend
W_color = (dayofweek == dayofweek.sunday or dayofweek == dayofweek.saturday) ? color.white : na
bgcolor(W_color, title = "Weekend", transp = 95)
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Re-entry Conditions
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Re-entry on long after tp, sl or Xlong
if Final_Long_tp or Final_Long_sl
CondIni_long := -1
sum_long := 0.0
nLongs := na
// ————— Re-entry on short after tp, sl or Xshort
if Final_Short_tp or Final_Short_sl
CondIni_short := 1
sum_short := 0.0
nShorts := na
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— Backtest
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ————— Defining new final unconfirmed long conditions
_longCondition = (longCond and not in_longCondition) or
(longCond and Final_Long_tp) or
(longCond and Final_Long_sl) or
(longCond and not longCondition and (last_long_tp >= nz(last_longCondition))) or
(longCond and not longCondition and (last_long_sl >= nz(last_longCondition)))
// ————— Defining new final unconfirmed short conditions
_shortCondition = (shortCond and not in_shortCondition) or
(shortCond and Final_Short_tp) or
(shortCond and Final_Short_sl) or
(shortCond and not shortCondition and (last_short_tp >= nz(last_shortCondition))) or
(shortCond and not shortCondition and (last_short_sl >= nz(last_shortCondition)))
// ————— Test period declaration
testPeriod = time >= timenow - backtest_time
// ————— Volume Factor for determine quantities
Volume_Factor_Leverage = min(Max_Lev, max(1, round(volume / sma(volume, sma_length))))
last_dynamic_Leverage_long := _longCondition ? Volume_Factor_Leverage : nz(last_dynamic_Leverage_long[1])
last_dynamic_Leverage_short := _shortCondition ? Volume_Factor_Leverage : nz(last_dynamic_Leverage_short[1])
// ————— Entering long positions
if (_longCondition)
strategy.entry("long", strategy.long, qty = Volume_Factor_Leverage * quanTity, when = Act_BT and testPeriod)
if (Final_long_BB)
strategy.entry("long", strategy.long, qty = last_dynamic_Leverage_long * quanTity, when = Act_BT and testPeriod)
// ————— Entering short positions
if (_shortCondition)
strategy.entry("short", strategy.short, qty = Volume_Factor_Leverage * quanTity, when = Act_BT and testPeriod)
if (Final_short_BB)
strategy.entry("short", strategy.short, qty = last_dynamic_Leverage_short * quanTity, when = Act_BT and testPeriod)
// ————— Closing positions with first long TP
strategy.exit("Tpl", "long",
profit = (abs((last_open_longCondition * (1 + tp_long)) - last_open_longCondition) / syminfo.mintick),
limit = nLongs >= 1 ? strategy.position_avg_price * (1 + tp_long) : na,
loss = Act_Conf_SL == false ?
(iff(Act_sl and (SL_options == "NORMAL"), (abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "ATR"), (abs(ATR_SL_Long-last_open_longCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "BOTH") and ((abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick) <
(abs(ATR_SL_Long-last_open_longCondition)/syminfo.mintick)), (abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "BOTH") and ((abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick) >
(abs(ATR_SL_Long-last_open_longCondition)/syminfo.mintick)), (abs(ATR_SL_Long-last_open_longCondition)/syminfo.mintick), na))))) : na,
stop = Act_Conf_SL == false and nLongs >= 1 ?
(iff(Act_sl and (SL_options == "NORMAL"), ((1-(sl/100))*strategy.position_avg_price),
iff(Act_sl and (SL_options == "ATR"), ATR_SL_Long,
iff(Act_sl and (SL_options == "BOTH") and (((1-(sl/100))*strategy.position_avg_price) > ATR_SL_Long), ((1-(sl/100))*strategy.position_avg_price),
iff(Act_sl and (SL_options == "BOTH") and (((1-(sl/100))*strategy.position_avg_price) < ATR_SL_Long), ATR_SL_Long, na))))) : na)
// Canceling long exit orders to avoid simultaneity with re-entry
strategy.cancel("Tpl", when = Final_long_BB)
// ————— Closing positions with first short TP
strategy.exit("Tps", "short",
profit = (abs((last_open_shortCondition * (1 - tp_short)) - last_open_shortCondition) / syminfo.mintick),
limit = nShorts >= 1 ? strategy.position_avg_price*(1-(tp_short)) : na,
loss = Act_Conf_SL == false ?
(iff(Act_sl and (SL_options == "NORMAL"), (abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "ATR"), (abs(ATR_SL_Short-last_open_shortCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "BOTH") and ((abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick) <
(abs(ATR_SL_Short-last_open_shortCondition)/syminfo.mintick)), (abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick),
iff(Act_sl and (SL_options == "BOTH") and ((abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick) >
(abs(ATR_SL_Short-last_open_shortCondition)/syminfo.mintick)), (abs(ATR_SL_Short-last_open_shortCondition)/syminfo.mintick), na))))) : na,
stop = Act_Conf_SL == false and nShorts >= 1 ?
(iff(Act_sl and (SL_options == "NORMAL"), ((1+(sl/100))*strategy.position_avg_price),
iff(Act_sl and (SL_options == "ATR"), ATR_SL_Short,
iff(Act_sl and (SL_options == "BOTH") and (((1+(sl/100))*strategy.position_avg_price) < ATR_SL_Short), ((1+(sl/100))*strategy.position_avg_price),
iff(Act_sl and (SL_options == "BOTH") and (((1+(sl/100))*strategy.position_avg_price) > ATR_SL_Short), ATR_SL_Short, na))))) : na)
// Canceling short exit orders to avoid simultaneity with re-entry
strategy.cancel("Tps", when = Final_short_BB)
// ————— Closing all positions with Xlong/Xshort
strategy.close_all(when = (Final_Long_sl and Act_Conf_SL) or (Final_Short_sl and Act_Conf_SL))
// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //
// ———————————————————— by Xaviz |
Crypto ZigZag RSI strategy 15min | https://www.tradingview.com/script/LhpfQMtP-Crypto-ZigZag-RSI-strategy-15min/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 1,201 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("Crypto ZigZag RSI strategy 15min",overlay=true)
length =input(5, title="RSI Length")
overSold = input(25)
overBought= input(75)
p =close
vrsi = rsi(p, length)
var bool long = na
var bool short = na
long :=crossover(vrsi,overSold)
short := crossunder(vrsi,overBought)
var float last_open_long = na
var float last_open_short = na
last_open_long := long ? close : nz(last_open_long[1])
last_open_short := short ? close : nz(last_open_short[1])
entry_value =last_open_long
entry_value1=last_open_short
//
ZZPercent = input(1, title="Minimum % Change", type=input.float)
r1Level=entry_value
s1Level=entry_value1
trend = 0
trend := na(trend[1]) ? 1 : trend[1]
LL = 0.0
LL := na(LL[1]) ? s1Level : LL[1]
HH = 0.0
HH := na(HH[1]) ?r1Level : HH[1]
Pi = ZZPercent * 0.01
zigzag = float(na)
if trend > 0
if r1Level >= HH
HH := r1Level
HH
else
if s1Level < HH * (1 - Pi)
zigzag :=r1Level[1]
trend := -1
LL := s1Level
LL
else
if s1Level <= LL
LL := s1Level
LL
else
if r1Level > LL * (1 + Pi)
zigzag := s1Level[1]
trend := 1
HH := s1Level
HH
shortc=crossunder(trend,0)
longc=crossover(trend,0)
longa =input(true)
shorta=input(false)
if(longa)
strategy.entry("long",1,when=longc)
strategy.close("long",when=shortc)
if(shorta)
strategy.entry("short",0,when=shortc)
strategy.close("long",when=longc)
|
Buy the Dips (by Coinrule) | https://www.tradingview.com/script/GpQLZz6K-Buy-the-Dips-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 268 | strategy | 3 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=3
strategy(shorttitle='Buy the Dips',title='Buy the Dips (by Coinrule)', overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month")
fromDay = input(defval = 10, title = "From Day")
fromYear = input(defval = 2020, title = "From Year")
thruMonth = input(defval = 1, title = "Thru Month")
thruDay = input(defval = 1, title = "Thru Day")
thruYear = input(defval = 2112, title = "Thru Year")
showDate = input(defval = true, title = "Show Date Range")
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
inp_lkb = input(1, title='Lookback Period')
perc_change(lkb) =>
overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100
// Call the function
overall = perc_change(inp_lkb)
//Entry
dip= -(input(2))
strategy.entry(id="long", long = true, when = overall< dip and window())
//Exit
Stop_loss= ((input (2))/100)
Take_profit= ((input (2))/100)
longStopPrice = strategy.position_avg_price * (1 - Stop_loss)
longTakeProfit = strategy.position_avg_price * (1 + Take_profit)
strategy.close("long", when = close < longStopPrice or close > longTakeProfit and window())
|
SuperTREX strategy | https://www.tradingview.com/script/K3U9opwQ-SuperTREX-strategy/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 1,552 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni
//@version=4
strategy(title = "SuperTREX strategy", overlay = true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 25, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.075)
strat_dir_input = input(title="Strategy Direction", defval="long", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
strategy.risk.allow_entry_in(strat_dir_value)
length = input( 14 )
overSold = input( 35 )
overBought = input( 70 )
HTF = input("W", type=input.resolution)
ti = change( time(HTF) ) != 0
p = fixnan( ti ? close : na )
vrsi = rsi(p, length)
price = close
var bool long = na
var bool short = na
long :=crossover(vrsi,overSold)
short := crossunder(vrsi,overBought)
var float last_open_long = na
var float last_open_short = na
last_open_long := long ? close : nz(last_open_long[1])
last_open_short := short ? close : nz(last_open_short[1])
entry_value =last_open_long
entry_value1=last_open_short
xy=(entry_value+entry_value)/2
// INPUTS //
st_mult = input(4, title = 'SuperTrend Multiplier', minval = 0, maxval = 100, step = 0.01)
st_period = input(10, title = 'SuperTrend Period', minval = 1)
// CALCULATIONS //
up_lev =xy - (st_mult * atr(st_period))
dn_lev =xy + (st_mult * atr(st_period))
up_trend = 0.0
up_trend := entry_value[1] > up_trend[1] ? max(up_lev, up_trend[1]) : up_lev
down_trend = 0.0
down_trend := entry_value1[1] < down_trend[1] ? min(dn_lev, down_trend[1]) : dn_lev
// Calculate trend var
trend = 0
trend := close > down_trend[1] ? 1: close < up_trend[1] ? -1 : nz(trend[1], 1)
// Calculate SuperTrend Line
st_line = trend ==1 ? up_trend : down_trend
plot(xy,color = trend == 1 ? color.green : color.red)
buy=crossover( close, st_line)
sell1=crossunder(close, st_line)
buy1=buy
//
sell=sell1
// STRATEGY
plotshape(buy , title="buy", text="Buy", color=color.green, style=shape.labelup, location=location.belowbar, size=size.small, textcolor=color.white, transp=0) //plot for buy icon
plotshape(sell, title="sell", text="Sell", color=color.red, style=shape.labeldown, location=location.abovebar, size=size.small, textcolor=color.white, transp=0) //plot for sell icon
// Take profit
//
l = buy
s1=sell
if l
strategy.entry("buy", strategy.long)
if s1
strategy.entry("sell", strategy.short)
per(pcnt) =>
strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
stoploss=input(title=" stop loss", defval=25, minval=0.01)
los = per(stoploss)
q1=input(title=" qty_percent1", defval=25, minval=1)
q2=input(title=" qty_percent2", defval=25, minval=1)
q3=input(title=" qty_percent3", defval=25, minval=1)
tp1=input(title=" Take profit1", defval=10, minval=0.01)
tp2=input(title=" Take profit2", defval=20, minval=0.01)
tp3=input(title=" Take profit3", defval=50, minval=0.01)
tp4=input(title=" Take profit4", defval=100, minval=0.01)
strategy.exit("x1", qty_percent = q1, profit = per(tp1), loss = los)
strategy.exit("x2", qty_percent = q2, profit = per(tp2), loss = los)
strategy.exit("x3", qty_percent = q3, profit = per(tp3), loss = los)
strategy.exit("x4", profit = per(tp4), loss = los)
|
Stepped trailing strategy example | https://www.tradingview.com/script/jjhUHcje-Stepped-trailing-strategy-example/ | adolgov | https://www.tradingview.com/u/adolgov/ | 2,159 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov
// @description
//-------------------------------------------------
// activateTrailingOnThirdStep == false (default)
// - when tp1 is reached, sl is moved to break-even
// - when tp2 is reached, sl is moved to tp1
// - when tp3 is reached - exit
//-------------------------------------------------
// activateTrailingOnThirdStep == true
// - when tp1 is reached, sl is moved to break-even
// - when tp2 is reached, sl is moved to tp1 and trailing stop is activated with tp2 amount level and tp1 offset level
//-------------------------------------------------
//@version=4
strategy("Stepped trailing strategy example", overlay=true)
// random entry condition
if (crossover(sma(close, 14), sma(close, 28)))
strategy.entry("My Long Entry Id", strategy.long)
// exit logic
percent2points(percent) =>
strategy.position_avg_price * percent / 100 / syminfo.mintick
// sl & tp in %%
sl = percent2points(input(5, title = "stop loss %%"))
tp1 = percent2points(input(5, title = "take profit 1 %%"))
tp2 = percent2points(input(10, title = "take profit 2 %%"))
tp3 = percent2points(input(15, title = "take profit 3 %%"))
activateTrailingOnThirdStep = input(false, title = "activate trailing on third stage (tp3 is amount, tp2 is offset level)")
curProfitInPts() =>
if strategy.position_size > 0
(high - strategy.position_avg_price) / syminfo.mintick
else if strategy.position_size < 0
(strategy.position_avg_price - low) / syminfo.mintick
else
0
calcStopLossPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else
na
calcProfitTrgtPrice(OffsetPts) =>
calcStopLossPrice(-OffsetPts)
getCurrentStage() =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size != 0
stage := 1
else if stage == 1 and curProfitInPts() >= tp1
stage := 2
else if stage == 2 and curProfitInPts() >= tp2
stage := 3
stage
calcTrailingAmountLevel(points) =>
var float level = na
level := calcProfitTrgtPrice(points)
if not na(level)
if strategy.position_size > 0
if not na(level[1])
level := max(level[1], level)
if not na(level)
level := max(high, level)
else if strategy.position_size < 0
if not na(level[1])
level := min(level[1], level)
if not na(level)
level := min(low, level)
calcTrailingOffsetLevel(points, offset) =>
float result = na
amountLevel = calcTrailingAmountLevel(points)
if strategy.position_size > 0
trailActiveDiff = amountLevel - calcProfitTrgtPrice(points)
if trailActiveDiff > 0
result := trailActiveDiff + calcProfitTrgtPrice(offset)
else if strategy.position_size < 0
trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel
if trailActiveDiff > 0
result := calcProfitTrgtPrice(offset) - trailActiveDiff
result
float stopLevel = na
float trailOffsetLevel = na
float profitLevel = activateTrailingOnThirdStep ? calcTrailingAmountLevel(tp3) : calcProfitTrgtPrice(tp3)
// note: calcTrailingOffsetLevel uses calcTrailingAmountLevel and last one has a state (level).
// therefor we needs calculate it on every bar for correct result.
// if we inline it the Pine compiler give us warning "The function '***' should be called on each calculation for consistency. It is recommended to extract the call from this scope."
trailOffsetLevelTmp = calcTrailingOffsetLevel(tp3, tp2)
// based on current stage set up exit
// note: we use same exit ids ("x") consciously, for MODIFY the exit's parameters
curStage = getCurrentStage()
if curStage == 1
stopLevel := calcStopLossPrice(sl)
strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")
else if curStage == 2
stopLevel := calcStopLossPrice(0)
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")
else if curStage == 3
stopLevel := calcStopLossPrice(-tp1)
if activateTrailingOnThirdStep
trailOffsetLevel := trailOffsetLevelTmp
strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = "stop tp1 or trailing tp3 with offset tp2")
else
strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")
else
strategy.cancel("x")
// this is debug plots for visulalize TP & SL levels
plot(stopLevel, style = plot.style_linebr, color = color.red)
plot(profitLevel, style = plot.style_linebr, color = color.blue)
plot(trailOffsetLevel, style = plot.style_linebr, color = color.green) |
Zignaly Tutorial | https://www.tradingview.com/script/YF0KJH7V-Zignaly-Tutorial/ | ruckard | https://www.tradingview.com/u/ruckard/ | 184 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ruckard
//@version=4
// Current version: v20201031 ( A061 )
// Tradingview Public description - BEGIN
//
// This strategy serves as a beginner's guide to connect TradingView signals to Zignaly Crypto Trading Platform.
//
// It was originally tested at BTCUSDT pair and 1D timeframe.
// The strategy is a slightly modified copy of default TradingView strategy that appears when you create a blank new strategy.
// It decides to go long when 14-period SMA crosses over 28-period SMA and goes short when 14-period SMA crosses under 28-period SMA.
//
// Before using this documentation it's recommended that you:
// [LIST]
// [*] Use default TradingView strategy script or another script and setup its associated alert manually. Just make the alert pop-up in the screen.
// [*] Create a 'Copy-Trader provider' (or Signal Provider) in Zignaly and send signals to it either thanks to your browser or with some basic programming.
// [/LIST]
// [B]SETTINGS[/B]
// [B]__ SETTINGS - Capital[/B]
// [LIST]
// [*] (CAPITAL) Capital quote invested per order in USDT units {100.0}. This setting is only used when '(ZIG) Provider type' is set to 'Signal Provider'.
// [*] (CAPITAL) Capital percentage invested per order (%) {25.0}. This setting is only used when '(ZIG) Provider type' is set to 'Copy Trader Provider'.
// [/LIST]
// [B]__ SETTINGS - Misc[/B]
// [LIST]
// [*] (ZIG) Enable Alert message {True}: Whether to enable alert message or not.
// [*] (DEBUG) Enable debug on order comments {True}: Whether to show alerts on order comments or not.
// [*] Number of decimal digits for Prices {2}.
// [*] (DECIMAL) Maximum number of decimal for contracts {3}.
// [/LIST]
// [B]__ SETTINGS - Zignaly[/B]
// [LIST]
// [*] (ZIG) Integration type {TradingView only}: [b]Hybrid[/b]: Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync. [b]TradingView only[/b]: TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.
// [*] (ZIG) Zignaly Alert Type {WebHook}: 'Email' or 'WebHook'.
// [*] (ZIG) Provider type {Copy Trader Provider}: 'Copy Trader Provider' or 'Signal Provider'. 'Copy Trader Provider' sends a percentage to manage. 'Signal Provider' sends a quote to manage.
// [*] (ZIG) Exchange: 'Binance' or 'Kucoin'.
// [*] (ZIG) Exchange Type {Spot}: 'Spot' or 'Futures'.
// [*] (ZIG) Leverage {1}. Set it to '1' when '(ZIG) Exchange Type' is set to 'Spot'.
// [/LIST]
// [B]__ SETTINGS - Strategy[/B]
// [LIST]
// [*] (STRAT) Strategy Type: 'Long and Short', 'Long Only' or 'Short Only'.
// [*] (STOPTAKE) Take Profit? {false}: Whether to enable Take Profit.
// [*] (STOPTAKE) Stop Loss? {True}: Whether to enable Stop Loss.
// [*] (TRAILING) Enable Trailing Take Profit (%) {True}: Whether to enable Trailing Take Profit.
// [*] (STOPTAKE) Take Profit % {3.0}: Take profit percentage. This setting is only used when '(STOPTAKE) Take Profit?' setting is set to true.
// [*] (STOPTAKE) Stop Loss % {2.0}: Stop loss percentage. This setting is only used when '(STOPTAKE) Stop Loss?' setting is set to true.
// [*] (TRAILING) Trailing Take Profit Trigger (%) {2.5}: Trailing Stop Trigger Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.
// [*] (TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}: Trailing Stop Distance Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.
// [*] (RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}.
// [/LIST]
// [B]DEFAULT SETTINGS[/B]
// By default this strategy has been setup with these beginner settings:
// [LIST]
// [*] '(ZIG) Integration type' : TradingView only
// [*] '(ZIG) Provider type' : 'Copy Trader Provider'
// [*] '(ZIG) Exchange' : 'Binance'
// [*] '(ZIG) Exchange Type' : 'Spot'
// [*] '(STRAT) Strategy Type' : 'Long Only'
// [*] '(ZIG) Leverage' : '1' (Or no leverage)
// [/LIST]
// but you can change those settings if needed.
// [B]FIRST STEP[/B]
// [LIST]
// [*] For both future or spot markets you should make sure to change '(ZIG) Zignaly Alert Type' to match either WebHook or Email. If you have a non paid account in TradingView as in October 2020 you would have to use Email which it's free to use.
// [/LIST]
// [B]RECOMMENDED SETTINGS[/B]
// [B]__ RECOMMENDED SETTINGS - Spot markets[/B]
// [LIST]
// [*] '(ZIG) Exchange Type' setting should be set to 'Spot'
// [*] '(STRAT) Strategy Type' setting should be set to 'Long Only'
// [*] '(ZIG) Leverage' setting should be set to '1'
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Future markets[/B]
// [LIST]
// [*] '(ZIG) Exchange Type' setting should be set to 'Futures'
// [*] '(STRAT) Strategy Type' setting should be set to 'Long and Short'
// [*] '(ZIG) Leverage' setting might be changed if desired.
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Signal Providers[/B]
// [LIST]
// [*] '(ZIG) Provider type' setting should be set to 'Signal Provider'
// [*] '(CAPITAL) Capital quote invested per order in USDT units' setting might be changed if desired.
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Copy Trader Providers[/B]
// [LIST]
// [*] '(ZIG) Provider type' setting should be set to 'Copy Trader Provider'
// [*] '(CAPITAL) Capital percentage invested per order (%)' setting might be changed if desired.
// [*] Strategy Properties setting: 'Initial Capital' might be changed if desired.
// [/LIST]
// [B]INTEGRATION TYPE EXPLANATION[/B]
// [LIST]
// [*] 'Hybrid': Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync.
// [*] 'TradingView only': TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.
// [/LIST]
// [B]HOW TO USE THIS STRATEGY[/B]
// [LIST]
// [*] Beginner: Copy and paste the strategy and change it to your needs. Turn off '(DEBUG) Enable debug on order comments' setting.
// [*] Medium: Reuse functions and inputs from this strategy into your own as if it was a library.
// [*] Advanced: Check Strategy Tester. List of trades. Copy and paste the different suggested 'alert_message' variable contents to your script and change them to your needs.
// [*] Expert: You needed a way to pass data from TradingView script to the alert. Now you know it's the 'alert_message' variable. You can find several examples in the source code using the variable. You also have seen 'ALERTS SETUP' explanation below. An additional quick look at 'Strategy Tester', 'List of Trades' and you are ready to go.
// [/LIST]
// [B] ALERTS SETUP[/B]
// This is the important piece of information that allows you to connect TradingView to Zignaly in a semi-automatic manner.
// [B] __ ALERTS SETUP - WebHook[/B]
// [LIST]
// [*] Webhook URL: https : // zignaly . com / api / signals.php?key=MYSECRETKEY
// [*] Message: { {{strategy.order.alert_message}} , "key" : "MYSECRETKEY" }
// [/LIST]
// [B] __ ALERTS SETUP - Email[/B]
// [LIST]
// [*] Setup a new Hotmail account
// [*] Add it as an 'SMS email' in TradingView Profile settings page.
// [*] Confirm your own the email address
// [*] Create a rule in your Hotmail account that 'Redirects' (not forwards) emails to 'signals @ zignaly . email' when (1): 'Subject' includes 'Alert', (2): 'Email body' contains string 'MYZIGNALYREDIRECTTRIGGER' and (3): 'From' contains 'noreply @ tradingview . com'.
// [*] In 'More Actions' check: Send Email-to-SMS
// [*] Message: ||{{strategy.order.alert_message}}||key=MYSECRETKEY||
// MYZIGNALYREDIRECTTRIGGER
// [/LIST]
// '(DEBUG) Enable debug on order comments' is turned on by default so that you can see in the Strategy Tester. List of Trades. The different orders alert_message that would have been sent to your alert. You might want to turn it off it some many letters in the screen is problem.
// [B]STRATEGY ADVICE[/B]
// [LIST]
// [*] If you turn on 'Take Profit' then turn off 'Trailing Take Profit'.
// [/LIST]
//
// [B]ZIGNALY SIDE ADVICE[/B]
// [LIST]
// [*] If you are a 'Signal Provider' make sure that 'Allow reusing the same signalId if there isn't any open position using it?' setting in the profile tab is set to true.
// [*] You can find your 'MYSECRETKEY' in your 'Copy Trader/Signal' provider Edit tab at 'Signal URL'.
// [/LIST]
//
// [B]ADDITIONAL ZIGNALY DOCUMENTATION[/B]
// This beginner's guide is quite basic and meant to be an introduction. Please read additional documentation to learn what you actually can do with Zignaly.
// [LIST]
// [*] docs . zignaly . com / signals / how-to -- How to send signals to Zignaly
// [*] 3 Ways to send signals to Zignaly
// [*] SIGNALS
// [/LIST]
//
// [B]FINAL REMARKS[/B]
// [LIST]
// [*] This strategy tries to match the Pine Script Coding Conventions as best as possible.
// [*] You can check my 'Ruckard TradingLatino' strategy for a more complex strategy that it's also integrated with Zignaly. Unfortunatley it does not use Pine Script Coding Conventions as much.
// [/LIST]
// Tradingview Public description - END
strategy("Zignaly Tutorial A061", shorttitle="A061ZigTuto", overlay=true, max_bars_back=5000, calc_on_order_fills=false, calc_on_every_tick=false, pyramiding=0, initial_capital=1000, slippage=1, commission_type=strategy.commission.percent, commission_value=0.1)
// INPUTS - BEGIN
// Strategy - Inputs
i_enableZignalyAlert = input(true, "(ZIG) Enable Alert message {True}")
_ZIGHYBRIDINTEGRATION_ = "Hybrid" , _ZIGTVONLYINTEGRATION_ = "TradingView only"
i_zignalyIntegrationType = input(_ZIGTVONLYINTEGRATION_, "(ZIG) Integration type", options=[_ZIGTVONLYINTEGRATION_, _ZIGHYBRIDINTEGRATION_])
_ZIGSIGNALPROVIDER_ = "Signal Provider" , _ZIGCOPYTRADERPROVIDER_ = "Copy Trader Provider"
i_zignalyProviderType = input(_ZIGCOPYTRADERPROVIDER_, "(ZIG) Provider type", options=[_ZIGSIGNALPROVIDER_, _ZIGCOPYTRADERPROVIDER_])
L_S = "Long and Short" , _L_ = "Long Only" , _S_ = "Short Only"
i_strategyType = input(_L_, "(STRAT) Strategy Type", options=[L_S, _L_, _S_])
// Order comments based debug
i_enableOrderCommentDebug = input(true, title="(DEBUG) Enable debug on order comments {True}", type=input.bool)
i_enableTakeProfit = input(false, "(STOPTAKE) Take Profit? {false}")
i_enableStopLoss = input(true, "(STOPTAKE) Stop Loss? {True}")
i_enableTrailingTakeProfit = input(true, title="(TRAILING) Enable Trailing Take Profit (%) {True}", type=input.bool)
i_TakeProfit = input(1.1, title="(STOPTAKE) Take Profit % {3.0}") / 100
i_StopLoss = input(2.0, title="(STOPTAKE) Stop Loss % {2.0}", minval=0.01 ) / 100
// Trailing Take Profit - Inputs
i_trailingTakeProfitPercentageTrigger = input(1.2, "(TRAILING) Trailing Take Profit Trigger (%) {2.5}",minval=0,step=0.01,type=input.float) * 0.01
i_trailingTakeProfitPercentageOffset = input(25.0, "(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01
// Zignaly - Email (zignalye)
_ZIGNALYE_="Email", _ZIGNALYW_="WebHook"
i_zignalyAlertType = input(_ZIGNALYW_, "(ZIG) Zignaly Alert Type {WebHook}", options=[_ZIGNALYW_, _ZIGNALYE_])
_ZIGEXBINANCE_ = "Binance" , _ZIGEXKUCOIN_ = "Kucoin"
i_zignalyExchange = input(_ZIGEXBINANCE_, "(ZIG) Exchange", options=[_ZIGEXBINANCE_, _ZIGEXKUCOIN_])
_ZIGEXTYPESPOT_ = "spot" , _ZIGEXFUTURES_ = "futures"
i_zignalyExchangeType = input(_ZIGEXTYPESPOT_, "(ZIG) Exchange Type {Spot}", options=[_ZIGEXTYPESPOT_, _ZIGEXFUTURES_])
i_zignalyLeverage = input(1, "(ZIG) Leverage {1}",minval=1,step=1,maxval=125,type=input.integer)
var i_zignalyLeverage_str = tostring(i_zignalyLeverage) // It needs to run only once
i_priceDecimalDigits = input(2, "Number of decimal digits for Prices {2}", minval=0, maxval=10, step=1)
// Decimal - Inputs
i_contractMaximumDecimalNumber = input(3, title="(DECIMAL) Maximum number of decimal for contracts {3}",minval=0)
i_tooRecentMinutesNumber = input(6, "(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}", minval=1, maxval=100, step=1)
i_CapitalQuote = input(100.0, title="(CAPITAL) Capital quote invested per order in USDT units {100.0}")
i_CapitalPercentage = input(25.0, title="(CAPITAL) Capital percentage invested per order (%) {25.0}",minval=0,step=0.01,type=input.float) * 0.01
// INPUTS - END
// Strategy - INIT - BEGIN
// Dynamic Trailing Take Profit - Variables
var int buyOrderOpenBarIndex = na
var int sellOrderOpenBarIndex = na
var float buyStopLoss = na
var float sellStopLoss = na
var float newBuyStopLoss = na
var float newSellStopLoss = na
// Handle to avoid two long and short orders being too next to each other
var bool _oldInsideABuyOrder = false
var bool oldInsideASellOrder = false
var bool insideABuyOrder = false
var bool insideASellOrder = false
_oldInsideABuyOrder := insideABuyOrder
oldInsideASellOrder := insideASellOrder
var int lastOrderOpenBarTime = na
// Handle recalculate after Stop Loss / Take Profit order
if (strategy.position_size == 0.0)
insideABuyOrder := false
insideASellOrder := false
else
lastOrderOpenBarTime := time_close
// Zignaly
exchangeTickerID = syminfo.basecurrency + syminfo.currency
var string zignalySeparator = ","
var string zignalyQuote = "\""
var string zignalyEquals = "="
if ( i_zignalyAlertType == _ZIGNALYE_)
zignalySeparator := "||"
zignalyQuote := ""
zignalyEquals := "="
else
zignalySeparator := ","
zignalyQuote := "\""
zignalyEquals := ":"
zignalyCommonAlertMessage = zignalyQuote + "exchange" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyExchange + zignalyQuote + zignalySeparator + zignalyQuote + "exchangeAccountType" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyExchangeType + zignalyQuote + zignalySeparator + zignalyQuote + "pair" + zignalyQuote + zignalyEquals + zignalyQuote + "" + exchangeTickerID + zignalyQuote + zignalySeparator + zignalyQuote + "leverage" + zignalyQuote + zignalyEquals + zignalyQuote + i_zignalyLeverage_str + zignalyQuote
var string tmpOrderComment = na
var string tmpOrderAlertMessage = na
var int i_tooRecentMinutesNumber_ms = i_tooRecentMinutesNumber * 60 * 1000 // Convert minutes into milliseconds only once
// Strategy - INIT - END
// FUNCTIONS - BEGIN
// Decimals - Functions
f_getContractMultiplier(_contractMaximumDecimalNumber) =>
_contractMultiplier = 1
if (_contractMaximumDecimalNumber == 0)
_contractMultiplier // Return 1
else
for _counter = 1 to _contractMaximumDecimalNumber
_contractMultiplier:= _contractMultiplier * 10
_contractMultiplier
f_priceDecimalDigitsZeroString () =>
// Dependencies: i_priceDecimalDigits (initialized in inputs).
_zeroString = ""
if not (i_priceDecimalDigits == 0)
for _digit = 1 to i_priceDecimalDigits
_zeroString := _zeroString + "0"
_zeroString
// Zignalye - Functions - BEGIN
f_getZignalyLongAlertMessage(_entryQuantityContractsUSDT, _currentCapital) =>
// Dependencies: i_enableStopLoss (initialized in inputs).
// Dependencies: i_enableTakeProfit (initialized in inputs).
// Dependencies: i_TakeProfit (initialized in inputs).
// Dependencies: i_enableTrailingTakeProfit (initialized in inputs).
// Dependencies: i_trailingTakeProfitPercentageOffset (initialized in inputs).
// Dependencies: i_trailingTakeProfitPercentageTrigger (initialized in inputs).
// Dependencies: i_zignalyIntegrationType (initialized in inputs).
// Function Dependencies: f_priceDecimalDigitsZeroString()
var string _zignaleStopLossCombo = ""
var string _zignaleTakeProfitCombo = ""
var string _zignaleTrailingTakeProfitCombo = ""
_zignalyLongCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "entry" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "long" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "LONG-" + exchangeTickerID + zignalyQuote
float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT
_entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString())
float _floatCurrentCapital = _currentCapital
float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00
_entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString())
// This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified)
float _constantBuyStopLoss = na
if (_oldInsideABuyOrder and insideABuyOrder)
_constantBuyStopLoss := buyStopLoss
else
_constantBuyStopLoss := newBuyStopLoss
if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((nz(_constantBuyStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleStopLossCombo := ""
if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleTakeProfitCombo := ""
if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleTrailingTakeProfitCombo := ""
var string _message = ""
if (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_)
_message :=
zignalyCommonAlertMessage +
zignalySeparator +
_zignalyLongCommonAlertMessage +
zignalySeparator +
zignalyQuote + "positionSizePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsPercentStr + zignalyQuote +
_zignaleStopLossCombo +
_zignaleTakeProfitCombo +
_zignaleTrailingTakeProfitCombo
else // _ZIGSIGNALPROVIDER_
_message :=
zignalyCommonAlertMessage +
zignalySeparator +
_zignalyLongCommonAlertMessage +
zignalySeparator +
zignalyQuote + "positionSizeQuote" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsUSDTStr + zignalyQuote +
_zignaleStopLossCombo +
_zignaleTakeProfitCombo +
_zignaleTrailingTakeProfitCombo
_message
f_getZignalyLongCloseAlertMessage() =>
// Dependencies: zignalyQuote
// Dependencies: zignalyEquals
// Dependencies: zignalySeparator
// Dependencies: zignalyCommonAlertMessage
_zignalyLongCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "exit" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "long" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "LONG-" + exchangeTickerID + zignalyQuote
var string _message = ""
_message := zignalyCommonAlertMessage + zignalySeparator + _zignalyLongCloseCommonAlertMessage
_message
f_getZignalyShortAlertMessage(_entryQuantityContractsUSDT, _currentCapital) =>
// Dependencies: i_enableStopLoss (initialized in inputs).
// Dependencies: i_enableTakeProfit (initialized in inputs).
// Dependencies: i_TakeProfit (initialized in inputs).
// Dependencies: i_enableTrailingTakeProfit (initialized in inputs).
// Dependencies: i_trailingTakeProfitPercentageOffset (initialized in inputs).
// Dependencies: i_trailingTakeProfitPercentageTrigger (initialized in inputs).
// Dependencies: i_zignalyIntegrationType (initialized in inputs).
// Function Dependencies: f_priceDecimalDigitsZeroString()
var string _zignaleStopLossCombo = ""
var string _zignaleTakeProfitCombo = ""
var string _zignaleTrailingTakeProfitCombo = ""
_zignalyLongCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "entry" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "short" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "SHORT-" + exchangeTickerID + zignalyQuote
float _floatEntryQuantityContractsUSDT = _entryQuantityContractsUSDT
_entryQuantityContractsUSDTStr = tostring(_entryQuantityContractsUSDT, "0." + f_priceDecimalDigitsZeroString())
float _floatCurrentCapital = _currentCapital
float _entryQuantityContractsPercent = (_floatEntryQuantityContractsUSDT / _floatCurrentCapital) * 100.00
_entryQuantityContractsPercentStr = tostring(_entryQuantityContractsPercent, "0." + f_priceDecimalDigitsZeroString())
// This is actually not needed because with pyramiding=0 it's impossible that an order is scaled (and thus modified)
float _constantSellStopLoss = na
if (oldInsideASellOrder and insideASellOrder)
_constantSellStopLoss := sellStopLoss
else
_constantSellStopLoss := newSellStopLoss
if (i_enableStopLoss and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleStopLossCombo := zignalySeparator + zignalyQuote + "stopLossPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((nz(_constantSellStopLoss) * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleStopLossCombo := ""
if (i_enableTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleTakeProfitCombo := zignalySeparator + zignalyQuote + "takeProfitPercentage1" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_TakeProfit * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleTakeProfitCombo := ""
if (i_enableTrailingTakeProfit and (i_zignalyIntegrationType == _ZIGHYBRIDINTEGRATION_))
_zignaleTrailingTakeProfitCombo := zignalySeparator + zignalyQuote + "trailingStopDistancePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + tostring((i_trailingTakeProfitPercentageOffset * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote + zignalySeparator + zignalyQuote + "trailingStopTriggerPercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "-" + tostring((i_trailingTakeProfitPercentageTrigger * 100), "0." + f_priceDecimalDigitsZeroString()) + zignalyQuote
else
_zignaleTrailingTakeProfitCombo := ""
var string _message = ""
if (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_)
_message :=
zignalyCommonAlertMessage +
zignalySeparator +
_zignalyLongCloseCommonAlertMessage +
zignalySeparator +
zignalyQuote + "positionSizePercentage" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsPercentStr + zignalyQuote +
_zignaleStopLossCombo +
_zignaleTakeProfitCombo +
_zignaleTrailingTakeProfitCombo
else // _ZIGSIGNALPROVIDER_
_message :=
zignalyCommonAlertMessage +
zignalySeparator +
_zignalyLongCloseCommonAlertMessage +
zignalySeparator +
zignalyQuote + "positionSizeQuote" + zignalyQuote + zignalyEquals + zignalyQuote + "" + _entryQuantityContractsUSDTStr + zignalyQuote +
_zignaleStopLossCombo +
_zignaleTakeProfitCombo +
_zignaleTrailingTakeProfitCombo
_message
f_getZignalyShortCloseAlertMessage() =>
// Dependencies: zignalyQuote
// Dependencies: zignalyEquals
// Dependencies: zignalySeparator
// Dependencies: zignalyCommonAlertMessage
zignalyShortCloseCommonAlertMessage = zignalyQuote + "type" + zignalyQuote + zignalyEquals + zignalyQuote + "exit" + zignalyQuote + zignalySeparator + zignalyQuote + "side" + zignalyQuote + zignalyEquals + zignalyQuote + "short" + zignalyQuote + zignalySeparator + zignalyQuote + "orderType" + zignalyQuote + zignalyEquals + zignalyQuote + "market" + zignalyQuote + zignalySeparator + zignalyQuote + "signalId" + zignalyQuote + zignalyEquals + zignalyQuote + "SHORT-" + exchangeTickerID + zignalyQuote
var string _message = ""
_message := zignalyCommonAlertMessage + zignalySeparator + zignalyShortCloseCommonAlertMessage
_message
// Zignalye - Functions - END
// Order comment - Functions - BEGIN
f_getOrderComment(_typeOrder, _side, _alertMessage) =>
// Dependencies: i_enableOrderCommentDebug (initialized in inputs).
// TODO: Add descriptive comments
// _typeOrder="entry" or _typeOrder="close"
// _side: true means long ; false means short ; We can use strategy.long or strategy.short as true and false aliases
// _alertMessage
var string _orderComment = ""
if (i_enableOrderCommentDebug)
_orderComment := _alertMessage
else
// TODO: Use human explanations instead of default order comment value (na)
_orderComment := na
_orderComment
// Order comment - Functions - END
// Too recent orders functions
f_getTooRecentOrderNotOpenAdvice () =>
// Dependencies: i_tooRecentMinutesNumber_ms
// Dependencies: lastOrderOpenBarTime
// Condition 1: The order was open
// Condition 2: The order was long or short
// Condition 3: Time since order was last open is smaller than minimum between orders
// Returns boolean
bool _isTooRecent = ((time_close) <= (lastOrderOpenBarTime + i_tooRecentMinutesNumber_ms))
bool _tooRecentOrderBuyNotOpenAdvice = na
if (na(lastOrderOpenBarTime))
_tooRecentOrderBuyNotOpenAdvice := false
else
_tooRecentOrderBuyNotOpenAdvice := _isTooRecent
_tooRecentOrderBuyNotOpenAdvice
// FUNCTIONS - END
// Strategy Body - BEGIN
// Simple Logic to go LONG/LONG or go SHORT/SHORT - BEGIN
// longCondition = crossover(sma(close, 14), sma(close, 28))
// shortCondition = crossunder(sma(close, 14), sma(close, 28))
longCondition = sma(close, 14) >= sma(close, 28)
shortCondition = sma(close, 14) < sma(close, 28)
// Simple Logic to go LONG/LONG or go SHORT/SHORT - END
// Position price calculation - BEGIN
float positionPrice = na
if (insideASellOrder or insideABuyOrder)
positionPrice := strategy.position_avg_price
else
positionPrice := close
// Position price calculation - END
tooRecentOrderNotOpenAdvice = f_getTooRecentOrderNotOpenAdvice ()
newBuyStopLoss := i_StopLoss
newSellStopLoss := i_StopLoss
// Decide if we are going to LONG/Go LONG - BEGIN
PRE_LONG = false
PRE_LONG := longCondition and (not tooRecentOrderNotOpenAdvice)
// LONG = PRE_LONG[1] and PRE_LONG // Wait for confirmation
LONG = PRE_LONG // Do not wait for confirmation
// Decide if we are going to LONG/Go LONG - END
// Decide if we are going to SHORT/Go SHORT - BEGIN
PRE_SHORT = false
PRE_SHORT := shortCondition and (not tooRecentOrderNotOpenAdvice)
// SHORT = PRE_SHORT[1] and PRE_SHORT // Wait for confirmation
SHORT = PRE_SHORT // Do not wait for confirmation
// Decide if we are going to SHORT/Go SHORT - END
// Decide if a LONG/LONG entry should be closed - BEGIN
LONG_CLOSE = true
LONG_CLOSE := not (longCondition)
// Let's make sure LONG does not trigger if LONG_CLOSE would tell us to close the LONG
if LONG_CLOSE
LONG := false
// Decide if a LONG/LONG entry should be closed - END
// Decide if a SHORT/SHORT entry should be closed - BEGIN
SHORT_CLOSE = true
SHORT_CLOSE := not (shortCondition)
// Let's make sure SHORT does not trigger if SHORT_CLOSE would tell us to close the SHORT
if SHORT_CLOSE
SHORT := false
// Decide if a SHORT/SHORT entry should be closed - END
// How much to LONG/GO LONG/SHORT/GO SHORT - BEGIN
// Custom take profit and stop loss
LongTakeProfit = positionPrice * (1 + i_TakeProfit)
ShortTakeProfit = positionPrice * (1 - i_TakeProfit)
float LongStopLoss = na
float ShortStopLoss = na
LongStopLoss := positionPrice * (1 - buyStopLoss)
ShortStopLoss := positionPrice * (1 + sellStopLoss)
float entryQuantity = na
float currentCapital = strategy.initial_capital + strategy.netprofit
if (i_zignalyProviderType == _ZIGCOPYTRADERPROVIDER_)
entryQuantity := i_CapitalPercentage * currentCapital
else // _ZIGSIGNALPROVIDER_
entryQuantity := i_CapitalQuote
float entryQuantityContractsReducer = 0.99
contractMultiplier = f_getContractMultiplier(i_contractMaximumDecimalNumber)
// We assume the current price is current bar close
entryQuantityContracts = (floor(((entryQuantity / close) * entryQuantityContractsReducer) * contractMultiplier) / contractMultiplier)
entryQuantityContractsUSDT = entryQuantityContracts * (close)
// How much to LONG/GO LONG/SHORT/GO SHORT - END
// GO LONG only logic - BEGIN
var float tmpPositionBeforeOpeningOrder = na
if (i_strategyType == _L_)
if LONG
tmpPositionBeforeOpeningOrder := strategy.position_avg_price
tmpOrderAlertMessage := f_getZignalyLongAlertMessage(entryQuantityContractsUSDT, currentCapital)
tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage)
strategy.entry("[B]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
buyOrderOpenBarIndex := bar_index + 1
if (not insideABuyOrder)
buyStopLoss := newBuyStopLoss
insideABuyOrder := true
0 // Workaround for making every if branch to return the same type of value
else if LONG_CLOSE
tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage())
strategy.close("[B]", alert_message=i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment)
insideABuyOrder := false
0 // Workaround for making every if branch to return the same type of value
// GO LONG only logic - END
// GO SHORT only logic - BEGIN
if (i_strategyType == _S_)
if SHORT
tmpPositionBeforeOpeningOrder := strategy.position_avg_price
tmpOrderAlertMessage := f_getZignalyShortAlertMessage(entryQuantityContractsUSDT, currentCapital)
tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage)
strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
sellOrderOpenBarIndex := bar_index + 1
if (not insideASellOrder)
sellStopLoss := newSellStopLoss
insideASellOrder := true
0 // Workaround for making every if branch to return the same type of value
else if SHORT_CLOSE
tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage())
strategy.close("[S]", alert_message=i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment)
insideASellOrder := false
0 // Workaround for making every if branch to return the same type of value
// GO SHORT only logic - END
// GO LONG and SHORT logic - BEGIN
if (i_strategyType == L_S)
// Asumption: Above we have:
// if LONG_CLOSE
// LONG := false
// if SHORT_CLOSE
// SHORT := false
// LONG and SHORT cannot be true at the same time
// Anyways we will take it into account
if (LONG == true) and (SHORT == true)
LONG := true
SHORT := false
SHORT_CLOSE := true
if LONG
tmpPositionBeforeOpeningOrder := strategy.position_avg_price
tmpOrderAlertMessage := f_getZignalyLongAlertMessage(entryQuantityContractsUSDT, currentCapital)
tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage)
strategy.entry("[B]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
buyOrderOpenBarIndex := bar_index + 1
if (not insideABuyOrder)
buyStopLoss := newBuyStopLoss
insideABuyOrder := true
if LONG_CLOSE
tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage())
strategy.close("[B]", alert_message=i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment)
insideABuyOrder := false
if SHORT
tmpPositionBeforeOpeningOrder := strategy.position_avg_price
tmpOrderAlertMessage := f_getZignalyShortAlertMessage(entryQuantityContractsUSDT, currentCapital)
tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage)
strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
sellOrderOpenBarIndex := bar_index + 1
if (not insideASellOrder)
sellStopLoss := newSellStopLoss
insideASellOrder := true
if SHORT_CLOSE
tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage())
strategy.close("[S]", alert_message=i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment)
insideASellOrder := false
// GO LONG and SHORT logic - END
// Handle STOP LOSS (and similar) order exits - BEGIN
// Quick Paste - BEGIN
float longTrailingTakeProfitPrice = na
float longTrailingTakeProfitPoints = na
float longTrailingTakeProfitOffset = na
float shortTrailingTakeProfitPrice = na
float shortTrailingTakeProfitPoints = na
float shortTrailingTakeProfitOffset = na
// Calculate trailing_take_profit_offset based on tick units
longTmpTtpBaseValue = positionPrice * (1 + i_trailingTakeProfitPercentageTrigger)
longTmpTtpTop_value = longTmpTtpBaseValue * (1 + i_trailingTakeProfitPercentageOffset)
longTrailingTakeProfitOffsetFloat = longTmpTtpTop_value - longTmpTtpBaseValue
float longTrailingTakeProfitOffsetTick = floor (longTrailingTakeProfitOffsetFloat / syminfo.mintick)
shortTmpTtpBaseValue = positionPrice * (1 - i_trailingTakeProfitPercentageTrigger)
shortTmpTtpBottomValue = shortTmpTtpBaseValue * (1 - i_trailingTakeProfitPercentageOffset)
shortTrailingTakeProfitOffsetFloat = shortTmpTtpBaseValue - shortTmpTtpBottomValue
float shortTrailingTakeProfitOffsetTick = floor (shortTrailingTakeProfitOffsetFloat / syminfo.mintick)
if i_enableTrailingTakeProfit
longTrailingTakeProfitPrice := positionPrice * (1 + i_trailingTakeProfitPercentageTrigger)
longTrailingTakeProfitOffset := longTrailingTakeProfitOffsetTick
shortTrailingTakeProfitPrice := positionPrice * (1 - i_trailingTakeProfitPercentageTrigger)
shortTrailingTakeProfitOffset := shortTrailingTakeProfitOffsetTick
else
longTrailingTakeProfitPrice := na
longTrailingTakeProfitOffset := na
shortTrailingTakeProfitPrice := na
shortTrailingTakeProfitOffset := na
// Quick Paste - END
// This might trigger additional close orders than needed in zignaly
// Better close an existing order twice than regreting zignaly not having closed it.
tmpOrderComment := f_getOrderComment("close", strategy.long, f_getZignalyLongCloseAlertMessage())
strategy.exit("[SL/TP]", "[B]", stop= i_enableStopLoss ? LongStopLoss : na, limit= i_enableTakeProfit ? LongTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? longTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? longTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? f_getZignalyLongCloseAlertMessage() : na, comment=tmpOrderComment)
tmpOrderComment := f_getOrderComment("close", strategy.short, f_getZignalyShortCloseAlertMessage())
strategy.exit("[SL/TP]", "[S]", stop= i_enableStopLoss ? ShortStopLoss : na, limit= i_enableTakeProfit ? ShortTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? shortTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? shortTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? f_getZignalyShortCloseAlertMessage() : na, comment=tmpOrderComment)
// Handle STOP LOSS (and similar) order exits - END
// Strategy Body - END
|
Multi Time Frame Buy the Dips (by Coinrule) | https://www.tradingview.com/script/pWjAdZql-Multi-Time-Frame-Buy-the-Dips-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 261 | strategy | 1 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=1
strategy(shorttitle='Multi Time Frame Buy the Dips',title='Multi Time Frame Buy the Dips (by Coinrule)', overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month")
fromDay = input(defval = 10, title = "From Day")
fromYear = input(defval = 2020, title = "From Year")
thruMonth = input(defval = 1, title = "Thru Month")
thruDay = input(defval = 1, title = "Thru Day")
thruYear = input(defval = 2112, title = "Thru Year")
showDate = input(defval = true, title = "Show Date Range")
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
inp_lkb = input(12, title='Lookback Long Period')
inp_lkb_2 = input(2, title='Lookback Short Period')
perc_change(lkb) =>
overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100
// Call the function
overall = perc_change(inp_lkb)
overall_2 = perc_change(inp_lkb_2)
//Entry
dip= -(input(1))
increase= (input(3))
strategy.entry(id="long", long = true, when = overall > increase and overall_2 < dip and window())
//Exit
Stop_loss= ((input (3))/100)
Take_profit= ((input (4))/100)
longStopPrice = strategy.position_avg_price * (1 - Stop_loss)
longTakeProfit = strategy.position_avg_price * (1 + Take_profit)
strategy.close("long", when = close < longStopPrice or close > longTakeProfit and window())
|
BuyTheDip | https://www.tradingview.com/script/eccsOVft-BuyTheDip/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 359 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("BuyTheDip", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
exitType = input(title="Exit Strategy", defval="Signal", options=["Signal", "TrailingStop", "Both"])
LookbackPeriod = input(30, minval=10,step=10)
BBStdDev = input(2, minval=1, maxval=10, step=0.5)
BBLength = input(60, minval=5, step=5)
atrLength = input(22)
atrMult = input(6)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
backtestYears = input(10, minval=1, step=1)
includePartiallyAligned = true
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getTrailingStop(atr, atrMult)=>
stop = close - atrMult*atr
stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop
stop
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
exitBySignal = exitType == "Signal" or exitType == "Both"
exitByTrailingStop = exitType == "TrailingStop" or exitType == "Both"
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
atr = atr(atrLength)
trailingStop = f_getTrailingStop(atr, atrMult)
maAligned = highest(maAlignment,LookbackPeriod)
[middle, upper, lower] = bb(close, BBLength, BBStdDev)
buyCondition = maAligned == 1 and (crossover(close, lower) or crossover(close, middle))
buyExitCondition = crossunder(close, upper)
strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)
strategy.close("Buy", when=buyExitCondition and exitBySignal)
strategy.exit("ExitBuy", "Buy", stop = trailingStop, when=exitByTrailingStop )
|
Moving Average Cross Strategy early Closing | https://www.tradingview.com/script/aIdZ7EvV-Moving-Average-Cross-Strategy-early-Closing/ | Geduldtrader | https://www.tradingview.com/u/Geduldtrader/ | 58 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Geduldtrader
//@version=4
strategy("MA Crossover", overlay = true)
start = timestamp(2009,2,1,0,0)
sma50 = sma(close, 50)
sma40 = sma(close, 40)
sma3 = sma(close, 3)
plot(sma50,title='50', color=#00ffaa, linewidth=2)
plot(sma3,title='3', color=#2196F3, linewidth=2)
long = crossover(sma3,sma50)
neut = crossunder(close,sma50)
short = crossunder(sma3,sma40)
if time >= start
strategy.entry("Long", strategy.long, 10.0, when=long)
strategy.close("Long", when = short)
strategy.close("Long", when = neut)
plot(close) |
AlignedMA and Cumulative HighLow Strategy V2 | https://www.tradingview.com/script/b5bVz0K1-AlignedMA-and-Cumulative-HighLow-Strategy-V2/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 242 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("AlignedMA and Cumulative HighLow Strategy V2", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
MAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
includePartiallyAligned = input(true)
HighLowPeriod = input(22, minval=1,step=1)
LookbackPeriod = input(10, minval=1,step=1)
considerYearlyHighLow = input(false)
dirTBars = input(1)
dirRBars = input(30)
PMAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
PMALength = input(10, minval=2, step=10)
shift = input(2, minval=1, step=1)
//Use 2 for ASX stocks
supertrendMult = input(3, minval=1, maxval=10, step=0.5)
supertrendLength = input(22, minval=1)
riskReward = input(2, minval=1, maxval=10, step=0.5)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
backtestYears = input(1, minval=1, step=1)
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
f_getHighLowValue(HighLowPeriod)=>
currentHigh = highest(high,HighLowPeriod) == high
currentLow = lowest(low,HighLowPeriod) == low
currentHigh?1:currentLow?-1:0
f_getDirection(Series)=>
direction = Series > Series[1] ? 1 : Series < Series[1] ? -1 : 0
direction := direction == 0? nz(direction[1],0):direction
direction
f_getDirectionT(Series, tBars, rBars)=>
compH = Series > 0? Series[tBars] : Series[rBars]
compL = Series < 0? Series[tBars] : Series[rBars]
direction = Series > compH ? 1 : Series < compL ? -1 : 0
direction := direction == 0? nz(direction[1],0):direction
direction
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
[yearlyHighCondition,yearlyLowCondition]
f_getOpenCloseMA(MAType, length)=>
openMA = f_getMovingAverage(open, MAType, length)
closeMA = f_getMovingAverage(close, MAType, length)
direction = openMA < closeMA ? 1 : -1
[openMA, closeMA, direction]
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
alignedMaIndex = sum(maAlignment,LookbackPeriod)
maAlignmentDirection=f_getDirectionT(alignedMaIndex,dirTBars, dirRBars)
atr = atr(22)
highLowIndex = f_getHighLowValue(HighLowPeriod)
cumulativeHighLowIndex = sum(highLowIndex,LookbackPeriod)
hlDirection = f_getDirectionT(cumulativeHighLowIndex,dirTBars,dirRBars)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
[supertrend, dir] = supertrend(supertrendMult, supertrendLength)
[esupertrend, edir] = supertrend(supertrendMult+1, supertrendLength)
movingAverage = f_getMovingAverage(close, PMAType, PMALength)
secondaryBuyFilter = movingAverage > movingAverage[shift]
secondarySellFilter = movingAverage < movingAverage[shift]
closeBuyFilter = dir == 1
closeSellFilter = dir == -1
buyFilter = (maAlignmentDirection == 1 and hlDirection == 1 and yearlyHighCondition)
sellFilter = (maAlignmentDirection == -1 and hlDirection == -1 and yearlyLowCondition)
barColor = buyFilter?color.lime:sellFilter?color.orange:color.gray
bandColor = secondaryBuyFilter ? color.green : secondarySellFilter ? color.red : color.gray
compound = strategy.position_size > 0? strategy.position_avg_price + (atr* supertrendMult * riskReward) : strategy.position_size < 0 ? strategy.position_avg_price - (atr* supertrendMult * riskReward) : na
riskFree = na(compound)?false:strategy.position_size > 0 ? supertrend > compound : strategy.position_size < 0 ? supertrend < compound : false
trailingStop = riskFree?(dir==-1?supertrend - 2*atr : supertrend + 2*atr) :supertrend
trailingStop := (strategy.position_size > 0 and trailingStop < trailingStop[1]) ? trailingStop[1] : ((strategy.position_size < 0 and trailingStop > trailingStop[1])? trailingStop[1] :trailingStop)
plot(trailingStop, title="Supertrend", color=riskFree? color.blue:dir==-1?color.green:color.red, linewidth=2)
buyEntry = buyFilter and secondaryBuyFilter and not closeBuyFilter and low > trailingStop
sellEntry = sellFilter and secondarySellFilter and not closeSellFilter and low < trailingStop
Fi1 = plot(movingAverage[shift], title="MA", color=color.red, linewidth=1, transp=50)
Fi2 = plot(movingAverage, title="Shift", color=color.green, linewidth=1, transp=50)
fill(Fi1, Fi2, title="Band Filler", color=bandColor, transp=40)
barcolor(barColor)
//plot(compound, title="Compound"mzn, color=dir==-1?color.lime:color.orange, linewidth=2)
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_buy", oca_type=strategy.oca.none)
strategy.exit("ExitBuy", "Buy", stop = trailingStop)
strategy.close("Buy", when=closeBuyFilter)
strategy.entry("Sell", strategy.short, when=sellEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_sell", oca_type=strategy.oca.none)
strategy.exit("ExitSell", "Buy", stop = trailingStop)
strategy.close("Sell", when=closeSellFilter)
|
Short In Downtrend Below MA100 (Coinrule) | https://www.tradingview.com/script/SpGO98mX-Short-In-Downtrend-Below-MA100-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 137 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=4
strategy(shorttitle='Short In Downtrend',title='Short In Downtrend Below MA100', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 10, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2019, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
//MA inputs and calculations
inSignal=input(50, title='MASignal')
MA= sma(close, inSignal)
// RSI inputs and calculations
lengthRSI = input(14, title = 'RSI period', minval=1)
RSI = rsi(close, lengthRSI)
//Entry
strategy.entry(id="short", long = false, when = close < MA and RSI > 30)
//Exit
shortStopPrice = strategy.position_avg_price * (1 + 0.03)
shortTakeProfit = strategy.position_avg_price * (1 - 0.02)
strategy.close("short", when = close > shortStopPrice or close < shortTakeProfit and window())
plot(MA, color=color.purple, linewidth=2)
|
Breakout Trend Trading Strategy - V1 | https://www.tradingview.com/script/nPquImkd-Breakout-Trend-Trading-Strategy-V1/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 235 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Breakout Trend Trading - V1", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)
///////////////////////////////////////// Input ////////////////////////////////////////////////////////////////////
//supertrendMult = input(6, minval=1, maxval=10, step=0.5)
//supertrendLength = input(22, minval=1)
//volumelength = input(title="Volume MA Length", defval=20, minval=10, step=10)
//volumeMaType = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
//trendVolumeMarkup = input(15, minval=0, maxval=100, step=5)
//reverseVolumeMarkup = input(15, minval=0, maxval=100, step=5)
//highVolumeMultiplyer = input(5, minval=2, maxval=10, step=1)
//atrlength = input(22, minval=1)
//trendTargetMult = input(1, minval=1, maxval=10, step=0.5)
//reverseTargetMult = input(1, minval=1, maxval=10, step=0.5)
//highBreakoutMult = input(2, minval=2, maxval=10, step=1)
//trendValueMarkup = input(15, minval=0, maxval=100, step=5)
//reverseValueMarkup = input(30, minval=0, maxval=100, step=5)
//stopMultFactor = input(1, minval=0.5, maxval=10, step=0.5)
//considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")
//shortHighLowPeriod = input(120, step=10)
//longHighLowPeriod = input(180, step=10)
//considerMaAlignment = input(true,"Check recent moving average alignment")
//MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
//LookbackPeriod = input(200, step=10)
//alignmentIndexThreshold = input(0, step=10)
//includePartiallyAligned = input(true)
//considerMaSupertrend = input(true)
//source = input(ohlc4)
//MaTypeMa = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
//MaLengthMa = input(10, step=10)
//supertrendLengthMa = input(10, step=10)
//supertrendMultMa = input(1, step=1)
supertrendMult = 6
supertrendLength = 22
volumelength = 20
volumeMaType = "sma"
trendVolumeMarkup = 15
reverseVolumeMarkup = 25
highVolumeMultiplyer = 5
atrlength = 22
trendTargetMult = 1
reverseTargetMult = 1
highBreakoutMult = 2
trendValueMarkup = 15
reverseValueMarkup = 30
stopMultFactor = 1
considerYearlyHighLow = true
ignoreReverseBreakout = true
//allowImmediateCompound = true
considerOpenCloseBreakout = false
allowReduceCompound = true
considerNewLongTermHighLows = true
shortHighLowPeriod = 120
longHighLowPeriod = 180
considerMaAlignment = true
MAType = "sma"
LookbackPeriod = 280
alignmentIndexThreshold = 0
includePartiallyAligned = true
considerMaSupertrend = true
source = ohlc4
MaTypeMa = "sma"
MaLengthMa = 10
supertrendLengthMa = 10
supertrendMultMa = 1
exitOnSignal = input(false)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
allowImmediateCompound = input(false)
displayMode = input(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])
showTrailingStop = input(true)
showTargetLevels = input(true)
showPreviousLevels = input(false)
stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)
compoundMultiplyer = input(1, minval=1, maxval=10, step=0.5)
backtestYears = input(10, minval=1, step=1)
///////////////////////////// Display mode calculation ////////////////////////////////////////////////
f_getDisplayModeVeriables(displayMode)=>
bool showTargets = false
bool showChannel = false
bool showTargetStops = false
bool showUpChannel = false
bool showDownChannel = false
if(displayMode == "Targets")
showTargets := true
if(displayMode == "Target Channel")
showChannel := true
if(displayMode == "Target with Stops")
showTargetStops := true
if(displayMode == "Up Channel")
showUpChannel := true
if(displayMode == "Down Channel")
showDownChannel := true
[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel]
///////////////////////////// Get Price breakout values ////////////////////////////////////////////////
f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)=>
trendBreakout = false
if(abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout)
trendBreakout := true
reverseBreakout = false
if(abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout)
reverseBreakout := true
highBreakout = false
if(abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout)
highBreakout:=true
[trendBreakout, reverseBreakout, highBreakout]
///////////////////////////// Get Volume breakout values ////////////////////////////////////////////////
f_getVolumeBreakout(vma, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMarkup)=>
vmaMarkup = vma * (1+(trendVolumeMarkup/100))
vmaReverseMarkup = vma * (1+(reverseVolumeMarkup/100))
vmaHighVolumeMarkup = vma * highVolumeMarkup
trendVolumeBreakout = vmaMarkup < volume or na(volume)
stopVolumeBreakout = vmaReverseMarkup < volume or na(volume)
highVolumeBreakout = vmaHighVolumeMarkup < volume and not na(volume)
[trendVolumeBreakout, stopVolumeBreakout, highVolumeBreakout]
//////////////////////////////////// Get Candle color //////////////////////////////////////////////////
f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)=>
barState = 0
if(close > close[1] and ( (dir == -1 and trendBreakout and trendVolumeBreakout) or (dir == 1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
barState := 1
if(close < close[1] and ( (dir == 1 and trendBreakout and trendVolumeBreakout) or (dir == -1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
barState := -1
barState
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)=>
diff = max(high-low, max(abs(high-close[1]), abs(low-close[1])))
upTarget = (barState == 1) ? high + ((dir==-1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
downTarget = (barState == -1) ? low - ((dir==1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
stopUpTarget = (barState == 1) ? low - atr * stopMultFactor : na
stopDownTarget = (barState == -1) ? high + atr * stopMultFactor : na
lastBreakout = barState
lastBreakout:= lastBreakout == 0? nz(lastBreakout[1], 0): lastBreakout
[upTarget,stopUpTarget,downTarget,stopDownTarget,lastBreakout]
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)=>
upLine = upTarget
downLine = downTarget
stopUpLine = stopUpTarget
stopDownLine = stopDownTarget
upLine := na(upLine) ? nz(upLine[1],na) : upLine
downLine := na(downLine) ? nz(downLine[1],na) : downLine
stopUpLine := na(stopUpLine) ? nz(stopUpLine[1],na) : stopUpLine
stopDownLine := na(stopDownLine) ? nz(stopDownLine[1],na) : stopDownLine
[upLine,stopUpLine,downLine,stopDownLine]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
[yearlyHighCondition,yearlyLowCondition]
//////////////////////////////////// Calculate Trade Flags /////////////////////////////////////////////////////
f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange)=>
buyPrerequisites = inDateRange and yearlyHighCondition
sellPrerequisites = inDateRange and yearlyLowCondition
buyEntry = buySignal and yearlyHighCondition and barState != -1 and inDateRange
sellEntry = sellSignal and yearlyLowCondition and barState != 1 and inDateRange
stopBuyEntry = stopBuySignal and barState != 1 and inDateRange
stopSellEntry = stopSellSignal and barState != -1 and inDateRange
[buyEntry, sellEntry, stopBuyEntry, stopSellEntry]
//////////////////////////////////// Get Moving average ///////////////////////////////////
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_supertrendOnMa(source, MaType, MaLength, supertrendLength, supertrendMult)=>
supertrendDistance = supertrendMult * atr(supertrendLength)
ma = f_getMovingAverage(source,MaType, MaLength)
longStop = ma - supertrendDistance
longStopPrev = nz(longStop[1], longStop)
longStop := ma > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = ma + supertrendDistance
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := ma < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and ma > shortStopPrev ? 1 : dir == 1 and ma < longStopPrev ? -1 : dir
supertrend = dir==1 ? longStop: shortStop
[supertrend, ma, dir]
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
//////////////////////////////////// Calculate Buy Sell signals //////////////////////////////////////////////////
f_calculateBuySellFlags(dir,lastBreakout,ignoreReverseBreakout, barState, upLine, stopUpLine, downLine, stopDownLine)=>
greenBreakout = (lastBreakout > 0) or ignoreReverseBreakout
redBreakout = (lastBreakout < 0) or ignoreReverseBreakout
buySignal = ((crossover(dir==-1?high:low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(dir==-1?high:low, stopDownLine[1]) and redBreakout) or ((barState == 1) and (dir==-1?high:low) > upLine[1]))
stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1]))
sellSignal = ((crossunder(dir==1?low:high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(dir==1?low:high, stopUpLine[1]) and greenBreakout) or (barState == -1) and (dir==1?low:high) < downLine[1])
stopSellSignal = (crossover(dir==1?close:high, upLine[1]) or crossover(dir==1?close:high, stopDownLine[1]))
[buySignal,stopBuySignal,sellSignal,stopSellSignal]
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
[newHigh,newLow]
//////////////////////////////////// Calculate trailing stop //////////////////////////////////////////////////
f_calculateTrailingStop(stop)=>
strategy.position_size > 0? (stop > stop[1]? stop : stop[1]) : strategy.position_size < 0 ? (stop < stop[1]? stop : stop[1]) : stop
//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////
f_calculateStopAndCompound(target, atr, stopMultiplyer, compoundMultiplyer, barState)=>
buyStop = target - (stopMultiplyer * atr)
sellStop = target + (stopMultiplyer * atr)
if(barState > 0 or strategy.position_size > 0)
buyStop := target - (stopMultiplyer * atr)
sellStop := target + (compoundMultiplyer * atr)
buyStop := (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop
sellStop := (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop
else if(barState < 0 or strategy.position_size < 0)
buyStop := target - (compoundMultiplyer * atr)
sellStop := target + (stopMultiplyer * atr)
sellStop := (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop
buyStop := (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop
[buyStop, sellStop]
//////////////////////////////////// Draw Lines with labels //////////////////////////////////////////////////
f_drawLinesWithLabels(target, lbl, linecolor)=>
line_x1 = time+(60*60*24*1000*1)
line_x2 = time+(60*60*24*1000*7)
label_x = time+(60*60*24*1000*4)
targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time)
targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal)
[targetLine,targetLabel]
//////////////////////////////////// Delete Lines with labels //////////////////////////////////////////////////
f_deleteLinesWithLabels(targetLine, targetLabel, last)=>
line.delete(id=last?targetLine[1]:targetLine)
label.delete(id=last?targetLabel[1]:targetLabel)
/////////////////////////////////////////////////// Calculate Trend //////////////////////////////////////////////////////
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel] = f_getDisplayModeVeriables(displayMode)
vma = f_getMovingAverage(volume, volumeMaType, volumelength)
[superTrend, dir] = supertrend(supertrendMult, supertrendLength)
atr = atr(atrlength)
[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)
[trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout] = f_getVolumeBreakout(vma, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMultiplyer)
barState = f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)
[upTarget,stopUpTarget,downTarget,stopDownTarget, lastBreakout] = f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)
[upLine,stopUpLine,downLine,stopDownLine] = f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
[supertrendMa, ma, dirMa] = f_supertrendOnMa(source, MaTypeMa, MaLengthMa, supertrendLengthMa, supertrendMultMa)
//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////
percentRank = percentrank(source, LookbackPeriod)
[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateBuySellFlags(dir,lastBreakout,ignoreReverseBreakout, barState, upLine, stopUpLine, downLine, stopDownLine)
[newHigh, newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
[buyEntry, sellEntry, stopBuyEntry, stopSellEntry] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange)
[buyStop, sellStop] = f_calculateStopAndCompound(close, atr, stopMultiplyer, compoundMultiplyer, barState)
crossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompound
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
alignedMaIndex = sum(maAlignment,LookbackPeriod)
maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignment
maLow = alignedMaIndex < -alignmentIndexThreshold or not considerMaAlignment
//buyEntry := buyEntry and ((newHigh and maHigh and percentRank > 50) or strategy.netprofit >= 0)
//sellEntry := sellEntry and ((newLow and maLow and percentRank < 50) or strategy.netprofit >= 0)
buyEntry := buyEntry and ((newHigh and maHigh and (dirMa == 1 or not considerMaSupertrend) and percentRank > 70) or strategy.netprofit >= 0)
sellEntry := sellEntry and ((newLow and maLow and (dirMa == -1 or not considerMaSupertrend) and percentRank < 30) or strategy.netprofit >= 0)
//////////////////////////////////////// Plot //////////////////////////////////////////////////////
plot(showChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showChannel?downLine:na, title="downChannel", color=color.red, linewidth=2, style=plot.style_line)
plotshape(showTargets or showTargetStops?upTarget:na, title="UpTarget", color=color.green, style=shape.triangleup, location = location.absolute)
plotshape(showTargets or showTargetStops?downTarget:na, title="DownTarget", color=color.red, style=shape.triangledown, location = location.absolute)
plotshape(showTargetStops?stopUpTarget:na, title="UpStop", color=color.green, style=shape.triangleup, location = location.absolute)
plotshape(showTargetStops?stopDownTarget:na, title="DownStop", color=color.red, style=shape.triangledown, location = location.absolute)
plot(showUpChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showUpChannel?stopUpLine:na, title="StopUpChannel", color=color.red, linewidth=2, style=plot.style_line)
plot(showDownChannel?stopDownLine:na, title="StopDownChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showDownChannel?downLine:na, title="DownChannel", color=color.red, linewidth=2, style=plot.style_line)
channelview = showChannel or showUpChannel or showDownChannel
plot(showTrailingStop and strategy.position_size != 0 and not channelview? buyStop : na, title="DownStop", color=(strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue), linewidth=2, style=plot.style_stepline)
plot(showTrailingStop and strategy.position_size != 0 and not channelview? sellStop : na, title="UpStop", color=(strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue), linewidth=2, style=plot.style_stepline)
//plot(percentValue, title="percentRank", color=color.blue, linewidth=2, style=plot.style_stepline)
barcolor(barState == 1? color.lime : barState == -1? color.orange : color.silver)
//////////////////////////////////////// Plot Trade //////////////////////////////////////////////////////
if(buyEntry or sellEntry) and (showTargetLevels)
[targetLine, targetLabel] = f_drawLinesWithLabels(close,buyEntry?"Long":"Short",color.blue)
if(not showPreviousLevels)
f_deleteLinesWithLabels(targetLine, targetLabel, true)
if(buyEntry or sellEntry or strategy.position_size != 0)
[stopLine, stopLabel] = f_drawLinesWithLabels(buyEntry?buyStop:sellStop,"Stop",color.red)
[compoundLine, compoundLabel] = f_drawLinesWithLabels(buyEntry?sellStop:buyStop,"Compound",color.green)
f_deleteLinesWithLabels(stopLine, stopLabel, true)
f_deleteLinesWithLabels(compoundLine, compoundLabel, true)
//////////////////////////////////////// Trade //////////////////////////////////////////////////////
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyEntry and crossedCompound)
strategy.close("Buy", when=stopBuyEntry and exitOnSignal)
strategy.exit("ExitBuy", "Buy", stop = buyStop)
strategy.entry("Sell", strategy.short, when=sellEntry and crossedCompound)
strategy.close("Sell", when=stopSellEntry and exitOnSignal)
strategy.exit("ExitSell", "Sell", stop = sellStop)
|
Breakout Trend Trading Strategy - V2 | https://www.tradingview.com/script/w5LHTJo4-Breakout-Trend-Trading-Strategy-V2/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 335 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Breakout Trend Trading - V2", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
///////////////////////////////////////// Input ////////////////////////////////////////////////////////////////////
exitOnSignal = input(false)
exitStrategyOnRangingCondition = input(title="Exit Strategy when in Range", defval="Disabled", options=["Disabled", "ExitOnSignal", "TrailStopLoss", "BollingerBands"])
allowImmediateCompound = input(false)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
tradeType = input(title="Trade Type", defval="all", options=["all", "pullback", "breakout", "reverse", "pullback + breakout"])
displayMode = input(title="Display Mode", defval="Targets", options=["Targets", "Target Channel", "Target with Stops", "Up Channel", "Down Channel"])
showTrailingStop = input(true)
showTargetLevels = input(true)
showPreviousLevels = input(false)
stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)
compoundMultiplyer = input(4, minval=1, maxval=10, step=0.5)
rangeBars = input(100, step=5)
backtestYears = input(10, minval=1, step=1)
considerNewLongTermHighLows = input(true,"Filter Highs/Lows for entry")
shortHighLowPeriod = input(100, step=10)
longHighLowPeriod = input(200, step=10)
considerMaAlignment = input(true,"Check recent moving average alignment")
LookbackPeriod = input(300, step=10)
includePartiallyAligned = input(true)
MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
alignmentIndexThreshold = input(50, step=10)
LookbackPeriodPR = input(50, step=10)
considerWeeklySupertrend = input(false)
SupertrendWMult = input(1)
SupertrendWPd = input(26)
considerMonthlySupertrend = input(false)
SupertrendMMult = input(2)
SupertrendMPd = input(6)
//supertrendMult = input(6, minval=1, maxval=10, step=0.5)
//supertrendLength = input(22, minval=1)
//volumelength = input(title="Volume MA Length", defval=20, minval=10, step=10)
//reverseVolumeLength = input(title="Volume MA Length", defval=20, minval=10, step=10)
//volumeMaType = input(title="Volume MA Type", defval="hma", options=["ema", "sma", "hma", "rma", "swma", "vwma", "wma"])
//trendVolumeMarkup = input(15, minval=0, maxval=100, step=5)
//reverseVolumeMarkup = input(25, minval=0, maxval=100, step=5)
//highVolumeMultiplyer = input(5, minval=2, maxval=10, step=1)
//atrlength = input(22, minval=1)
//trendTargetMult = input(1, minval=1, maxval=10, step=0.5)
//reverseTargetMult = input(1, minval=1, maxval=10, step=0.5)
//highBreakoutMult = input(2, minval=2, maxval=10, step=1)
//trendValueMarkup = input(15, minval=0, maxval=100, step=5)
//reverseValueMarkup = input(30, minval=0, maxval=100, step=5)
//stopMultFactor = input(1, minval=0.5, maxval=10, step=0.5)
//considerMaSupertrend = input(true)
//source = input(ohlc4)
//MaTypeMa = input(title="Volume MA Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
//MaLengthMa = input(10, step=10)
//supertrendLengthMa = input(10, step=10)
//supertrendMultMa = input(1, step=1)
considerMaSupertrend = true
source = ohlc4
MaTypeMa = "sma"
MaLengthMa = 10
supertrendLengthMa = 10
supertrendMultMa = 1
ignoreReverseBreakout = true
considerYearlyHighLow = true
considerOpenCloseBreakout = false
supertrendMult = 6
supertrendLength = 22
volumelength = 20
reverseVolumeLength = 20
volumeMaType = "hma"
trendVolumeMarkup = 15
reverseVolumeMarkup = 25
highVolumeMultiplyer = 5
atrlength = 22
trendTargetMult = 1
reverseTargetMult = 1
highBreakoutMult = 2
trendValueMarkup = 15
reverseValueMarkup = 30
stopMultFactor = 1
///////////////////////////// Display mode calculation ////////////////////////////////////////////////
f_getDisplayModeVeriables(displayMode)=>
bool showTargets = false
bool showChannel = false
bool showTargetStops = false
bool showUpChannel = false
bool showDownChannel = false
if(displayMode == "Targets")
showTargets := true
if(displayMode == "Target Channel")
showChannel := true
if(displayMode == "Target with Stops")
showTargetStops := true
if(displayMode == "Up Channel")
showUpChannel := true
if(displayMode == "Down Channel")
showDownChannel := true
[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel]
f_getRangeExitStrategy(exitStrategyOnRangingCondition)=>
exitOnSignalWhenInRange = false
exitOnTrailingStopWhenInRange = false
exitOnBB = false
if(exitStrategyOnRangingCondition == "ExitOnSignal")
exitOnSignalWhenInRange := true
if(exitStrategyOnRangingCondition == "TrailStopLoss")
exitOnTrailingStopWhenInRange := true
if(exitStrategyOnRangingCondition == "BollingerBands")
exitOnBB := true
[exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB]
///////////////////////////// Get Price breakout values ////////////////////////////////////////////////
f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)=>
trendBreakout = false
if(abs(close[1] - close) > atr * trendTargetMult) or (high-low > 2 * atr * trendTargetMult and considerOpenCloseBreakout)
trendBreakout := true
reverseBreakout = false
if(abs(close[1] - close) > atr * reverseTargetMult) or (high-low > 2 * atr * reverseTargetMult and considerOpenCloseBreakout)
reverseBreakout := true
highBreakout = false
if(abs(close[1] - close) > atr * highBreakoutMult) or (high-low > 2 * atr * highBreakoutMult and considerOpenCloseBreakout)
highBreakout:=true
[trendBreakout, reverseBreakout, highBreakout]
///////////////////////////// Get Volume breakout values ////////////////////////////////////////////////
f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMarkup)=>
vmaMarkup = vma * (1+(trendVolumeMarkup/100))
vmaReverseMarkup = vmareverse * (1+(reverseVolumeMarkup/100))
vmaHighVolumeMarkup = vma * highVolumeMarkup
trendVolumeBreakout = vmaMarkup < volume or na(volume)
stopVolumeBreakout = vmaReverseMarkup < volume or na(volume)
highVolumeBreakout = vmaHighVolumeMarkup < volume and not na(volume)
[trendVolumeBreakout, stopVolumeBreakout, highVolumeBreakout]
//////////////////////////////////// Get Candle color //////////////////////////////////////////////////
f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)=>
barState = 0
if(close > close[1] and ( (dir == -1 and trendBreakout and trendVolumeBreakout) or (dir == 1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
barState := 1
if(close < close[1] and ( (dir == 1 and trendBreakout and trendVolumeBreakout) or (dir == -1 and reverseBreakout and reverseVolumeBreakout) or highVolumeBreakout or highBreakout))
barState := -1
barState
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)=>
diff = max(high-low, max(abs(high-close[1]), abs(low-close[1])))
upTarget = (barState == 1) ? high + ((dir==-1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
downTarget = (barState == -1) ? low - ((dir==1?trendValueMarkup:reverseValueMarkup)/100)*diff : na
stopUpTarget = (barState == 1) ? low - atr * stopMultFactor : na
stopDownTarget = (barState == -1) ? high + atr * stopMultFactor : na
lastBreakout = barState
lastBreakout:= lastBreakout == 0? nz(lastBreakout[1], 0): lastBreakout
[upTarget,stopUpTarget,downTarget,stopDownTarget,lastBreakout]
//////////////////////////////////// Calculate target values //////////////////////////////////////////////////
f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)=>
upLine = upTarget
downLine = downTarget
stopUpLine = stopUpTarget
stopDownLine = stopDownTarget
upLine := na(upLine) ? nz(upLine[1],na) : upLine
downLine := na(downLine) ? nz(downLine[1],na) : downLine
stopUpLine := na(stopUpLine) ? nz(stopUpLine[1],na) : stopUpLine
stopDownLine := na(stopDownLine) ? nz(stopDownLine[1],na) : stopDownLine
[upLine,stopUpLine,downLine,stopDownLine]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
label_x = time+(60*60*24*1000*1)
[yearlyHighCondition,yearlyLowCondition]
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
f_supertrendOnMa(source, MaType, MaLength, supertrendLength, supertrendMult)=>
supertrendDistance = supertrendMult * atr(supertrendLength)
ma = f_getMovingAverage(source,MaType, MaLength)
longStop = ma - supertrendDistance
longStopPrev = nz(longStop[1], longStop)
longStop := ma > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = ma + supertrendDistance
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := ma < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and ma > shortStopPrev ? 1 : dir == 1 and ma < longStopPrev ? -1 : dir
supertrend = dir==1 ? longStop: shortStop
[supertrend, ma, dir]
//////////////////////////////////// Calculate Buy Sell signals //////////////////////////////////////////////////
f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)=>
greenBreakout = (lastBreakout > 0) or ignoreReverseBreakout
redBreakout = (lastBreakout < 0) or ignoreReverseBreakout
buySignal = dir==-1? false : (crossover(low, upLine[1]) and greenBreakout and close > downLine[1]) or (crossover(low, stopDownLine[1]) and redBreakout)
stopBuySignal = (crossunder(dir==-1?close:low, downLine[1]) or crossunder(dir==-1?close:low, stopUpLine[1]))
sellSignal = dir==1? false : (crossunder(high, downLine[1]) and redBreakout and close < upLine[1]) or (crossunder(high, stopUpLine[1]) and greenBreakout)
stopSellSignal = (crossover(dir==1?close:high, upLine[1]) or crossover(dir==1?close:high, stopDownLine[1]))
[buySignal,stopBuySignal,sellSignal,stopSellSignal]
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
[newHigh,newLow]
//////////////////////////////////// Calculate Trade Flags /////////////////////////////////////////////////////
f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)=>
buyPrerequisites = inDateRange and yearlyHighCondition and newHigh and maHigh
sellPrerequisites = inDateRange and yearlyLowCondition and newLow and maLow
buyEntry = buyPrerequisites? (dir == -1 and barState != 0) ? true : buySignal : false
sellEntry = sellPrerequisites? dir == 1 and barState != 0 ? true : sellSignal : false
stopBuyEntry = stopBuySignal and barState != 1 and inDateRange
stopSellEntry = stopSellSignal and barState != -1 and inDateRange
reverse = (buySignal or sellSignal and (buyPrerequisites or sellPrerequisites)) and (tradeType == "all" or tradeType == "reverse")
breakout = ((buyPrerequisites and dir == -1 and barState == 1) or (sellPrerequisites and dir == 1 and barState == -1)) and (tradeType == "all" or tradeType == "breakout" or tradeType == "pullback + breakout")
pullback = ((buyPrerequisites and dir == -1 and barState == -1) or (sellPrerequisites and dir == 1 and barState == 1)) and (tradeType == "all" or tradeType == "pullback" or tradeType == "pullback + breakout")
[buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse]
//////////////////////////////////// Calculate trailing stop //////////////////////////////////////////////////
f_calculateTrailingStop(stop)=>
strategy.position_size > 0? (stop > stop[1]? stop : stop[1]) : strategy.position_size < 0 ? (stop < stop[1]? stop : stop[1]) : stop
//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////
f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)=>
target = reverse ? close: breakout and buyEntry ? upLine : breakout and sellEntry? downLine: buyEntry and pullback ? stopDownLine : sellEntry and pullback? stopUpLine : strategy.position_size > 0 ? low : strategy.position_size < 0? high : close
buyStop = target - (stopMultiplyer * atr)
sellStop = target + (stopMultiplyer * atr)
range = false
range := range[1] and exitOnBB? close > buyStop[1] and close < sellStop[1]:strategy.position_size != 0 and buyStop[1] == buyStop[rangeBars+1] and sellStop[1] == sellStop[rangeBars+1]
if(range and exitOnBB)
buyStop := buyStop[1]
sellStop := sellStop[1]
else if(barState > 0 or strategy.position_size > 0)
buyStop := target - (stopMultiplyer * atr)
sellStop := target + (compoundMultiplyer * atr)
buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop
sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]): (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop
else if(barState < 0 or strategy.position_size < 0)
buyStop := target - (compoundMultiplyer * atr)
sellStop := target + (stopMultiplyer * atr)
sellStop := range and exitOnTrailingStopWhenInRange? min(sellStop, sellStop[1]) : (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop
buyStop := range and exitOnTrailingStopWhenInRange? max(buyStop, buyStop[1]): (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop
[target, buyStop, sellStop, range]
//////////////////////////////////// Draw Lines with labels //////////////////////////////////////////////////
f_drawLinesWithLabels(target, lbl, linecolor)=>
line_x1 = time+(60*60*24*1000*1)
line_x2 = time+(60*60*24*1000*7)
label_x = time+(60*60*24*1000*4)
targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time)
targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal)
[targetLine,targetLabel]
//////////////////////////////////// Delete Lines with labels //////////////////////////////////////////////////
f_deleteLinesWithLabels(targetLine, targetLabel, last)=>
line.delete(id=last?targetLine[1]:targetLine)
label.delete(id=last?targetLabel[1]:targetLabel)
/////////////////////////////////////////////////// Calculate Trend //////////////////////////////////////////////////////
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
[showTargets,showChannel,showTargetStops,showUpChannel,showDownChannel] = f_getDisplayModeVeriables(displayMode)
vma = f_getMovingAverage(volume, volumeMaType, volumelength)
vmareverse = f_getMovingAverage(volume, volumeMaType, reverseVolumeLength)
[superTrend, dir] = supertrend(supertrendMult, supertrendLength)
atr = atr(atrlength)
[trendBreakout, reverseBreakout, highBreakout] = f_getPriceBreakout(atr, trendTargetMult, reverseTargetMult, considerOpenCloseBreakout, highBreakoutMult)
[trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout] = f_getVolumeBreakout(vma, vmareverse, trendVolumeMarkup, reverseVolumeMarkup, highVolumeMultiplyer)
barState = f_getBarState(dir,trendBreakout, reverseBreakout, highBreakout, trendVolumeBreakout, reverseVolumeBreakout, highVolumeBreakout)
[upTarget,stopUpTarget,downTarget,stopDownTarget, lastBreakout] = f_getTargets(barState, trendValueMarkup, reverseValueMarkup, stopMultFactor, dir, atr)
[upLine,stopUpLine,downLine,stopDownLine] = f_getChannels(upTarget, stopUpTarget, downTarget, stopDownTarget)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
alignedMaIndex = sum(maAlignment,LookbackPeriod)
maHigh = alignedMaIndex > alignmentIndexThreshold or not considerMaAlignment
maLow = alignedMaIndex < -alignmentIndexThreshold or not considerMaAlignment
[newHigh, newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
[supertrendMa, ma, dirMa] = f_supertrendOnMa(source, MaTypeMa, MaLengthMa, supertrendLengthMa, supertrendMultMa)
//////////////////////////////////////// Calculate Trade //////////////////////////////////////////////////////
[exitOnSignalWhenInRange, exitOnTrailingStopWhenInRange, exitOnBB] = f_getRangeExitStrategy(exitStrategyOnRangingCondition)
[buySignal,stopBuySignal,sellSignal,stopSellSignal] = f_calculateSignals(dir,lastBreakout,ignoreReverseBreakout, upLine, stopUpLine, downLine, stopDownLine)
[buyEntry, sellEntry, stopBuyEntry, stopSellEntry, breakout, pullback, reverse] = f_calculateTradeFlags(dir, barState, buySignal, stopBuySignal, sellSignal, stopSellSignal, yearlyHighCondition, yearlyLowCondition, inDateRange, tradeType, newHigh, maHigh, newLow, maLow)
[target, buyStop, sellStop, range] = f_calculateStopAndCompound(buyEntry, sellEntry, breakout, pullback, reverse, upLine, stopUpLine, downLine, stopDownLine, atr, stopMultiplyer, compoundMultiplyer, barState, exitOnTrailingStopWhenInRange, exitOnBB)
//crossedCompound = (strategy.position_size > 0 ? strategy.position_avg_price < buyStop : strategy.position_size < 0 ? strategy.position_avg_price > sellStop : true) or allowImmediateCompound
crossedCompound = (strategy.position_size > 0 ? close > sellStop : strategy.position_size < 0 ? close < buyStop : true) or allowImmediateCompound
percentRank = percentrank(source, LookbackPeriodPR)
[SupertrendW, DirW] = security(syminfo.tickerid, 'W', supertrend(SupertrendWMult, SupertrendWPd), lookahead = true)
[SupertrendM, DirM] = security(syminfo.tickerid, 'M', supertrend(SupertrendMMult, SupertrendMPd), lookahead = true)
buyEntry := buyEntry and (((dirMa == 1 or not considerMaSupertrend) and percentRank > 50) or strategy.netprofit >= 0) and (DirW == -1 or not considerWeeklySupertrend) and (DirM == -1 or not considerMonthlySupertrend)
sellEntry := sellEntry and (((dirMa == -1 or not considerMaSupertrend) and percentRank < 50) or strategy.netprofit >= 0) and (DirW == 1 or not considerWeeklySupertrend) and (DirM == 1 or not considerMonthlySupertrend)
[middle, upper, lower] = bb(close, 100, 2.5)
rangeBuyEntry = range and crossover(close, lower) and exitOnBB
rangeSellEntry = range and crossunder(close, upper) and exitOnBB
//////////////////////////////////////// Plot //////////////////////////////////////////////////////
plot(showChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showChannel?downLine:na, title="downChannel", color=color.red, linewidth=2, style=plot.style_line)
plotshape(showTargets or showTargetStops?upTarget:na, title="UpTarget", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)
plotshape(showTargets or showTargetStops?downTarget:na, title="DownTarget", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)
plotshape(showTargetStops?stopUpTarget:na, title="UpStop", color=color.green, style=shape.arrowup, location = location.absolute, size=size.tiny)
plotshape(showTargetStops?stopDownTarget:na, title="DownStop", color=color.red, style=shape.arrowdown, location = location.absolute, size=size.tiny)
plot(showUpChannel?upLine:na, title="UpChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showUpChannel?stopUpLine:na, title="StopUpChannel", color=color.red, linewidth=2, style=plot.style_line)
plot(showDownChannel?stopDownLine:na, title="StopDownChannel", color=color.green, linewidth=2, style=plot.style_line)
plot(showDownChannel?downLine:na, title="DownChannel", color=color.red, linewidth=2, style=plot.style_line)
channelview = showChannel or showUpChannel or showDownChannel
buyStopLineColor = range ? color.purple : strategy.position_size > 0 ?color.red:strategy.position_size < 0 ?color.green:color.blue
sellStopLineColor = range ? color.purple : strategy.position_size > 0?color.green:strategy.position_size < 0 ?color.red:color.blue
showStopCompound = showTrailingStop and (range or strategy.position_size != 0) and not channelview
plot(showStopCompound? buyStop : na, title="DownStop", color=buyStopLineColor, linewidth=2, style=plot.style_stepline)
plot(showStopCompound? sellStop : na, title="UpStop", color=sellStopLineColor, linewidth=2, style=plot.style_stepline)
barcolor(barState==1?color.lime:barState==-1?color.orange:color.silver)
//////////////////////////////////////// Plot Trade //////////////////////////////////////////////////////
if(buyEntry or sellEntry) and (showTargetLevels) and (breakout or pullback or reverse)
[targetLine, targetLabel] = f_drawLinesWithLabels(target,buyEntry?"Long":"Short",color.blue)
if(not showPreviousLevels)
f_deleteLinesWithLabels(targetLine, targetLabel, true)
if(buyEntry or sellEntry or strategy.position_size != 0)
[stopLine, stopLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?buyStop:sellStop,"Stop",color.red)
[compoundLine, compoundLabel] = f_drawLinesWithLabels(buyEntry or strategy.position_size > 0?sellStop:buyStop,"Compound",color.green)
f_deleteLinesWithLabels(stopLine, stopLabel, true)
f_deleteLinesWithLabels(compoundLine, compoundLabel, true)
//////////////////////////////////////// Trade //////////////////////////////////////////////////////
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.entry("Buy", strategy.long, when=buyEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.entry("Buy", strategy.long, when=rangeBuyEntry, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.close("Buy", when=(stopBuyEntry and (exitOnSignal or (exitOnSignalWhenInRange and range))) or rangeSellEntry)
strategy.exit("ExitBuy", "Buy", stop = buyStop)
strategy.entry("Sell", strategy.short, when=sellEntry and reverse and crossedCompound and (not range or not exitOnBB), oca_name="oca_sell", oca_type=strategy.oca.cancel)
strategy.entry("Sell", strategy.short, when=sellEntry and (breakout or pullback) and crossedCompound and (not range or not exitOnBB), stop=target, oca_name="oca_sell", oca_type=strategy.oca.cancel)
strategy.close("Sell", when=stopSellEntry and (exitOnSignal or (exitOnSignalWhenInRange and range)))
strategy.exit("ExitSell", "Sell", stop = sellStop)
|
EMA_HMA_RSI_Strategy | https://www.tradingview.com/script/PZ5MpxP1-EMA-HMA-RSI-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 209 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="EMA_HMA_RSI_Strategy", overlay=true, pyramiding=2, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
//longCondition = crossover(sma(close, 14), sma(close, 28))
//if (longCondition)
//strategy.entry("My Long Entry Id", strategy.long)
//shortCondition = crossunder(sma(close, 14), sma(close, 28))
//if (shortCondition)
// strategy.entry("My Short Entry Id", strategy.short)
//HMA
HMA(src1, length1) => wma(2 * wma(src1, length1/2) - wma(src1, length1), round(sqrt(length1)))
var stopLossVal=0.00
//variables BEGIN
length=input(200,title="EMA and HMA Length") //square root of 13
rsiLength=input(13, title="RSI Length")
takePartialProfits = input(true, title="Take Partial Profits (if this selected, RSI 13 higher reading over 80 is considered for partial closing ) ")
stopLoss = input(title="Stop Loss%", defval=8, minval=1)
//variables END
//RSI
rsi13=rsi(close,rsiLength)
ema200=ema(close,length)
hma200=HMA(close,length)
//exitOnAroonOscCrossingDown = input(true, title="Exit when Aroon Osc cross down zero ")
// Drawings
//Aroon oscillator
arronUpper = 100 * (highestbars(high, length+1) + length)/length
aroonLower = 100 * (lowestbars(low, length+1) + length)/length
aroonOsc = arronUpper - aroonLower
aroonMidpoint = 0
//oscPlot = plot(aroonOsc, color=color.green)
//midLine= plot(aroonMidpoint, color=color.green)
//topLine = plot(90,style=plot.style_circles, color=color.green)
//bottomLine = plot(-90,style=plot.style_circles, color=color.red)
//fill(oscPlot, midLine, color=aroonOsc>0?color.green:color.red, transp=50)
//fill(topLine,bottomLine, color=color.blue)
//fill(topLine,oscPlot, color=aroonOsc>90?color.purple:na, transp=25)
// RSI
//plot(rsi13, title="RSI", linewidth=2, color=color.purple)
//hline(50, title="Middle Line", linestyle=hline.style_dotted)
//obLevel = hline(80, title="Overbought", linestyle=hline.style_dotted)
//osLevel = hline(30, title="Oversold", linestyle=hline.style_dotted)
//fill(obLevel, osLevel, title="Background", color=rsi13 >=30 ? color.green:color.purple, transp=65) // longTermRSI >=50
hullColor = hma200 > hma200[2] ? #00ff00 : #ff0000
plot(hma200, title="HULL 200", color=hullColor, transp=25)
plot(ema200, title="EMA 200", color=color.orange)
//Entry--
strategy.entry(id="Long Entry", comment="LE", qty=(strategy.initial_capital * 0.10)/close, long=true, when=strategy.position_size<1 and hma200 < ema200 and hma200 > hma200[2] and rsi13<70 ) // // aroonOsc<0
//Add
if(strategy.position_size>=1 and close < strategy.position_avg_price and ( crossover(rsi13,30) or crossover(rsi13,40) ) ) // hma200 < ema200 and hma200 > hma200[2] and hma200[2] < hma200[3] ) //and crossover(rsi13,30) aroonOsc<0 //and hma200 > hma200[2] and hma200[2] <= hma200[3] //crossover(rsi13,30)
qty1=(strategy.initial_capital * 0.10)/close
//stopLossVal:= abs(strategy.position_size)>1 ? ( (close > close[1] and close > open and close>strategy.position_avg_price) ? close[1]*(1-stopLoss*0.01) : stopLossVal ) : 0.00
strategy.entry(id="Long Entry", comment="Add", qty=qty1, long=true ) //crossover(close,ema34) //and close>ema34 //crossover(rsi5Val,rsiBuyLine) -- SL="+tostring(stopLossVal, "####.##")
//stopLossVal:= abs(strategy.position_size)>1 ? strategy.position_avg_price*(1-0.5) : 0.00
stopLossVal:= abs(strategy.position_size)>1 ? ( (close > close[1] and close > open and close>strategy.position_avg_price) ? close[1]*(1-stopLoss*0.01) : stopLossVal ) : 0.00
//stopLossVal:= abs(strategy.position_size)>1 ? strategy.position_avg_price*(1-stopLoss*0.01) : 0.00
barcolor(color=strategy.position_size>=1? rsi13>80 ? color.purple: color.blue:na)
//close partial
if(takePartialProfits==true)
strategy.close(id="Long Entry", comment="Partial X points="+tostring(close - strategy.position_avg_price, "####.##"), qty_percent=20 , when=abs(strategy.position_size)>=1 and crossunder(rsi13, 80) and close > strategy.position_avg_price ) //close<ema55 and rsi5Val<20 //ema34<ema55
//close All
//if(exitOnAroonOscCrossingDown)
// strategy.close(id="Long Entry", comment="Exit All points="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size)>=1 and crossunder(aroonOsc, 0) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
//close All on stop loss
strategy.close(id="Long Entry", comment="Stoploss X points="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size)>=1 and close < stopLossVal ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
strategy.close(id="Long Entry", comment="hmaXema X points="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size)>=1 and close > strategy.position_avg_price and crossunder(hma200,ema200) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
|
TEMA/DEMA/HMA Strategy | https://www.tradingview.com/script/rlhozhjZ-TEMA-DEMA-HMA-Strategy/ | Tuned_Official | https://www.tradingview.com/u/Tuned_Official/ | 48 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tuned-com
//@version=4
strategy("TEMA/DEMA/HMA", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000000, commission_type=strategy.commission.percent, commission_value=0.1)
Tlength = input(8, title="TEMA Length", minval=1)
Dlength = input(43, title="DEMA Length", minval=1)
Hlength = input(52, title="Hull Length", minval=1)
Rlength = input(2, title="Hull Trend Test Length", minval=1)
//TEMA//
ema1 = ema(close, Tlength)
ema2 = ema(ema1, Tlength)
ema3 = ema(ema2, Tlength)
tema = 3 * (ema1 - ema2) + ema3
//DEMA//
e1 = ema(close, Dlength)
e2 = ema(e1, Dlength)
dema = 2 * e1 - e2
//HMA//
hma = wma(2 * wma(close, Hlength / 2) - wma(close, Hlength), round(sqrt(Hlength)))
up = crossunder(dema, tema) and rising(hma, Rlength)
down = crossover(dema, tema) and falling(hma, Rlength)
downc = crossunder(dema, tema)
upc = crossover(dema, tema)
plot(dema, color=color.green, linewidth=2)
plot(tema, color=color.aqua, linewidth=2)
plot(hma, color=rising(hma, Rlength) ? color.green : na, linewidth=2, transp=0)
plot(hma, color=falling(hma, Rlength) ? color.red : na, linewidth=2, transp=0)
bgcolor(rising(hma, Rlength) ? color.green : na, transp=70)
bgcolor(falling(hma, Rlength) ? color.red : na, transp=70)
plotarrow(tema - dema, colorup=color.green, colordown=color.red, transp=70)
if up
strategy.entry("Long Entry", strategy.long)
if down
strategy.entry("Short Entry", strategy.short) |
[Strategy] Simple Golden Cross | https://www.tradingview.com/script/U4fO0okX-Strategy-Simple-Golden-Cross/ | CJDeegan | https://www.tradingview.com/u/CJDeegan/ | 42 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CJDeegan
//@version=4
strategy(title = "[LIVE] Golden Cross", overlay=true, initial_capital=400, default_qty_type=strategy.percent_of_equity, default_qty_value=10, currency="USD")
// ------------Functions------------
//Percent to Decimal Conversion
perToDec(a) => a * 0.01
//Price Difference to Tick
diffToTick(a,b) => (a - b) / syminfo.mintick
// ------------Strategy Inputs------------
takeProfitInput = input(300, "Take Profit Price (% Gain)")
stopLossInput = input(25, "Stop Loss (% Loss)")
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2018, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer,
defval=1, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=1, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2021, minval=1800, maxval=2100)
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// ------------Populate Indicators------------
//EMA
sma50 = sma(close,50)
sma100 = sma(close,100)
sma200 = sma(close,200)
// ------------Entry Logic------------
//Guards
entryGuard = true
//Triggers
entryTrigger = crossover(sma50,sma100)
//Conditions
entryCondition = entryGuard and entryTrigger
//Calculations
//Execution
if (inDateRange and entryCondition)
strategy.entry("Long", strategy.long, when = entryCondition, comment = "Entry")
//------------Exit Logic------------
//Guards
//Triggers
exitTrigger = crossunder(sma50,sma100) or close < sma100 or crossunder(sma100,sma200)
//Conditions
exitCondition = exitTrigger
//Calculations
//Take Profit
takeProfitPrice = strategy.position_avg_price + (strategy.position_avg_price * perToDec(takeProfitInput))
//Take Profit Ticks
takeProfitTicks = diffToTick(takeProfitPrice, strategy.position_avg_price)
//StopLoss
stopLossPrice = strategy.position_avg_price - (strategy.position_avg_price * perToDec(stopLossInput))
//Execution
if (inDateRange)
strategy.close("Long", when = exitCondition, comment = "Sell Trigger")
strategy.exit("Exit", "Long", comment="Stop", profit=takeProfitTicks, stop=stopLossPrice)
//Plots
plot(sma50, "SMA 50", color = color.blue)
plot(sma100, "SMA 100", color = color.green)
plot(sma200, "SMA 200", color = color.yellow)
entry = plot(strategy.position_size <= 0 ? na : strategy.position_avg_price, "Entry Price", color = color.yellow, style = plot.style_linebr)
profit = plot(strategy.position_size <= 0 ? na : takeProfitPrice, "Take Profit (Price)", color = color.green, style = plot.style_linebr)
stop = plot(strategy.position_size <= 0 ? na : stopLossPrice, "Stop Loss", color = color.red, style = plot.style_linebr)
fill(entry,profit, color=color.green)
fill(entry,stop, color=color.red)
|
TrendMaAlignmentStrategy - Long term trades | https://www.tradingview.com/script/HbdQiDfb-TrendMaAlignmentStrategy-Long-term-trades/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 164 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("TrendMaAlignmentStrategy", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)
MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
LookbackPeriod = input(5, step=10)
shortHighLowPeriod = input(10, step=10)
longHighLowPeriod = input(20, step=10)
atrlength=input(22)
stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)
compoundMultiplyer = input(1, minval=1, maxval=10, step=0.5)
reentryStopMultiplyer = input(3, minval=1, maxval=10, step=0.5)
exitOnSignal = input(false)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
backtestYears = input(10, minval=1, step=1)
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
includePartiallyAligned = true
considerYearlyHighLow = true
considerNewLongTermHighLows = true
//////////////////////////////////// Get Moving average ///////////////////////////////////
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
f_getMaAlignmentHighLow(MAType, includePartiallyAligned, LookbackPeriod)=>
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
[highest(maAlignment, LookbackPeriod), lowest(maAlignment, LookbackPeriod)]
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
[newHigh,newLow]
//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////
f_calculateStopAndCompound(target, atr, stopMultiplyer, compoundMultiplyer, barState)=>
buyStop = target - (stopMultiplyer * atr)
sellStop = target + (stopMultiplyer * atr)
if(barState > 0 or strategy.position_size > 0)
buyStop := target - (stopMultiplyer * atr)
sellStop := target + (compoundMultiplyer * atr)
buyStop := (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop
sellStop := (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop
else if(barState < 0 or strategy.position_size < 0)
buyStop := target - (compoundMultiplyer * atr)
sellStop := target + (stopMultiplyer * atr)
sellStop := (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop
buyStop := (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop
[buyStop, sellStop]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
[yearlyHighCondition,yearlyLowCondition]
atr = atr(atrlength)
[maAlignmentHigh, maAlignmentLow] = f_getMaAlignmentHighLow(MAType, includePartiallyAligned, LookbackPeriod)
[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
[middle, upper, lower] = bb(close, 20, 2)
barState = (maAlignmentLow > 0 or maAlignmentHigh == 1) and newHigh ? 1 : (maAlignmentHigh < 0 or maAlignmentLow == -1) and newLow ? -1 : 0
[buyStop, sellStop] = f_calculateStopAndCompound(close, atr, stopMultiplyer, compoundMultiplyer, barState)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
barcolor(barState == 1?color.lime : barState == -1? color.orange: color.silver)
plot(barState == 1 or strategy.position_size != 0 ?buyStop:na, title="BuyStop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(barState == -1 or strategy.position_size != 0 ?sellStop:na, title="SellStop", color=color.green, linewidth=2, style=plot.style_linebr)
buyEntry = barState == 1 and close - reentryStopMultiplyer*atr > buyStop and yearlyHighCondition and inDateRange
sellEntry = barState == -1 and close + reentryStopMultiplyer*atr < sellStop and yearlyLowCondition and inDateRange
buyExit = barState == -1
sellExit = barState == 1
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyEntry)
strategy.close("Buy", when=buyExit and exitOnSignal)
strategy.exit("ExitBuy", "Buy", stop = buyStop)
strategy.entry("Sell", strategy.short, when=sellEntry)
strategy.close("Sell", when=sellExit and exitOnSignal)
strategy.exit("ExitSell", "Sell", stop = sellStop) |
VWAP + Fibo Dev Extensions Strategy | https://www.tradingview.com/script/EaBACrDi/ | Mysteriown | https://www.tradingview.com/u/Mysteriown/ | 3,545 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mysteriown
//@version=4
strategy(title="VWAP + Fibo Dev Extensions Strategy", overlay=true, pyramiding=5, commission_value=0.08)
// -------------------------------------
// ------- Inputs Fibos Values ---------
// -------------------------------------
fib1 = input(title="Fibo extension 1", type=input.float, defval=1.618)
fib2 = input(title="Fibo extension 2", type=input.float, defval=2.618)
reso = input(title="Resolution VWAP", type=input.resolution, defval="W")
dev = input(title="Deviation value min.", type=input.integer, defval=150)
// -------------------------------------
// -------- VWAP Calculations ----------
// -------------------------------------
t = time(reso)
debut = na(t[1]) or t > t[1]
addsource = hlc3 * volume
addvol = volume
addsource := debut ? addsource : addsource + addsource[1]
addvol := debut ? addvol : addvol + addvol[1]
VWAP = addsource / addvol
sn = 0.0
sn := debut ? sn : sn[1] + volume * (hlc3 - VWAP[1]) * (hlc3 - VWAP)
sd = sqrt(sn / addvol)
Fibp2 = VWAP + fib2 * sd
Fibp1 = VWAP + fib1 * sd
Fibm1 = VWAP - fib1 * sd
Fibm2 = VWAP - fib2 * sd
// -------------------------------------
// -------------- Plots ----------------
// -------------------------------------
plot(VWAP, title="VWAP", color=color.orange)
pFibp2 = plot(Fibp2, color=color.red)
pFibp1 = plot(Fibp1, color=color.red)
pFibm1 = plot(Fibm1, color=color.lime)
pFibm2 = plot(Fibm2, color=color.lime)
fill(pFibp2,pFibp1, color.red)
fill(pFibm2,pFibm1, color.lime)
// -------------------------------------
// ------------ Positions --------------
// -------------------------------------
bull = crossunder(low[1],Fibm1[1]) and low[1]>=Fibm2[1] and low>Fibm2 and low<Fibm1 and sd>dev
bear = crossover(high[1],Fibp1[1]) and high[1]<=Fibp2[1] and high<Fibp2 and high>Fibp1 and sd>dev
//plotshape(bear, title='Bear', style=shape.triangledown, location=location.abovebar, color=color.red, offset=0)
//plotshape(bull, title='Bull', style=shape.triangleup, location=location.belowbar, color=color.green, offset=0)
// -------------------------------------
// --------- Strategy Orders -----------
// -------------------------------------
strategy.entry("Long", true, when = bull)
strategy.close("Long", when = crossover(high,VWAP) or crossunder(low,Fibm2))
strategy.entry("Short", false, when = bear)
strategy.close("Short", when = crossunder(low,VWAP) or crossover(high,Fibp2)) |
Aroon Oscillator Strategy | https://www.tradingview.com/script/Kh6czPWr-Aroon-Oscillator-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 279 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="Aroon Oscillator Strategy", overlay=false, pyramiding=2, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
var stopLossVal=0.00
//variables BEGIN
aroonLength=input(169,title="Aroon Length") //square root of 13
rsiLength=input(13, title="RSI Length")
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
//variables END
//RSI
rsi13=rsi(close,rsiLength)
fastEma1=ema(close,5)
ema13=ema(close,13)
ema169=ema(close,169)
exitOnAroonOscCrossingDown = input(true, title="Exit when Aroon Osc cross down zero ")
// Drawings
//Aroon oscillator
arronUpper = 100 * (highestbars(high, aroonLength+1) + aroonLength)/aroonLength
aroonLower = 100 * (lowestbars(low, aroonLength+1) + aroonLength)/aroonLength
aroonOsc = arronUpper - aroonLower
aroonMidpoint = 0
oscPlot = plot(aroonOsc, color=color.green)
midLine= plot(aroonMidpoint, color=color.green)
topLine = plot(90,style=plot.style_circles, color=color.green)
bottomLine = plot(-90,style=plot.style_circles, color=color.red)
fill(oscPlot, midLine, color=aroonOsc>0?color.green:color.red, transp=50)
fill(topLine,bottomLine, color=color.blue)
fill(topLine,oscPlot, color=aroonOsc>90?color.purple:na, transp=25)
// RSI
//plot(rsi13, title="RSI", linewidth=2, color=color.purple)
//hline(50, title="Middle Line", linestyle=hline.style_dotted)
//obLevel = hline(80, title="Overbought", linestyle=hline.style_dotted)
//osLevel = hline(30, title="Oversold", linestyle=hline.style_dotted)
//fill(obLevel, osLevel, title="Background", color=rsi13 >=30 ? color.green:color.purple, transp=65) // longTermRSI >=50
//Entry--
strategy.entry(id="Long Entry", comment="LE", qty=(strategy.initial_capital * 0.10)/close, long=true, when= crossover(aroonOsc,0) ) //crossover(close,ema34) //and close>ema34 //crossover(rsi5Val,rsiBuyLine)
//Add
if(strategy.position_size>=1 and aroonOsc>0 and close < strategy.position_avg_price and crossover(rsi13,30))
qty1=(strategy.initial_capital * 0.30)/close
stopLossVal:= abs(strategy.position_size)>1 ? ( (close > close[1] and close > open and close>strategy.position_avg_price) ? close[1]*(1-stopLoss*0.01) : stopLossVal ) : 0.00
//stopLossVal:= abs(strategy.position_size)>1 ? strategy.position_avg_price*(1-stopLoss*0.01) : 0.00
strategy.order(id="Long Entry", comment="Add SL="+tostring(stopLossVal, "####.##"), qty=qty1, long=true ) //crossover(close,ema34) //and close>ema34 //crossover(rsi5Val,rsiBuyLine) --
//stopLossVal:= abs(strategy.position_size)>1 ? strategy.position_avg_price*(1-0.5) : 0.00
stopLossVal:= abs(strategy.position_size)>1 ? ( (close > close[1] and close > open and close>strategy.position_avg_price) ? close[1]*(1-stopLoss*0.01) : stopLossVal ) : 0.00
//stopLossVal:= abs(strategy.position_size)>1 ? strategy.position_avg_price*(1-stopLoss*0.01) : 0.00
barcolor(color=strategy.position_size>=1? aroonOsc>90 ? color.purple: color.blue:na)
//close partial
strategy.close(id="Long Entry", comment="Partial X SL="+tostring(stopLossVal, "####.##"), qty=strategy.position_size/5, when=abs(strategy.position_size)>=1 and crossunder(aroonOsc, 90) ) //close<ema55 and rsi5Val<20 //ema34<ema55
//strategy.close(id="Long Entry", comment="Partial X SL="+tostring(stopLossVal, "####.##"), qty=strategy.position_size/3, when=abs(strategy.position_size)>=1 and ( (close - ema169) > ema169*0.10 ) and crossunder(close,ema13)) //close<ema55 and rsi5Val<20 //ema34<ema55
//close All
if(exitOnAroonOscCrossingDown)
strategy.close(id="Long Entry", comment="Exit All", when=abs(strategy.position_size)>=1 and crossunder(aroonOsc, 0) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
//close All on stop loss
if(not exitOnAroonOscCrossingDown)
strategy.close(id="Long Entry", comment="Stoploss X", when=abs(strategy.position_size)>=1 and close < stopLossVal ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
|
Cross impro test by Canundo Crossover Crossunder Tick values | https://www.tradingview.com/script/VgMPO0Wu-Cross-impro-test-by-Canundo-Crossover-Crossunder-Tick-values/ | Canundo | https://www.tradingview.com/u/Canundo/ | 93 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Canundo
//@version=4
strategy("Cross impro test by Canundo", overlay=true)
//Run on 1 min chart for better testing cases where x and y of crossover have the same value.
EnableStrictCross = input(title="Enable Strict Cross (rounds SMA to pips/ticks), otherwise standard", type=input.bool, defval=true) //Disable to see differences
BacktestTradeCandleCount = input(title="Backtest Trade Candle Count", type=input.integer, defval=3000) //Avoid error for too many trades
MinTick = input(title="Change mintick for Cross Check (0 = Standard Tick/Pip, Chose pips like 0.5, 10, 100, 0.002)",
type=input.float, defval=0) //Precision of round to pip function
SpreadBetween = input(title="Add spread between values to be crossed.",
type=input.float, defval=0)
//Calculate Timeframe for Backtest demonstration
starttime = 0, starttime := starttime[1] != 0 ? starttime[1] : timenow
timeFrame = (time_close - time_close[1]) * BacktestTradeCandleCount
f_tWindow() => time >= starttime - timeFrame ? true : false
//Rounding function
mult = 1 / (MinTick == 0 ? syminfo.mintick : MinTick)
f_roundToPip(x)=> (x-floor(x*mult)/mult) < (ceil(x*mult)/mult-x) ? floor(x*mult)/mult : ceil(x*mult)/mult
//Very short SMA's to show the effect of crossovers und price values with more decimals than the tick has
sma1 = sma(close, 2), sma1impr = EnableStrictCross ? f_roundToPip(sma1) : sma1
sma2 = sma(close, 3), sma2impr = EnableStrictCross ? f_roundToPip(sma2) : sma2
longCondition = crossover(sma1impr - SpreadBetween/2, sma2impr + SpreadBetween/2)
if (longCondition and f_tWindow())
strategy.entry("Long", strategy.long)
shortCondition = crossunder(sma1impr + SpreadBetween/2, sma2impr - SpreadBetween/2)
if (shortCondition and f_tWindow())
strategy.entry("Short", strategy.short)
//Show changed SMA as line, show normal SMA with crosses.
plot(sma1, title="SMA1", color=color.red, linewidth=2, style=plot.style_cross)
plot(sma1impr, title="SMA1 Improved", color=color.red, linewidth=2, style=plot.style_cross)
plot(strategy.position_size < 0 ? sma1impr - SpreadBetween/2 : sma1impr + SpreadBetween/2, title="SMA1 Improved + Spread", color=color.red, linewidth=1)
plot(sma2, title="SMA2", color=color.green, linewidth=2, style=plot.style_cross)
plot(sma2impr, title="SMA2 Improved ", color=color.green, linewidth=2, style=plot.style_cross)
plot(strategy.position_size < 0 ? sma2impr + SpreadBetween : sma2impr - SpreadBetween, title="SMA2 Improved + Spread", color=color.green, linewidth=1)
plot(sma1*1000, title="sma1*1000 (Show hidden decimal values)", transp=100)
|
MACD,RSI & EMA strategy with MA+PSAR by MAM | https://www.tradingview.com/script/v3igOvQW-MACD-RSI-EMA-strategy-with-MA-PSAR-by-MAM/ | maizirul959 | https://www.tradingview.com/u/maizirul959/ | 137 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © maizirul959
//@version=4
strategy("MACD,RSI & EMA strategy with MA+PSAR by MAM", overlay=true)
//Input Data
_ema_len1 = input(5, title="EMA1 length")
_ema_len2 = input(20, title="EMA2 length")
_macd_fast = input(12, title="MACD Fast")
_macd_slow = input(26, title="MACD Slow")
_macd_signal_len = input(20, title="MACD Signal length")
//MAM add SMA
_sma_len1 = input(5, title="SMA1 Length")
_sma_len2 = input(10, title="SMA2 Length")
_sma_len3 = input(50, title="SMA3 Length")
_sma_len4 = input(200, title="SMA4 Length")
lineWidth = input(1, minval=1, title="Line width")
src = input(close, title="Source")
SMA1 = if _sma_len1 != 0
sma(src, _sma_len1)
SMA2 = if _sma_len2 != 0
sma(src, _sma_len2)
SMA3 = if _sma_len3 != 0
sma(src, _sma_len3)
SMA4 = if _sma_len4 != 0
sma(src, _sma_len4)
//__________________________________________________________________________
_rsi_len = input(14, title="RSI length")
_rsi_signal_len = input(20, title="RSI signal length")
//_________________________________________________________________________
//MAM Add PSAR
PSAR_start = input(0.02)
PSAR_increment = input(0.02)
PSAR_maximum = input(0.2)
psar = sar(PSAR_start, PSAR_increment, PSAR_maximum)
//_________________________________________________________________________
_ema1 = ema(close, _ema_len1)
_ema2 = ema(close, _ema_len2)
//_________________________________________________________________________
//MAM add SMA
//_sma1 = sma(close, _sma_len1)
//_sma2 = sma(close, _sma_len2)
//_________________________________________________________________________
_macd = ema(close, _macd_fast) - ema(close, _macd_slow)
_macd_signal = ema(_macd, _macd_signal_len)
_rsi = rsi(close, _rsi_len)
_rsi_signal = ema(_rsi, _rsi_signal_len)
//PLOT SMA
plot(SMA1, color=#B71C1C, title="SMA1", linewidth=lineWidth)
plot(SMA2, color=#FFFF00, title="SMA2", linewidth=lineWidth)
plot(SMA3, color=#5b34ff, title="SMA3", linewidth=lineWidth)
plot(SMA4, color=#d7d7d7, title="SMA4", linewidth=lineWidth)
//PLOT PSAR
//plot(psar, "ParabolicSAR", style=plot.style_cross, color=#3A6CA8)
pc = close < psar ? color.red : color.green
plot(psar, style=plot.style_cross, color=pc)
//plot(_rsi, color=color.yellow)
//plot(_rsi_signal, color=color.green)
//plot(_macd, color=color.blue)
//plot(_macd_signal, color=color.red)
longCondition = close > _ema1 and close > _ema2 and _macd > _macd_signal and _rsi > _rsi_signal and _rsi > 50 and _rsi < 70
if (longCondition)
strategy.entry("Buy",strategy.long)
shortCondition = close < _ema1 and close <_ema2 and _macd < _macd_signal and _rsi < _rsi_signal
if (shortCondition)
strategy.entry("Sell",strategy.short)
//bcol = longCondition ? color.green : shortCondition ? color.orange : na
//bgcolor(bcol)
|
Profit Maximizer PMax Strategy - Long-Short | https://www.tradingview.com/script/v6Ws9H9j-Profit-Maximizer-PMax-Strategy-Long-Short/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 634 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © melihtuna
//developer: @KivancOzbilgic
//author: @KivancOzbilgic
//stretegy converter: @crypto_melih
//@version=4
strategy("Profit Maximizer Strategy Long-Short", shorttitle="PMax-Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000, currency=currency.USD, commission_value=0, commission_type=strategy.commission.percent)
src = input(hl2, title="Source")
Periods = input(title="ATR Length", type=input.integer, defval=10)
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
mav = input(title="Moving Average Type", defval="EMA", options=["SMA", "EMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"])
length =input(10, "Moving Average Length", minval=1)
condition = input(title="Signal Type", defval="Only Crossing Signals", options=["Only Crossing Signals", "Only Price/Pmax Crossing Signals"])
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsupport = input(title="Show Moving Average?", type=input.bool, defval=true)
//showsignalsk = input(title="Show Crossing Signals?", type=input.bool, defval=true)
//showsignalsc = input(title="Show Price/Pmax Crossing Signals?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
long_short = input(defval = false, title = "Long-Short", type=input.bool)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
valpha=2/(length+1)
vud1=src>src[1] ? src-src[1] : 0
vdd1=src<src[1] ? src[1]-src : 0
vUD=sum(vud1,9)
vDD=sum(vdd1,9)
vCMO=nz((vUD-vDD)/(vUD+vDD))
VAR=0.0
VAR:=nz(valpha*abs(vCMO)*src)+(1-valpha*abs(vCMO))*nz(VAR[1])
wwalpha = 1/ length
WWMA = 0.0
WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1])
zxLag = length/2==round(length/2) ? length/2 : (length - 1) / 2
zxEMAData = (src + (src - src[zxLag]))
ZLEMA = ema(zxEMAData, length)
lrc = linreg(src, length, 0)
lrc1 = linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = linreg(src, length, 0)+lrs
getMA(src, length) =>
ma = 0.0
if mav == "SMA"
ma := sma(src, length)
ma
if mav == "EMA"
ma := ema(src, length)
ma
if mav == "WMA"
ma := wma(src, length)
ma
if mav == "TMA"
ma := sma(sma(src, ceil(length / 2)), floor(length / 2) + 1)
ma
if mav == "VAR"
ma := VAR
ma
if mav == "WWMA"
ma := WWMA
ma
if mav == "ZLEMA"
ma := ZLEMA
ma
if mav == "TSF"
ma := TSF
ma
ma
MAvg=getMA(src, length)
longStop = MAvg - Multiplier*atr
longStopPrev = nz(longStop[1], longStop)
longStop := MAvg > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = MAvg + Multiplier*atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := MAvg < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir
PMax = dir==1 ? longStop: shortStop
plot(showsupport ? MAvg : na, color=#0585E1, linewidth=2, title="Moving Avg Line")
pALL=plot(PMax, color=color.red, linewidth=2, title="PMax", transp=0)
alertcondition(cross(MAvg, PMax), title="Cross Alert", message="PMax - Moving Avg Crossing!")
alertcondition(crossover(MAvg, PMax), title="Crossover Alarm", message="Moving Avg BUY SIGNAL!")
alertcondition(crossunder(MAvg, PMax), title="Crossunder Alarm", message="Moving Avg SELL SIGNAL!")
alertcondition(cross(src, PMax), title="Price Cross Alert", message="PMax - Price Crossing!")
alertcondition(crossover(src, PMax), title="Price Crossover Alarm", message="PRICE OVER PMax - BUY SIGNAL!")
alertcondition(crossunder(src, PMax), title="Price Crossunder Alarm", message="PRICE UNDER PMax - SELL SIGNAL!")
buySignalk = crossover(MAvg, PMax)
//plotshape(buySignalk and showsignalsk ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallk = crossunder(MAvg, PMax)
//plotshape(sellSignallk and showsignalsk ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
buySignalc = crossover(src, PMax)
//plotshape(buySignalc and showsignalsc ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
sellSignallc = crossunder(src, PMax)
//plotshape(sellSignallc and showsignalsc ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0,display=display.none)
longFillColor = highlighting ? (MAvg>PMax ? color.green : na) : na
shortFillColor = highlighting ? (MAvg<PMax ? color.red : na) : na
fill(mPlot, pALL, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, pALL, title="DownTrend Highligter", color=shortFillColor)
if(condition=="Only Crossing Signals")
strategy.entry("BUY", strategy.long, when = buySignalk)
else
strategy.entry("BUY", strategy.long, when = buySignalc)
if(long_short)
if(condition=="Only Crossing Signals")
strategy.entry("SELL", strategy.short, when = sellSignallk)
else
strategy.entry("SELL", strategy.short, when = sellSignallc)
else
if(condition=="Only Crossing Signals")
strategy.close("BUY", when = sellSignallk)
else
strategy.close("BUY", when = sellSignallc)
|
Money maker EURUSD 15min daytrader | https://www.tradingview.com/script/jU2JCWZr-Money-maker-EURUSD-15min-daytrader/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 281 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("Money maker EURUSD 15min",initial_capital=1000,
commission_type=strategy.commission.cash_per_contract,
commission_value=0.000065,
slippage=3)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 8, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
len = input(3, minval=1, title="Length")
src = input(hl2, title="Source")
smma = 0.0
sma1 = sma(src, len)
smma := na(smma[1]) ? sma1 : (smma[1] * (len - 1) + src) / len
len2 = input(6, minval=1, title="Length")
src2 = input(hl2, title="Source")
smma2 = 0.0
sma2 = sma(src2, len2)
smma2 := na(smma2[1]) ? sma2 : (smma2[1] * (len2 - 1) + src2) / len2
len3 = input(9, minval=1, title="Length")
src3 = input(hl2, title="Source")
smma3 = 0.0
sma3 = sma(src3, len3)
smma3 := na(smma3[1]) ? sma3 : (smma3[1] * (len3 - 1) + src3) / len3
len4 = input(50, minval=1, title="Length")
src4 = input(close, title="Source")
smma4 = 0.0
sma4 = sma(src4, len4)
smma4 := na(smma4[1]) ? sma4 : (smma4[1] * (len4 - 1) + src4) / len4
len5 = input(200, minval=1, title="Length")
src5 = input(close, title="Source")
out5 = ema(src5, len5)
timeinrange(res, sess) => time(res, sess) != 0
london=timeinrange(timeframe.period, "0300-1045")
londonEntry=timeinrange(timeframe.period, "0300-0845")
extraEntry =timeinrange(timeframe.period, "0745-1030")
time_cond = time >= startDate and time <= finishDate and londonEntry
//time_cond2 = time >= startDate and time <= finishDate and extraEntry
//
longCond = close > out5 and close > smma4 and close > smma3 and close > smma2 and close > smma and smma > smma2 and smma2>smma3 and smma3>smma4 and smma4>out5 and time_cond
shortCond = close < out5 and close < smma4 and close < smma3 and close < smma2 and close < smma and smma < smma2 and smma2<smma3 and smma3<smma4 and smma4<out5 and time_cond
//longCond = close > out5 and close > smma4 and close > smma3 and close > smma2 and close > smma and smma > smma2 and smma2>smma3 and smma3>smma4 and smma4>out5 and time_cond2
//shortCond = close < out5 and close < smma4 and close < smma3 and close < smma2 and close < smma and smma < smma2 and smma2<smma3 and smma3<smma4 and smma4<out5 and time_cond2
//longCond2 = crossover(close,out5) and crossover(close,smma4) and crossover(close,smma3) and crossover(close,smma2) and crossover(close,smma) and time_cond
//shortCond2 = crossunder(close,out5) and crossunder(close,smma4) and crossunder(close,smma3) and crossunder(close,smma2) and crossunder(close,smma) and time_cond
tp=input(300,title="tp")
sl=input(300,title="sl")
//MONEY MANAGEMENT--------------------------------------------------------------
balance = strategy.netprofit + strategy.initial_capital //current balance
floating = strategy.openprofit //floating profit/loss
risk = input(1,type=input.float,title="Risk %")/100 //risk % per trade
//Calculate the size of the next trade
temp01 = balance * risk //Risk in USD
temp02 = temp01/sl //Risk in lots
temp03 = temp02*100000 //Convert to contracts
size = temp03 - temp03%1000 //Normalize to 1000s (Trade size)
if(size < 1000)
size := 1000 //Set min. lot size
dataL = (close-out5)*100000
dataS = (out5-close)*100000
minDistanceL = (smma4 - out5)*100000
minDistanceS= (out5 - smma4)*100000
strategy.entry("long",1,size,when=longCond )
strategy.exit("closelong","long", profit=tp,loss=sl)
strategy.entry("short",0,size,when=shortCond )
strategy.exit("closeshort","short", profit=tp,loss=sl)
strategy.close_all(when = not london, comment="london finish")
//strategy.close_all(when = not extraEntry, comment="london finish")
maxEntry=input(2,title="max entries")
strategy.risk.max_intraday_filled_orders(maxEntry)
|
Turtle Trend Trading System [racer8] | https://www.tradingview.com/script/6TnqZSoe-Turtle-Trend-Trading-System-racer8/ | racer8 | https://www.tradingview.com/u/racer8/ | 469 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © racer8
//@version=4
strategy("Turtle System", overlay=true)
n = input(55,"Entry Length")
e = input(20,"Exit Length")
HI = highest(n)
LO = lowest(n)
hi = highest(e)
lo = lowest(e)
if close>HI[1]
strategy.entry("Buy", strategy.long)
if close<LO[1]
strategy.entry("Sell", strategy.short)
if low<lo[1]
strategy.close("Buy")
if high>hi[1]
strategy.close("Sell")
plot(HI,color=color.lime)
plot(LO,color=color.red)
plot(hi,color=color.blue)
plot(lo,color=color.maroon)
|
High/low crypto strategy with MACD/PSAR/ATR/EWave | https://www.tradingview.com/script/5d1S8yhR-High-low-crypto-strategy-with-MACD-PSAR-ATR-EWave/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 183 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("Crypto strategy high/low", overlay=true)
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=true)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
//sar
start = input(0.02)
increment = input(0.02)
maximum = input(0.2)
var bool uptrend = na
var float EP = na
var float SAR = na
var float AF = start
var float nextBarSAR = na
if bar_index > 0
firstTrendBar = false
SAR := nextBarSAR
if bar_index == 1
float prevSAR = na
float prevEP = na
lowPrev = low[1]
highPrev = high[1]
closeCur = close
closePrev = close[1]
if closeCur > closePrev
uptrend := true
EP := high
prevSAR := lowPrev
prevEP := high
else
uptrend := false
EP := low
prevSAR := highPrev
prevEP := low
firstTrendBar := true
SAR := prevSAR + start * (prevEP - prevSAR)
if uptrend
if SAR > low
firstTrendBar := true
uptrend := false
SAR := max(EP, high)
EP := low
AF := start
else
if SAR < high
firstTrendBar := true
uptrend := true
SAR := min(EP, low)
EP := high
AF := start
if not firstTrendBar
if uptrend
if high > EP
EP := high
AF := min(AF + increment, maximum)
else
if low < EP
EP := low
AF := min(AF + increment, maximum)
if uptrend
SAR := min(SAR, low[1])
if bar_index > 1
SAR := min(SAR, low[2])
else
SAR := max(SAR, high[1])
if bar_index > 1
SAR := max(SAR, high[2])
nextBarSAR := SAR + AF * (EP - SAR)
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
CCI = input(20)
ATR = input(5)
Multiplier=input(1,title='ATR Multiplier')
original=input(true,title='original coloring')
thisCCI = cci(close, CCI)
lastCCI = nz(thisCCI[1])
bufferDn= high + Multiplier * sma(tr,ATR)
bufferUp= low - Multiplier * sma(tr,ATR)
if (thisCCI >= 0 and lastCCI < 0)
bufferUp := bufferDn[1]
if (thisCCI <= 0 and lastCCI > 0)
bufferDn := bufferUp[1]
if (thisCCI >= 0)
if (bufferUp < bufferUp[1])
bufferUp := bufferUp[1]
else
if (thisCCI <= 0)
if (bufferDn > bufferDn[1])
bufferDn := bufferDn[1]
x=0.0
x:=thisCCI >= 0 ?bufferUp:thisCCI <= 0 ?bufferDn:x[1]
swap=0.0
swap:=x>x[1]?1:x<x[1]?-1:swap[1]
swap2=swap==1?color.lime:color.red
swap3=thisCCI >=0 ?color.lime:color.red
swap4=original?swap3:swap2
//elliot wave
srce = input(close, title="source")
sma1length = input(5)
sma2length = input(35)
UsePercent = input(title="Show Dif as percent of current Candle", type=input.bool, defval=true)
smadif=iff(UsePercent,(sma(srce, sma1length) - sma(srce, sma2length)) / srce * 100, sma(srce, sma1length) - sma(srce, sma2length))
col=smadif <= 0 ? color.red : color.green
longC = high > high[1] and high[1] > high[2] and close[2] > high[3] and hist > 0 and uptrend and smadif < 0 and swap4==color.lime
//longC = high > high[1] and high[1] > high[2] and high[2] > high[3] and high[3] > high[4] and close[4] > high[5]
shortC = low < low[1] and low[1] < low[2] and close[2] < low[3] and hist < 0 and not uptrend and smadif > 0 and swap4==color.red
//shortC = low < low[1] and low[1] < low[2] and low[2] < low[3] and low[3] < low[4] and close[4] < low[5]
tp=input(0.15, title="tp")
sl=input(0.005, title="sl")
strategy.entry("long",1,when=longC)
strategy.entry("short",0,when=shortC)
strategy.exit("x_long", "long" ,loss = close * sl / syminfo.mintick, profit = close * tp / syminfo.mintick , alert_message = "closelong")
//strategy.entry("short",0, when= loss = close * sl / syminfo.mintick)
strategy.exit("x_short", "short" , loss = close * sl / syminfo.mintick, profit = close * tp / syminfo.mintick,alert_message = "closeshort")
//strategy.entry("long",1, when = loss = close * sl / syminfo.mintick)
//strategy.close("long",when= hist < 0)
//strategy.close("short", when= hist > 0) |
RSI on VWAP Upgraded strategy | https://www.tradingview.com/script/Q5TPHHLs/ | Mysteriown | https://www.tradingview.com/u/Mysteriown/ | 1,265 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mysteriown
//@version=4
strategy("RSI on VWAP Upgraded strategy", overlay=false, pyramiding = 4, commission_value = 0.08)
// pyramiding is the number of positions you can take before closing all of them (be carefull if using it with a trading bot)
// commission_value is the commission taken for each buy/sell
// ------------------------------------------ //
// ----------------- Inputs ----------------- //
// ------------------------------------------ //
reso = input(title="Resolution", type=input.resolution, defval="")
length = input(20, title="RSI Length", type=input.integer)
ovrsld = input(30, "RSI Oversold level", type=input.float)
ovrbgt = input(85, "RSI Overbought level", type=input.float)
lateleave = input(28, "Number of candles", type=input.integer)
// lateleave : numbers of bars in overbought/oversold zones where the position is closed. The position is closed when this number is reached or when the zone is left (the first condition).
// best parameters BTCUSDTPERP M15 : 20 / 30 / 85 / 28
stratbull = input(title="Enter longs ?", type = input.bool, defval=true)
stratbear = input(title="Enter shorts ?", type = input.bool, defval=true)
stratyear = input(2020, title = "Strategy Start Year")
stratmonth = input(1, title = "Strategy Start Month")
stratday = input(1, title = "Strategy Start Day")
stratstart = timestamp(stratyear,stratmonth,stratday,0,0)
// ------------------------------------------ //
// --------------- Laguerre ----------------- //
// ------------------------------------------ //
laguerre = input(title="Use Laguerre on RSI ?", type=input.bool, defval=false)
gamma = input(0.06, title="Laguerre Gamma")
laguerre_cal(s,g) =>
l0 = 0.0
l1 = 0.0
l2 = 0.0
l3 = 0.0
l0 := (1 - g)*s+g*nz(l0[1])
l1 := -g*l0+nz(l0[1])+g*nz(l1[1])
l2 := -g*l1+nz(l1[1])+g*nz(l2[1])
l3 := -g*l2+nz(l2[1])+g*nz(l3[1])
(l0 + 2*l1 + 2*l2 + l3)/6
// ------------------------------------------ //
// ---------------- Rsi VWAP ---------------- //
// ------------------------------------------ //
rsiV = security(syminfo.tickerid, reso, rsi(vwap(close), length))
rsiVWAP = laguerre ? laguerre_cal(rsiV,gamma) : rsiV
// ------------------------------------------ //
// ------------------ Plots ----------------- //
// ------------------------------------------ //
prsi = plot(rsiVWAP, color = rsiVWAP>ovrbgt ? color.red : rsiVWAP<ovrsld ? color.green : color.white, title="RSI on VWAP", linewidth=1, style=plot.style_line)
hline = plot(ovrbgt, color = color.gray, style=plot.style_line)
lline = plot(ovrsld, color = color.gray, style=plot.style_line)
fill(prsi,hline, color = rsiVWAP > ovrbgt ? color.red : na, transp = 30)
fill(prsi,lline, color = rsiVWAP < ovrsld ? color.green : na, transp = 30)
// ------------------------------------------ //
// ---------------- Positions --------------- //
// ------------------------------------------ //
timebull = stratbull and time > stratstart
timebear = stratbear and time > stratstart
strategy.entry("Long", true, when = timebull and crossover(rsiVWAP, ovrsld), comment="")
strategy.close("Long", when = timebull and crossover(rsiVWAP, ovrbgt)[lateleave] or crossunder(rsiVWAP, ovrbgt), comment="")
strategy.entry("Short", false, when = timebear and crossunder(rsiVWAP, ovrbgt), comment="")
strategy.close("Short", when = timebear and crossunder(rsiVWAP, ovrsld)[lateleave] or crossover(rsiVWAP, ovrsld), comment="") |
Donchian Channels System [racer8] | https://www.tradingview.com/script/Kn28VIrm-Donchian-Channels-System-racer8/ | racer8 | https://www.tradingview.com/u/racer8/ | 158 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © racer8
//@version=4
strategy("Donchian Channels System", overlay=true)
n = input(20,"Period")
hi = highest(n)
lo = lowest(n)
cl = close
mid = 0.5*(hi + lo)
if cl>hi[1]
strategy.entry("Buy", strategy.long)
if cl<lo[1]
strategy.entry("Sell", strategy.short)
if close<mid
strategy.close("Buy")
if close>mid
strategy.close("Sell")
plot(hi,color=color.blue)
plot(lo,color=color.red)
plot(mid,color=color.gray)
|
BB21_MA200_Strategy | https://www.tradingview.com/script/oeY8qqcm-BB21-MA200-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 110 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="BB9_MA200_Strategy", overlay=true, pyramiding=0, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=100, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
var stopLossVal=0.00
//var qty1=0.00
//variables BEGIN
smaLength=input(200,title="MA Length")
bbLength=input(21,title="BB Length")
bbsrc = input(close, title="BB Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
riskCapital = input(title="Risk % of capital == Based on this trade size is claculated numberOfShares = (AvailableCapital*risk/100) / stopLossPoints", defval=10, minval=1)
sma200=ema(close,smaLength)
plot(sma200, title="SMA 200", color=color.orange)
//bollinger calculation
basis = sma(bbsrc, bbLength)
dev = mult * stdev(bbsrc, bbLength)
upperBand = basis + dev
lowerBand = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
//plot bb
plot(basis, "Basis", color=color.teal, style=plot.style_circles , offset = offset)
p1 = plot(upperBand, "Upper", color=color.teal, offset = offset)
p2 = plot(lowerBand, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=color.teal, transp=95)
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//strategy.risk.max_position_size(100)
strategy.entry(id="LE", comment="LE equity="+tostring(strategy.equity ,"######.##")+" risk = " +tostring(strategy.equity * riskCapital * 0.01, "####") + " SL = " +tostring(close * stopLoss * 0.01, "####.##"), qty=qty1 , long=true, when=strategy.position_size<1 and upperBand>sma200 and lowerBand > sma200 and crossover(close, basis) ) // // aroonOsc<0 //(strategy.initial_capital * 0.10)/close
barcolor(color=strategy.position_size>=1? color.blue: na)
//partial Exit
tpVal=strategy.position_size>1 ? strategy.position_avg_price * (1+(stopLoss/100) ) : 0.00
strategy.close(id="LE", comment="Partial points="+tostring(close - strategy.position_avg_price, "####.##"), qty_percent=30 , when=abs(strategy.position_size)>=1 and close>tpVal and crossunder(lowerBand, sma200) ) //close<ema55 and rsi5Val<20 //ema34<ema55
//close All on stop loss
//stoploss
stopLossVal:= strategy.position_size>1 ? strategy.position_avg_price * (1-(stopLoss/100) ) : 0.00
strategy.close_all( comment="SL Exit points="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size)>=1 and close < stopLossVal ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89//
strategy.close_all( comment="BB9 X SMA200 points="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size)>=1 and crossunder(basis, sma200) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
|
RSI of VWAP | https://www.tradingview.com/script/OUzp2NR6-RSI-of-VWAP/ | mohanee | https://www.tradingview.com/u/mohanee/ | 679 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="RSI of VWAP", overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
rsiLength=input(14,title="RSI Length", minval=1, maxval=50)
buyLine=input(70,title="RSI Buy Line", minval=30, maxval=100)
exitLine=input(90,title="RSI Exit Line", minval=0, maxval=100)
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(5,title="Stop Loss",minval=1)
partialExit=input(true,title="Allow Partial exit / take profits")
myVwap=vwap
vwapRsi=rsi(vwap,rsiLength)
ema200=ema(close,200)
plot(ema200, title="EMA 200", color=color.orange, transp=25)
plot(myVwap, title="VWAP", color=color.purple, transp=25)
//plot(close)
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//more than 80%
strategy.entry(id="LE", comment="Entry", long=true, qty=qty1, when=crossover(vwapRsi,buyLine) and close>ema200 )
//stoploss
stopLossVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//draw initil stop loss
plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
bgcolor(strategy.position_size>=1?color.blue:na, transp=80)
if(partialExit==true)
strategy.close(id="LE",comment="TP points="+tostring(close - strategy.position_avg_price, "####.##"),qty=strategy.position_size/3, when=crossover(vwapRsi,99) ) //and close>ema200
strategy.close_all(comment="Exit All points="+tostring(close - strategy.position_avg_price, "####.##"), when=crossunder(vwapRsi,exitLine) ) //and close>ema200
//close all on stop loss
strategy.close_all(comment="Exit points="+tostring(close - strategy.position_avg_price, "####.##"), when=close<stopLossVal ) //and close>ema200
|
BNB Burn Buyer | https://www.tradingview.com/script/ZR4XAxvl-BNB-Burn-Buyer/ | pAulseperformance | https://www.tradingview.com/u/pAulseperformance/ | 37 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gammapips
// This is a compiled list of all the BNB token burns to date with TX Hash's on the BNB chain for the most recent burns
// And links to the blog posts for Burns done while BNB was still an ERC-20 Token.
// I grabbed the dates from each TX used only the days, month, and year the tx occured for this strategy.
// https://explorer.binance.org/tx/2E16FBFD0F2BA92BAFFC987F6C33918240141CA8E7E2B7D49AB88E341B8255CE
// A08063428AB6140E31333A9793A2DD462E17D6C071F5ABF4CDCE75B4ACD38188
// 5B824CC8C9DC7A838E2F02D28F68029B85BCBF02326D4AF907795B4B8844405A
// 6047184045F3F761C4E91D81E530A10AAC2887B20E26CBB41A12A0DBAD5BDC3B
// D3ED9EFA4A242BD06E667A1F5DF102BC190C9EE76F7DB8005A5633FD7D46732A
// 9B29E778EEC20E6AB0676A11E88C7CD00DFAB2849C34B6C6A3EAEE6B4E6A8C6D
// 2C976CCADB984C3538D2CF3D674C419ECA04DB296544B0F58FE87119C1AD5020
// https://binance.zendesk.com/hc/en-us/articles/360026706152-Binance-Completes-7th-Quarterly-BNB-Burn
// https://binance.zendesk.com/hc/en-us/articles/360021824592-Binance-Completes-6th-Quarterly-BNB-Burn
// https://binance.zendesk.com/hc/en-us/articles/360018044252-Binance-Completes-5th-Quarter-Token-Burn
// https://binance.zendesk.com/hc/en-us/articles/360007242192-Binance-4th-Quarter-Token-Burn
// https://binance.zendesk.com/hc/en-us/articles/360002684252-Binance-3rd-Quarterly-Token-Burn
// https://binance.zendesk.com/hc/en-us/articles/360000012892-Binance-Coin-Burn-in-2018-Winter
// https://binance.zendesk.com/hc/en-us/articles/115002205552-Binance-1st-Quarter-BNB-Burn-Event
// The strategy itself is very simple, it will buy on the day a burn happens and sell either when it hits TP or 2 weeks after the burn date.
//@version=4
strategy("BNB Burn Buyer", overlay=true, pyramiding=1, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, currency="USD")
burn1 = timestamp(2017, 10, 18, 0, 0, 0)
burn2 = timestamp(2018, 1, 15, 0, 0, 0)
burn3 = timestamp(2018, 4, 15, 0, 0, 0)
burn4 = timestamp(2018, 7, 17, 0, 0, 0)
burn5 = timestamp(2018, 10, 17, 0, 0, 0)
burn6 = timestamp(2019, 1, 16, 0, 0, 0)
burn7 = timestamp(2019, 4, 16, 0, 0, 0)
burn8 = timestamp(2019, 7, 12, 0, 0, 0)
burn9 = timestamp(2019, 10, 17, 0, 0, 0)
burn10 = timestamp(2020, 1, 18, 0, 0, 0)
burn11 = timestamp(2020, 4, 18, 0, 0, 0)
burn12 = timestamp(2020, 7, 18, 0, 0, 0)
burn13 = timestamp(2020, 10, 17, 0, 0, 0)
i_BuyBeforeBurn = input(14, "# of bars to buy before the burn day.", type=input.integer) * (time-time[1])
burndates = array.new_int(0)
f_push(_burnStamp) =>
array.push(burndates, _burnStamp-i_BuyBeforeBurn)
f_push( burn1)
f_push( burn2)
f_push( burn3)
f_push( burn4)
f_push( burn5)
f_push( burn6)
f_push( burn7)
f_push( burn8)
f_push( burn9)
f_push( burn10)
f_push( burn11)
f_push( burn12)
f_push( burn13)
i_TP = input(15.0, title="Take Profit %", type=input.float)
longTake = strategy.position_avg_price * (1 + i_TP/100)
i_TimeClose = input(2, title="# weeks after Entry to Close Long")
var int entryTime = na
if array.includes(burndates, time) and strategy.position_size == 0
entryTime := time
strategy.entry("BNB Burn", strategy.long)
timeToExit = (time-entryTime)/ 1000 / 60 / 60 / 24 / 7
strategy.close("BNB Burn", when=timeToExit >= i_TimeClose, comment="Time Expired")
strategy.close("BNB Burn", when=high>=longTake, comment="Take Profit") |
Simple and efficient MACD crypto strategy with risk management | https://www.tradingview.com/script/rMBAUANp-Simple-and-efficient-MACD-crypto-strategy-with-risk-management/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 272 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("MACD crypto strategy", overlay=true)
// Getting inputs
//fast_length = input(title="Fast Length", type=input.integer, defval=12)
//slow_length = input(title="Slow Length", type=input.integer, defval=26)
//src = input(title="Source", type=input.source, defval=close)
//signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
//sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=true)
//sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
fast_length = 12
slow_length = 26
src = input(title="Source", type=input.source, defval=close)
signal_length = 9
sma_source = true
sma_signal = false
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
longcondition = hist > 0
shortcondition = hist < 0
//sl = input(0.5, title="SL")
//tp = input(0.1, title="tp")
strategy.entry("long",1,when=longcondition)
strategy.entry("short",0,when=shortcondition)
//strategy.exit("x_long", "long" ,loss = close * sl / syminfo.mintick, profit = close * tp / syminfo.mintick , alert_message = "closelong")
//strategy.entry("short",0, when= loss = close * sl / syminfo.mintick)
//strategy.exit("x_short", "short" , loss = close * sl / syminfo.mintick, profit = close * tp / syminfo.mintick,alert_message = "closeshort")
risk = input(2, type=input.float,title="Risk percentage of BALANCE")
strategy.risk.max_intraday_loss(risk, strategy.percent_of_equity) |
AlignedMA and Cumulative HighLow Strategy | https://www.tradingview.com/script/IHvWHZHB-AlignedMA-and-Cumulative-HighLow-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 74 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("AlignedMA and Cumulative HighLow Strategy", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
MAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
includePartiallyAligned = input(true)
HighLowPeriod = input(22, minval=1,step=1)
LookbackPeriod = input(10, minval=1,step=1)
considerYearlyHighLow = input(false)
supertrendMult = input(2, minval=1, maxval=10, step=0.5)
supertrendLength = input(22, minval=1)
tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getMaAlignment(MAType, includePartiallyAligned)=>
ma5 = f_getMovingAverage(close,MAType,5)
ma10 = f_getMovingAverage(close,MAType,10)
ma20 = f_getMovingAverage(close,MAType,20)
ma30 = f_getMovingAverage(close,MAType,30)
ma50 = f_getMovingAverage(close,MAType,50)
ma100 = f_getMovingAverage(close,MAType,100)
ma200 = f_getMovingAverage(close,MAType,200)
upwardScore = 0
upwardScore := close > ma5? upwardScore+1:upwardScore
upwardScore := ma5 > ma10? upwardScore+1:upwardScore
upwardScore := ma10 > ma20? upwardScore+1:upwardScore
upwardScore := ma20 > ma30? upwardScore+1:upwardScore
upwardScore := ma30 > ma50? upwardScore+1:upwardScore
upwardScore := ma50 > ma100? upwardScore+1:upwardScore
upwardScore := ma100 > ma200? upwardScore+1:upwardScore
upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200
downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200
upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0
f_getHighLowValue(HighLowPeriod)=>
currentHigh = highest(high,HighLowPeriod) == high
currentLow = lowest(low,HighLowPeriod) == low
currentHigh?1:currentLow?-1:0
f_getDirection(Series)=>
direction = Series > Series[1] ? 1 : Series < Series[1] ? -1 : 0
direction := direction == 0? nz(direction[1],0):direction
direction
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
label_x = time+(60*60*24*1000*1)
[yearlyHighCondition,yearlyLowCondition]
maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)
alignedMaIndex = sum(maAlignment,LookbackPeriod)
maAlignmentDirection=f_getDirection(alignedMaIndex)
highLowIndex = f_getHighLowValue(HighLowPeriod)
cumulativeHighLowIndex = sum(highLowIndex,LookbackPeriod)
hlDirection = f_getDirection(cumulativeHighLowIndex)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
[superTrend, dir] = supertrend(supertrendMult, supertrendLength)
buyEntry = (dir == -1 and maAlignmentDirection == 1 and hlDirection == 1 and yearlyHighCondition)
sellEntry = (dir == 1 and maAlignmentDirection == -1 and hlDirection == -1 and yearlyLowCondition)
barColor = buyEntry?color.lime:sellEntry?color.orange:color.gray
barcolor(barColor)
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=barColor == color.lime and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)
strategy.close("Buy", when=dir == 1)
strategy.entry("Sell", strategy.short, when=barColor == color.orange and inDateRange, oca_name="oca_sell", oca_type=strategy.oca.none)
strategy.close("Sell", when=dir == -1)
|
PMax Explorer STRATEGY & SCREENER | https://www.tradingview.com/script/nHGK4Qtp/ | KivancOzbilgic | https://www.tradingview.com/u/KivancOzbilgic/ | 13,256 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KivancOzbilgic
//developer: KivancOzbilgic
//author: KivancOzbilgic
//@version=4
strategy("PMax Explorer", shorttitle="PMEx", overlay=true)
src = input(hl2, title="Source")
Periods = input(title="ATR Length", type=input.integer, defval=10)
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
mav = input(title="Moving Average Type", defval="EMA", options=["SMA", "EMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"])
length =input(10, "Moving Average Length", minval=1)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsupport = input(title="Show Moving Average?", type=input.bool, defval=true)
showsignalsk = input(title="Show Crossing Signals?", type=input.bool, defval=true)
showsignalsc = input(title="Show Price/Pmax Crossing Signals?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
Var_Func(src,length)=>
valpha=2/(length+1)
vud1=src>src[1] ? src-src[1] : 0
vdd1=src<src[1] ? src[1]-src : 0
vUD=sum(vud1,9)
vDD=sum(vdd1,9)
vCMO=nz((vUD-vDD)/(vUD+vDD))
VAR=0.0
VAR:=nz(valpha*abs(vCMO)*src)+(1-valpha*abs(vCMO))*nz(VAR[1])
VAR=Var_Func(src,length)
Wwma_Func(src,length)=>
wwalpha = 1/ length
WWMA = 0.0
WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1])
WWMA=Wwma_Func(src,length)
Zlema_Func(src,length)=>
zxLag = length/2==round(length/2) ? length/2 : (length - 1) / 2
zxEMAData = (src + (src - src[zxLag]))
ZLEMA = ema(zxEMAData, length)
ZLEMA=Zlema_Func(src,length)
Tsf_Func(src,length)=>
lrc = linreg(src, length, 0)
lrc1 = linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = linreg(src, length, 0)+lrs
TSF=Tsf_Func(src,length)
getMA(src, length) =>
ma = 0.0
if mav == "SMA"
ma := sma(src, length)
ma
if mav == "EMA"
ma := ema(src, length)
ma
if mav == "WMA"
ma := wma(src, length)
ma
if mav == "TMA"
ma := sma(sma(src, ceil(length / 2)), floor(length / 2) + 1)
ma
if mav == "VAR"
ma := VAR
ma
if mav == "WWMA"
ma := WWMA
ma
if mav == "ZLEMA"
ma := ZLEMA
ma
if mav == "TSF"
ma := TSF
ma
ma
MAvg=getMA(src, length)
Pmax_Func(src,length)=>
longStop = MAvg - Multiplier*atr
longStopPrev = nz(longStop[1], longStop)
longStop := MAvg > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = MAvg + Multiplier*atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := MAvg < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir
PMax = dir==1 ? longStop: shortStop
PMax=Pmax_Func(src,length)
plot(showsupport ? MAvg : na, color=#0585E1, linewidth=2, title="Moving Avg Line")
pALL=plot(PMax, color=color.red, linewidth=2, title="PMax", transp=0)
alertcondition(cross(MAvg, PMax), title="Cross Alert", message="PMax - Moving Avg Crossing!")
alertcondition(crossover(MAvg, PMax), title="Crossover Alarm", message="Moving Avg BUY SIGNAL!")
alertcondition(crossunder(MAvg, PMax), title="Crossunder Alarm", message="Moving Avg SELL SIGNAL!")
alertcondition(cross(src, PMax), title="Price Cross Alert", message="PMax - Price Crossing!")
alertcondition(crossover(src, PMax), title="Price Crossover Alarm", message="PRICE OVER PMax - BUY SIGNAL!")
alertcondition(crossunder(src, PMax), title="Price Crossunder Alarm", message="PRICE UNDER PMax - SELL SIGNAL!")
buySignalk = crossover(MAvg, PMax)
plotshape(buySignalk and showsignalsk ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
sellSignallk = crossunder(MAvg, PMax)
plotshape(sellSignallk and showsignalsk ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
buySignalc = crossover(src, PMax)
plotshape(buySignalc and showsignalsc ? PMax*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
sellSignallc = crossunder(src, PMax)
plotshape(sellSignallc and showsignalsc ? PMax*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0,display=display.none)
longFillColor = highlighting ? (MAvg>PMax ? color.green : na) : na
shortFillColor = highlighting ? (MAvg<PMax ? color.red : na) : na
fill(mPlot, pALL, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, pALL, title="DownTrend Highligter", color=shortFillColor)
showscr = input(true, title="Show Screener Label")
posX_scr = input(20, title="Pos. Label x-axis")
posY_scr = input(1, title="Pos. Size Label y-axis")
colinput = input(title="Label Color", defval="Blue", options=["White", "Black", "Red", "Green", "Yellow", "Blue"])
col = color.gray
if colinput=="White"
col:=color.white
if colinput=="Black"
col:=color.black
if colinput=="Red"
col:=color.red
if colinput=="Green"
col:=color.green
if colinput=="Yellow"
col:=color.yellow
if colinput=="Blue"
col:=color.blue
dummy0 = input(true, title = "=Backtest Inputs=")
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromYear = input(defval = 2005, title = "From Year", minval = 2005)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToYear = input(defval = 9999, title = "To Year", minval = 2006)
Start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
Finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
Timerange() =>
time >= Start and time <= Finish ? true : false
if buySignalk
strategy.entry("Long", strategy.long,when=Timerange())
if sellSignallk
strategy.entry("Short", strategy.short,when=Timerange())
t1=input('EURUSD', title='Symbol 01',type=input.symbol)
t2=input('XAUUSD', title='Symbol 02',type=input.symbol)
t3=input('AMZN', title='Symbol 03',type=input.symbol)
t4=input('TSLA', title='Symbol 04',type=input.symbol)
t5=input('BTCUSDT', title='Symbol 05',type=input.symbol)
t6=input('ETHBTC', title='Symbol 06',type=input.symbol)
t7=input('XBTUSD', title='Symbol 07',type=input.symbol)
t8=input('XRPBTC', title='Symbol 08',type=input.symbol)
t9=input('THYAO', title='Symbol 09',type=input.symbol)
t10=input('GARAN', title='Symbol 10',type=input.symbol)
t11=input('USDTRY', title='Symbol 11',type=input.symbol)
t12=input('PETKM', title='Symbol 12',type=input.symbol)
t13=input('AAPL', title='Symbol 13',type=input.symbol)
t14=input('TUPRS', title='Symbol 14',type=input.symbol)
t15=input('HALKB', title='Symbol 15',type=input.symbol)
t16=input('AVAXUSDT', title='Symbol 16',type=input.symbol)
t17=input('ETHUSDT', title='Symbol 17',type=input.symbol)
t18=input('UKOIL', title='Symbol 18',type=input.symbol)
t19=input('ABNB', title='Symbol 19',type=input.symbol)
t20=input('SISE', title='Symbol 20',type=input.symbol)
Pmax(Multiplier, Periods) =>
Up=MAvg-(Multiplier*atr)
Dn=MAvg+(Multiplier*atr)
TrendUp = 0.0
TrendUp := MAvg[1]>TrendUp[1] ? max(Up,TrendUp[1]) : Up
TrendDown = 0.0
TrendDown := MAvg[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = 0.0
Trend := MAvg > TrendDown[1] ? 1: MAvg< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
S_Buy = Trend == 1 ? 1 : 0
S_Sell = Trend != 1 ? 1 : 0
[Trend, Tsl]
[Trend, Tsl] = Pmax(Multiplier, Periods)
TrendReversal = Trend != Trend[1]
[t01, s01] = security(t1, timeframe.period, Pmax(Multiplier, Periods))
[t02, s02] = security(t2, timeframe.period, Pmax(Multiplier, Periods))
[t03, s03] = security(t3, timeframe.period, Pmax(Multiplier, Periods))
[t04, s04] = security(t4, timeframe.period, Pmax(Multiplier, Periods))
[t05, s05] = security(t5, timeframe.period, Pmax(Multiplier, Periods))
[t06, s06] = security(t6, timeframe.period, Pmax(Multiplier, Periods))
[t07, s07] = security(t7, timeframe.period, Pmax(Multiplier, Periods))
[t08, s08] = security(t8, timeframe.period, Pmax(Multiplier, Periods))
[t09, s09] = security(t9, timeframe.period, Pmax(Multiplier, Periods))
[t010, s010] = security(t10, timeframe.period, Pmax(Multiplier, Periods))
[t011, s011] = security(t11, timeframe.period, Pmax(Multiplier, Periods))
[t012, s012] = security(t12, timeframe.period, Pmax(Multiplier, Periods))
[t013, s013] = security(t13, timeframe.period, Pmax(Multiplier, Periods))
[t014, s014] = security(t14, timeframe.period, Pmax(Multiplier, Periods))
[t015, s015] = security(t15, timeframe.period, Pmax(Multiplier, Periods))
[t016, s016] = security(t16, timeframe.period, Pmax(Multiplier, Periods))
[t017, s017] = security(t17, timeframe.period, Pmax(Multiplier, Periods))
[t018, s018] = security(t18, timeframe.period, Pmax(Multiplier, Periods))
[t019, s019] = security(t19, timeframe.period, Pmax(Multiplier, Periods))
[t020, s020] = security(t20, timeframe.period, Pmax(Multiplier, Periods))
tr01 = t01 != t01[1], up01 = t01 == 1, dn01 = t01 == -1
tr02 = t02 != t02[1], up02 = t02 == 1, dn02 = t02 == -1
tr03 = t03 != t03[1], up03 = t03 == 1, dn03 = t03 == -1
tr04 = t04 != t04[1], up04 = t04 == 1, dn04 = t04 == -1
tr05 = t05 != t05[1], up05 = t05 == 1, dn05 = t05 == -1
tr06 = t06 != t06[1], up06 = t06 == 1, dn06 = t06 == -1
tr07 = t07 != t07[1], up07 = t07 == 1, dn07 = t07 == -1
tr08 = t08 != t08[1], up08 = t08 == 1, dn08 = t08 == -1
tr09 = t09 != t09[1], up09 = t09 == 1, dn09 = t09 == -1
tr010 = t010 != t010[1], up010 = t010 == 1, dn010 = t010 == -1
tr011 = t011 != t011[1], up011 = t011 == 1, dn011 = t011 == -1
tr012 = t012 != t012[1], up012 = t012 == 1, dn012 = t012 == -1
tr013 = t013 != t013[1], up013 = t013 == 1, dn013 = t013 == -1
tr014 = t014 != t014[1], up014 = t014 == 1, dn014 = t014 == -1
tr015 = t015 != t015[1], up015 = t015 == 1, dn015 = t015 == -1
tr016 = t016 != t016[1], up016 = t016 == 1, dn016 = t016 == -1
tr017 = t017 != t017[1], up017 = t017 == 1, dn017 = t017 == -1
tr018 = t018 != t018[1], up018 = t018 == 1, dn018 = t018 == -1
tr019 = t019 != t019[1], up019 = t019 == 1, dn019 = t019 == -1
tr020 = t020 != t020[1], up020 = t020 == 1, dn020 = t020 == -1
pot_label = 'Potential Reversal: \n'
pot_label := tr01 ? pot_label + t1 + '\n' : pot_label
pot_label := tr02 ? pot_label + t2 + '\n' : pot_label
pot_label := tr03 ? pot_label + t3 + '\n' : pot_label
pot_label := tr04 ? pot_label + t4 + '\n' : pot_label
pot_label := tr05 ? pot_label + t5 + '\n' : pot_label
pot_label := tr06 ? pot_label + t6 + '\n' : pot_label
pot_label := tr07 ? pot_label + t7 + '\n' : pot_label
pot_label := tr08 ? pot_label + t8 + '\n' : pot_label
pot_label := tr09 ? pot_label + t9 + '\n' : pot_label
pot_label := tr010 ? pot_label + t10 + '\n' : pot_label
pot_label := tr011 ? pot_label + t11 + '\n' : pot_label
pot_label := tr012 ? pot_label + t12 + '\n' : pot_label
pot_label := tr013 ? pot_label + t13 + '\n' : pot_label
pot_label := tr014 ? pot_label + t14 + '\n' : pot_label
pot_label := tr015 ? pot_label + t15 + '\n' : pot_label
pot_label := tr016 ? pot_label + t16 + '\n' : pot_label
pot_label := tr017 ? pot_label + t17 + '\n' : pot_label
pot_label := tr018 ? pot_label + t18 + '\n' : pot_label
pot_label := tr019 ? pot_label + t19 + '\n' : pot_label
pot_label := tr020 ? pot_label + t20 + '\n' : pot_label
scr_label = 'Confirmed Reversal: \n'
scr_label := tr01[1] ? scr_label + t1 + '\n' : scr_label
scr_label := tr02[1] ? scr_label + t2 + '\n' : scr_label
scr_label := tr03[1] ? scr_label + t3 + '\n' : scr_label
scr_label := tr04[1] ? scr_label + t4 + '\n' : scr_label
scr_label := tr05[1] ? scr_label + t5 + '\n' : scr_label
scr_label := tr06[1] ? scr_label + t6 + '\n' : scr_label
scr_label := tr07[1] ? scr_label + t7 + '\n' : scr_label
scr_label := tr08[1] ? scr_label + t8 + '\n' : scr_label
scr_label := tr09[1] ? scr_label + t9 + '\n' : scr_label
scr_label := tr010[1] ? scr_label + t10 + '\n' : scr_label
scr_label := tr011[1] ? scr_label + t11 + '\n' : scr_label
scr_label := tr012[1] ? scr_label + t12 + '\n' : scr_label
scr_label := tr013[1] ? scr_label + t13 + '\n' : scr_label
scr_label := tr014[1] ? scr_label + t14 + '\n' : scr_label
scr_label := tr015[1] ? scr_label + t15 + '\n' : scr_label
scr_label := tr016[1] ? scr_label + t16 + '\n' : scr_label
scr_label := tr017[1] ? scr_label + t17 + '\n' : scr_label
scr_label := tr018[1] ? scr_label + t18 + '\n' : scr_label
scr_label := tr019[1] ? scr_label + t19 + '\n' : scr_label
scr_label := tr020[1] ? scr_label + t20 + '\n' : scr_label
up_label = 'Uptrend: \n'
up_label := up01[1] ? up_label + t1 + '\n' : up_label
up_label := up02[1] ? up_label + t2 + '\n' : up_label
up_label := up03[1] ? up_label + t3 + '\n' : up_label
up_label := up04[1] ? up_label + t4 + '\n' : up_label
up_label := up05[1] ? up_label + t5 + '\n' : up_label
up_label := up06[1] ? up_label + t6 + '\n' : up_label
up_label := up07[1] ? up_label + t7 + '\n' : up_label
up_label := up08[1] ? up_label + t8 + '\n' : up_label
up_label := up09[1] ? up_label + t9 + '\n' : up_label
up_label := up010[1] ? up_label + t10 + '\n' : up_label
up_label := up011[1] ? up_label + t11 + '\n' : up_label
up_label := up012[1] ? up_label + t12 + '\n' : up_label
up_label := up013[1] ? up_label + t13 + '\n' : up_label
up_label := up014[1] ? up_label + t14 + '\n' : up_label
up_label := up015[1] ? up_label + t15 + '\n' : up_label
up_label := up016[1] ? up_label + t16 + '\n' : up_label
up_label := up017[1] ? up_label + t17 + '\n' : up_label
up_label := up018[1] ? up_label + t18 + '\n' : up_label
up_label := up019[1] ? up_label + t19 + '\n' : up_label
up_label := up020[1] ? up_label + t20 + '\n' : up_label
dn_label = 'Downtrend: \n'
dn_label := dn01[1] ? dn_label + t1 + '\n' : dn_label
dn_label := dn02[1] ? dn_label + t2 + '\n' : dn_label
dn_label := dn03[1] ? dn_label + t3 + '\n' : dn_label
dn_label := dn04[1] ? dn_label + t4 + '\n' : dn_label
dn_label := dn05[1] ? dn_label + t5 + '\n' : dn_label
dn_label := dn06[1] ? dn_label + t6 + '\n' : dn_label
dn_label := dn07[1] ? dn_label + t7 + '\n' : dn_label
dn_label := dn08[1] ? dn_label + t8 + '\n' : dn_label
dn_label := dn09[1] ? dn_label + t9 + '\n' : dn_label
dn_label := dn010[1] ? dn_label + t10 + '\n' : dn_label
dn_label := dn011[1] ? dn_label + t11 + '\n' : dn_label
dn_label := dn012[1] ? dn_label + t12 + '\n' : dn_label
dn_label := dn013[1] ? dn_label + t13 + '\n' : dn_label
dn_label := dn014[1] ? dn_label + t14 + '\n' : dn_label
dn_label := dn015[1] ? dn_label + t15 + '\n' : dn_label
dn_label := dn016[1] ? dn_label + t16 + '\n' : dn_label
dn_label := dn017[1] ? dn_label + t17 + '\n' : dn_label
dn_label := dn018[1] ? dn_label + t18 + '\n' : dn_label
dn_label := dn019[1] ? dn_label + t19 + '\n' : dn_label
dn_label := dn020[1] ? dn_label + t20 + '\n' : dn_label
f_colorscr (_valscr ) =>
_valscr ? #00000000 : na
f_printscr (_txtscr ) =>
var _lblscr = label(na),
label.delete(_lblscr ),
_lblscr := label.new(
time + (time-time[1])*posX_scr ,
ohlc4[posY_scr],
_txtscr ,
xloc.bar_time,
yloc.price,
f_colorscr ( showscr ),
textcolor = showscr ? col : na,
size = size.normal,
style=label.style_label_center
)
f_printscr ( scr_label + '\n' + pot_label +'\n' + up_label + '\n' + dn_label)
|
Custom Triple Moving Average Strategy | Auto Backtesting | https://www.tradingview.com/script/7xRYOdQA-Custom-Triple-Moving-Average-Strategy-Auto-Backtesting/ | Meesemoo | https://www.tradingview.com/u/Meesemoo/ | 150 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Meesemoo
//@version=4
strategy("Custom MA Strategy Tester", overlay = true)
MA1Period = input(13, title="MA1 Period")
MA1Type = input(title="MA1 Type", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA"])
MA1Source = input(title="MA1 Source", type=input.source, defval=close)
MA1Visible = input(title="MA1 Visible", type=input.bool, defval=true)
MA2Period = input(50, title="MA2 Period")
MA2Type = input(title="MA2 Type", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA"])
MA2Source = input(title="MA2 Source", type=input.source, defval=close)
MA2Visible = input(title="MA2 Visible", type=input.bool, defval=true)
MA3Period = input(200, title="MA3 Period")
MA3Type = input(title="MA3 Type", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA"])
MA3Source = input(title="MA3 Source", type=input.source, defval=close)
MA3Visible = input(title="MA3 Visible", type=input.bool, defval=true)
ShowCrosses = input(title="Show Crosses", type=input.bool, defval=true)
MA1 = if MA1Type == "SMA"
sma(MA1Source, MA1Period)
else
if MA1Type == "EMA"
ema(MA1Source, MA1Period)
else
if MA1Type == "WMA"
wma(MA1Source, MA1Period)
else
if MA1Type == "RMA"
rma(MA1Source, MA1Period)
else
if MA1Type == "HMA"
wma(2*wma(MA1Source, MA1Period/2)-wma(MA1Source, MA1Period), round(sqrt(MA1Period)))
else
if MA1Type == "DEMA"
e = ema(MA1Source, MA1Period)
2 * e - ema(e, MA1Period)
else
if MA1Type == "TEMA"
e = ema(MA1Source, MA1Period)
3 * (e - ema(e, MA1Period)) + ema(ema(e, MA1Period), MA1Period)
MA2 = if MA2Type == "SMA"
sma(MA2Source, MA2Period)
else
if MA2Type == "EMA"
ema(MA2Source, MA2Period)
else
if MA2Type == "WMA"
wma(MA2Source, MA2Period)
else
if MA2Type == "RMA"
rma(MA2Source, MA2Period)
else
if MA2Type == "HMA"
wma(2*wma(MA2Source, MA2Period/2)-wma(MA2Source, MA2Period), round(sqrt(MA2Period)))
else
if MA2Type == "DEMA"
e = ema(MA2Source, MA2Period)
2 * e - ema(e, MA2Period)
else
if MA2Type == "TEMA"
e = ema(MA2Source, MA2Period)
3 * (e - ema(e, MA2Period)) + ema(ema(e, MA2Period), MA2Period)
MA3 = if MA3Type == "SMA"
sma(MA3Source, MA3Period)
else
if MA3Type == "EMA"
ema(MA3Source, MA3Period)
else
if MA3Type == "WMA"
wma(MA3Source, MA3Period)
else
if MA3Type == "RMA"
rma(MA3Source, MA3Period)
else
if MA3Type == "HMA"
wma(2*wma(MA3Source, MA3Period/2)-wma(MA3Source, MA3Period), round(sqrt(MA3Period)))
else
if MA3Type == "DEMA"
e = ema(MA3Source, MA3Period)
2 * e - ema(e, MA3Period)
else
if MA3Type == "TEMA"
e = ema(MA3Source, MA3Period)
3 * (e - ema(e, MA3Period)) + ema(ema(e, MA3Period), MA3Period)
p1 = plot(MA1Visible ? MA1 : na, color=color.green, linewidth=1)
p2 = plot(MA2Visible ? MA2 : na, color=color.yellow, linewidth=1)
p3 = plot(MA3Visible ? MA3 : na, color=color.red, linewidth=2)
fill(p1, p2, color.silver, transp=80, title="Fill")
start = timestamp(2019, 1, 1, 1, 0)
end = timestamp(2025, 1, 1, 1, 0)
if time >= start and time <= end
longCondition = crossover(MA1, MA2) and close > MA3
if (longCondition)
strategy.entry("Long", strategy.long)
shortCondition = crossunder(MA1, MA2) and close < MA3
if (shortCondition)
strategy.entry("Short", strategy.short) |
ATR Stop Buy Strategy | https://www.tradingview.com/script/mUSqzuOq/ | phobo3s | https://www.tradingview.com/u/phobo3s/ | 57 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © phobo3s
//@version=4
strategy("ATR Stop Buy Strategy",shorttitle="ATR-ST",initial_capital=1000, overlay = true, default_qty_type = strategy.percent_of_equity, pyramiding = 5, default_qty_value = 20, commission_type = strategy.commission.cash_per_order, commission_value = 1, calc_on_every_tick = true)
daysBack = input(defval=120, title="Days Back", type=input.integer)
sellCoeff = input(defval=1.5, title="Selling Coefficent For ATR", type=input.float, minval= 0.01, step=0.1)
buyCoeff = input(defval=1.2, title = "Buying Coefficent For ATR", type=input.float, minval= 0.01, step=0.1)
fromDate = timenow - (daysBack*24*60*60*1000)
toDate = timenow
ATR = atr(14)
stopLossPoint = ATR * sellCoeff
buyPoint = ATR * buyCoeff
StoplossLine = close[1] - stopLossPoint[1]
BuyLine = close[1] + buyPoint[1]
if (high > BuyLine and time >= fromDate and time <= toDate )
strategy.entry("GG", strategy.long, comment="Gir")
if (low < StoplossLine and strategy.position_avg_price < close and time >= fromDate and time <= toDate )
strategy.entry("GG", strategy.short, comment="Çık")
//longFlags = close < StoplossLine
//shortFlags = close > BuyLine
//plotshape(shortFlags, style=shape.triangledown, location=location.abovebar, color=color.red)
//plotshape(longFlags, style=shape.triangleup, location=location.belowbar, color=color.blue)
plot(StoplossLine)
plot(BuyLine) |
Bollinger %B Candles Strategy | https://www.tradingview.com/script/msOsw3f7-Bollinger-B-Candles-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 223 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Bollinger %B Candles Strategy", overlay=false, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
BBLength = input(100, minval=1, step=1)
StdDev = 10
useMovingAverage = input(true)
MAType = input(title="Moving Average Type", defval="rma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
lookbackPeriod = input(22, minval=10, step=10)
colorByPreviousClose = input(true)
delaySignalBars = input(2, minval=2)
AtrMAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
AtrLength = input(10)
AtrMult = input(4)
wicks = input(false)
considerYearlyHighLow = input(false)
considerNewLongTermHighLows = input(false)
shortHighLowPeriod = 100
longHighLowPeriod = 200
tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
backtestYears = input(10, minval=1, step=1)
//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////
f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>
newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows
newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows
[newHigh,newLow]
//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////
f_getYearlyHighLowCondition(considerYearlyHighLow)=>
yhigh = security(syminfo.tickerid, '12M', high[1])
ylow = security(syminfo.tickerid, '12M', low[1])
yhighlast = yhigh[365]
ylowlast = ylow[365]
yhighllast = yhigh[2 * 365]
ylowllast = ylow[2 * 365]
yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))
yearlyHighCondition = ( (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow
yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))
yearlyLowCondition = ( (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow
label_x = time+(60*60*24*1000*1)
[yearlyHighCondition,yearlyLowCondition]
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)
[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)
[newHighS,newLowS] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)
[middleclose, upperclose, lowerclose] = bb(close, BBLength, StdDev)
[middleopen, upperopen, loweropen] = bb(open, BBLength, StdDev)
[middlehigh, upperhigh, lowerhigh] = bb(high, BBLength, StdDev)
[middlelow, upperlow, lowerlow] = bb(low, BBLength, StdDev)
percentBClose = (close - lowerclose)*100/(upperclose-lowerclose)
percentBOpen = (open - loweropen)*100/(upperopen-loweropen)
percentBHigh = (high - lowerhigh)*100/(upperhigh-lowerhigh)
percentBLow = (low - lowerlow)*100/(upperlow-lowerlow)
percentBMAClose = f_getMovingAverage(percentBClose, MAType, lookbackPeriod)
percentBMAOpen = f_getMovingAverage(percentBOpen, MAType, lookbackPeriod)
percentBMAHigh = f_getMovingAverage(percentBHigh, MAType, lookbackPeriod)
percentBMALow = f_getMovingAverage(percentBLow, MAType, lookbackPeriod)
newOpen = useMovingAverage? percentBMAOpen : percentBOpen
newClose = useMovingAverage? percentBMAClose : percentBClose
newHigh = useMovingAverage? percentBMAHigh : percentBHigh
newLow = useMovingAverage? percentBMALow : percentBLow
truerange = max(newHigh, newClose[1]) - min(newLow, newClose[1])
averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength)
atr = averagetruerange * AtrMult
longStop = newClose - atr
longStopPrev = nz(longStop[1], longStop)
longStop := (wicks ? newLow[1] : newClose[1]) > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = newClose + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := (wicks ? newHigh[1] : newClose[1]) < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and (wicks ? newHigh : newClose) > shortStopPrev ? 1 : dir == 1 and (wicks ? newLow : newClose) < longStopPrev ? -1 : dir
trailingStop = dir == 1? longStop : shortStop
candleColor = colorByPreviousClose ?
(newClose[1] < newClose ? color.green : newClose[1] > newClose ? color.red : color.silver) :
(newOpen < newClose ? color.green : newOpen > newClose ? color.red : color.silver)
plotcandle(newOpen, newHigh, newLow, newClose, title='PercentBCandle', color = candleColor)
plot(trailingStop, title="TrailingStop", style=plot.style_linebr, linewidth=1, color= dir == 1 ? color.green : color.red)
buyCondition = lowest(dir,delaySignalBars)==1 and yearlyHighCondition and newHighS
exitBuyCondition = highest(dir,delaySignalBars) == -1
sellCondition = highest(dir,delaySignalBars) == -1 and yearlyLowCondition and newLowS
exitSellCondition = lowest(dir,delaySignalBars) == 1
strategy.risk.allow_entry_in(tradeDirection)
barcolor(buyCondition? color.lime : sellCondition ? color.orange : color.silver)
strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)
strategy.close("Buy", when=exitBuyCondition)
strategy.entry("Sell", strategy.short, when=sellCondition and inDateRange, oca_name="oca_sell", oca_type=strategy.oca.none)
strategy.close("Sell", when=exitSellCondition) |
VWAP and BB strategy [EEMANI] | https://www.tradingview.com/script/oZYSB6Ui-VWAP-and-BB-strategy-EEMANI/ | mohanee | https://www.tradingview.com/u/mohanee/ | 571 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="VWAP and BB strategy [EEMANI]", overlay=true,pyramiding=2, default_qty_value=1, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)
//This strategy combines VWAP and BB indicators
//BUY RULE
//1. EMA50 > EMA 200
//2. if current close > vwap session value
//3. check if price dipped BB lower band for any of last 10 candles
//EXIT RULE
//1. price closes above BB upper
//STOP LOSS EXIT
//1. As configured --- default is set to 5%
is_price_dipped_bb(pds,source1) =>
t_bbDipped=false
for i=1 to pds
t_bbDipped:= (t_bbDipped or close[i]<source1) ? true : false
if t_bbDipped==true
break
else
continue
t_bbDipped
is_bb_per_dipped(pds,bbrSrc) =>
t_bbDipped=false
for i=1 to pds
t_bbDipped:= (t_bbDipped or bbrSrc[i]<=0) ? true : false
if t_bbDipped==true
break
else
continue
t_bbDipped
// variables BEGIN
shortEMA = input(13, title="fast EMA", minval=1)
longEMA = input(55, title="slow EMA", minval=1)
//BB
smaLength = input(20, title="BB SMA Length", minval=1)
bbsrc = input(close, title="BB Source")
strategyCalcOption = input(title="strategy to use", type=input.string, options=["BB", "BB_percentageB"], defval="BB")
//addOnDivergence = input(true,title="Add to existing on Divergence")
//exitOption = input(title="exit on RSI or BB", type=input.string, options=["RSI", "BB"], defval="BB")
//bbSource = input(title="BB source", type=input.string, options=["close", "vwap"], defval="close")
//vwap_res = input(title="VWAP Resolution", type=input.resolution, defval="session")
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
//variables END
longEMAval= ema(close, longEMA)
shortEMAval= ema(close, shortEMA)
ema200val = ema(close, 200)
vwapVal=vwap(close)
// Drawings
//plot emas
plot(shortEMAval, color = color.green, linewidth = 1, transp=0)
plot(longEMAval, color = color.orange, linewidth = 1, transp=0)
plot(ema200val, color = color.purple, linewidth = 2, style=plot.style_line ,transp=0)
//bollinger calculation
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = sma(bbsrc, smaLength)
dev = mult * stdev(bbsrc, smaLength)
upperBand = basis + dev
lowerBand = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
bbr = (bbsrc - lowerBand)/(upperBand - lowerBand)
//bollinger calculation
//plot bb
//plot(basis, "Basis", color=#872323, offset = offset)
p1 = plot(upperBand, "Upper", color=color.teal, offset = offset)
p2 = plot(lowerBand, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)
plot(vwapVal, color = color.purple, linewidth = 2, transp=0)
// Colour background
//barcolor(shortEMAval>longEMAval and close<=lowerBand ? color.yellow: na)
//longCondition= shortEMAval > longEMAval and close>open and close>vwapVal
longCondition= ( shortEMAval > longEMAval and close>open and close>vwapVal and close<upperBand ) // and close>=vwapVal
//Entry
strategy.entry(id="VWAP_BB LE", comment="VB LE" , long=true, when= longCondition and ( strategyCalcOption=="BB"? is_price_dipped_bb(10,lowerBand) : is_bb_per_dipped(10,bbr) ) and strategy.position_size<1 ) //is_price_dipped_bb(10,lowerBand)) //and strategy.position_size<1 is_bb_per_dipped(15,bbr)
//add to the existing position
strategy.entry(id="VWAP_BB LE", comment="Add" , long=true, when=strategy.position_size>=1 and close<strategy.position_avg_price and close>vwapVal )
barcolor(strategy.position_size>=1 ? color.blue: na)
strategy.close(id="VWAP_BB LE", comment="TP Exit", when=crossover(close,upperBand) )
//stoploss
stopLossVal = strategy.position_avg_price * (1-(stopLoss*0.01) )
strategy.close(id="VB LE", comment="SL Exit", when= close < stopLossVal)
|
Configurable BB+RSI+Aroon strategy backtest for binary options | https://www.tradingview.com/script/C9hNBmhr-Configurable-BB-RSI-Aroon-strategy-backtest-for-binary-options/ | MarcoJarquin | https://www.tradingview.com/u/MarcoJarquin/ | 206 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Developed by Marco Jarquin as part of Arkansas 22 Project for Binary Options
// CBRA for binary options (Configurable Bollinger Bands, RSI and Aroon)
//@version=5
// ====================================================================================
strategy('A22.CBRA.Strat', overlay=true, initial_capital=10000, currency='USD', calc_on_every_tick=true, default_qty_type=strategy.cash, default_qty_value=4000, commission_type=strategy.commission.cash_per_order, commission_value=0)
// Aroonish Parameters
// ====================================================================================
Aroonish_length = input.int(4, minval=1, title='Aroonish Lenght')
Aroonish_ConfVal = input.int(50, minval=0, maxval=100, step=25, title='Aroonish Confirmation Value')
Aroonish_upper = 100 * (-ta.highestbars(high, Aroonish_length + 1) + Aroonish_length) / Aroonish_length
Aroonish_lower = 100 * (-ta.lowestbars(low, Aroonish_length + 1) + Aroonish_length) / Aroonish_length
// Aroonish confirmations
// ====================================================================================
Aroonish_ConfLong = Aroonish_lower >= Aroonish_ConfVal and Aroonish_upper < Aroonish_lower
Aroonish_ConfShrt = Aroonish_upper >= Aroonish_ConfVal and Aroonish_upper > Aroonish_lower
plotshape(ta.crossover(Aroonish_lower, Aroonish_upper), color=color.new(color.red, 0), style=shape.triangledown, location=location.abovebar, size=size.auto, title='Ar-B')
plotshape(ta.crossover(Aroonish_upper, Aroonish_lower), color=color.new(color.green, 0), style=shape.triangleup, location=location.belowbar, size=size.auto, title='Ar-S')
// RSI Parameters
// ====================================================================================
RSI_length = input(4, title='RSI Lenght')
RSI_overSold = input(20, title='RSI Oversold Limit')
RSI_overBought = input(80, title='RSI Overbought Limit')
RSI = ta.rsi(close, RSI_length)
plotshape(ta.crossover(RSI, RSI_overSold), color=color.new(color.orange, 0), style=shape.square, location=location.belowbar, size=size.auto, title='RSI-B')
plotshape(ta.crossunder(RSI, RSI_overBought), color=color.new(color.orange, 0), style=shape.square, location=location.abovebar, size=size.auto, title='RSI-S')
// Bollinger Parameters
// ====================================================================================
BB_length = input.int(20, minval=1, title='Bollinger Lenght')
BB_mult = input.float(2.5, minval=0.1, maxval=50, step=0.1, title='Bollinger Std Dev')
// BB_bars = input(3, minval=1, maxval=5, title="Check bars after crossing")
BB_basis = ta.sma(close, BB_length)
BB_dev = BB_mult * ta.stdev(close, BB_length)
BB_upper = BB_basis + BB_dev
BB_lower = BB_basis - BB_dev
p1 = plot(BB_upper, color=color.new(color.blue, 0))
p2 = plot(BB_lower, color=color.new(color.blue, 0))
// Bars to have the operation open
// ====================================================================================
nBars = input.int(3, minval=1, maxval=30, title='Bars to keep the operation open')
// Strategy condition short or long
// ====================================================================================
ConditionShrt = (ta.crossunder(close, BB_upper) or ta.crossunder(close[1], BB_upper[1])) and Aroonish_ConfShrt and (ta.crossunder(RSI, RSI_overBought) or ta.crossunder(RSI[1], RSI_overBought[1]))
ConditionLong = (ta.crossover(close, BB_lower) or ta.crossover(close[1], BB_lower[1])) and Aroonish_ConfLong and (ta.crossover(RSI, RSI_overSold) or ta.crossover(RSI[1], RSI_overSold[1]))
plotshape(ta.crossover(close, BB_lower), color=color.new(color.blue, 0), style=shape.circle, location=location.belowbar, size=size.auto, title='BB-B')
plotshape(ta.crossunder(close, BB_upper), color=color.new(color.blue, 0), style=shape.circle, location=location.abovebar, size=size.auto, title='BB-S')
// Make input options that configure backtest date range
// ====================================================================================
iSDate = input.time(title='Start Date', defval=timestamp('14 Sep 2022 06:00 +0100'), tooltip='Start date and time of backtest')
iFDate = input.time(title='End Date', defval=timestamp('16 Sep 2022 16:00 +0100'), tooltip='End date and time of backtest')
// Look if the close time of the current bar falls inside the date range
// ====================================================================================
inDateRange = time >= iSDate and time < iFDate
// Evaluates conditions to enter short or long
// ====================================================================================
if inDateRange and ConditionLong
strategy.entry('A22.L', strategy.long)
if inDateRange and ConditionLong[nBars]
strategy.close('A22.L', comment='A22.L Exit')
if inDateRange and ConditionShrt
strategy.entry('A22.S', strategy.short)
if inDateRange and ConditionShrt[nBars]
strategy.close('A22.S', comment='A22.S Exit')
if not inDateRange
strategy.close_all()
|
Simple SMA Strategy Backtest Part 5 | https://www.tradingview.com/script/UtmXIbEo-Simple-SMA-Strategy-Backtest-Part-5/ | HPotter | https://www.tradingview.com/u/HPotter/ | 243 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HPotter
// Simple SMA strategy
//
// WARNING:
// - For purpose educate only
// - This script to change bars colors
//@version=4
timeinrange(res, sess) => not na(time(res, sess)) ? 1 : 0
strategy(title="Simple SMA Strategy Backtest", shorttitle="SMA Backtest", precision=6, overlay=true)
Resolution = input(title="Resolution", type=input.resolution, defval="D")
Source = input(title="Source", type=input.source, defval=close)
xSeries = security(syminfo.tickerid, Resolution, Source)
Length = input(title="Length", type=input.integer, defval=14, minval=2)
TriggerPrice = input(title="Trigger Price", type=input.source, defval=close)
TakeProfit = input(50, title="Take Profit", step=0.01)
StopLoss = input(20, title="Stop Loss", step=0.01)
UseTPSL = input(title="Use Take\Stop", type=input.bool, defval=false)
BarColors = input(title="Painting bars", type=input.bool, defval=true)
ShowLine = input(title="Show Line", type=input.bool, defval=true)
UseAlerts = input(title="Use Alerts", type=input.bool, defval=false)
timeframe = input(title="Time Frame", defval="15")
timerange = input(title="Time Range", defval="2300-0800")
reverse = input(title="Trade Reverse", type=input.bool, defval=false)
pos = 0
xSMA = sma(xSeries, Length)
pos := iff(TriggerPrice > xSMA, 1,
iff(TriggerPrice < xSMA, -1, nz(pos[1], 0)))
nRes = ShowLine ? xSMA : na
alertcondition(UseAlerts == true and pos != pos[1] and pos == 1, title='Signal Buy', message='Strategy to change to BUY')
alertcondition(UseAlerts == true and pos != pos[1] and pos == -1, title='Signal Sell', message='Strategy to change to SELL')
alertcondition(UseAlerts == true and pos != pos[1] and pos == 0, title='FLAT', message='Strategy get out from position')
possig =iff(pos[1] != pos,
iff(reverse and pos == 1, -1,
iff(reverse and pos == -1, 1, pos)), 0)
if (possig == 1 and timeinrange(timeframe, timerange))
strategy.entry("Long", strategy.long)
if (possig == -1 and timeinrange(timeframe, timerange))
strategy.entry("Short", strategy.short)
if (timeinrange(timeframe, timerange) == 0)
strategy.close_all()
if (UseTPSL)
strategy.close("Long", when = high > strategy.position_avg_price + TakeProfit, comment = "close buy take profit")
strategy.close("Long", when = low < strategy.position_avg_price - StopLoss, comment = "close buy stop loss")
strategy.close("Short", when = low < strategy.position_avg_price - TakeProfit, comment = "close buy take profit")
strategy.close("Short", when = high > strategy.position_avg_price + StopLoss, comment = "close buy stop loss")
nColor = BarColors ? strategy.position_avg_price != 0 and pos == 1 ? color.green :strategy.position_avg_price != 0 and pos == -1 ? color.red : color.blue : na
barcolor(nColor)
plot(nRes, title='SMA', color=#00ffaa, linewidth=2, style=plot.style_line) |
Function Polynomial Regression Strategy | https://www.tradingview.com/script/5q6K1Suu-Function-Polynomial-Regression-Strategy/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 594 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Credit for polynomial linear regression to RicardoSantos! Great work!
// © X11joe for strategy using it.
//@version=4
strategy(title="Function Polynomial Regression Strategy", overlay=false, precision=2,commission_value=0.0025,commission_type=strategy.commission.percent, initial_capital=5000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
f_array_polyreg(_X, _Y)=>
//{
//| Returns a polynomial regression channel using (X,Y) vector points.
//| Resources:
//| language D: https://rosettacode.org/wiki/Polynomial_regression
int _sizeY = array.size(id=_Y)
int _sizeX = array.size(id=_X)
//
float _meanX = array.sum(id=_X) / _sizeX
float _meanY = array.sum(id=_Y) / _sizeX
float _meanXY = 0.0
float _meanY2 = 0.0
float _meanX2 = 0.0
float _meanX3 = 0.0
float _meanX4 = 0.0
float _meanX2Y = 0.0
if _sizeY == _sizeX
for _i = 0 to _sizeY - 1
float _Xi = array.get(id=_X, index=_i)
float _Yi = array.get(id=_Y, index=_i)
_meanXY := _meanXY + (_Xi * _Yi)
_meanY2 := _meanY2 + pow(_Yi, 2)
_meanX2 := _meanX2 + pow(_Xi, 2)
_meanX3 := _meanX3 + pow(_Xi, 3)
_meanX4 := _meanX4 + pow(_Xi, 4)
_meanX2Y := _meanX2Y + pow(_Xi, 2) * _Yi
_meanXY := _meanXY / _sizeX
_meanY2 := _meanY2 / _sizeX
_meanX2 := _meanX2 / _sizeX
_meanX3 := _meanX3 / _sizeX
_meanX4 := _meanX4 / _sizeX
_meanX2Y := _meanX2Y / _sizeX
//-----------|covs
float _sXX = _meanX2 - _meanX * _meanX
float _sXY = _meanXY - _meanX * _meanY
float _sXX2 = _meanX3 - _meanX * _meanX2
float _sX2X2 = _meanX4 - _meanX2 * _meanX2
float _sX2Y = _meanX2Y - _meanX2 * _meanY
//-----------|
float _b = (_sXY * _sX2X2 - _sX2Y * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2)
float _c = (_sX2Y * _sXX - _sXY * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2)
float _a = _meanY - _b * _meanX - _c * _meanX2
//-----------|
float[] _predictions = array.new_float(size=0, initial_value=0.0)
float _max_dev = 0.0
float _min_dev = 0.0
float _stdev = 0.0
for _i = 0 to _sizeX - 1
float _Xi = array.get(id=_X, index=_i)
float _vector = _a + _b * _Xi + _c * _Xi * _Xi
array.push(id=_predictions, value=_vector)
//
float _Yi = array.get(id=_Y, index=_i)
float _diff = _Yi - _vector
if _diff > _max_dev
_max_dev := _diff
if _diff < _min_dev
_min_dev := _diff
_stdev := _stdev + abs(_diff)
//| Output:
//| _predictions: Array with adjusted _Y values.
//| _max_dev: Max deviation from the mean.
//| _min_dev: Min deviation from the mean.
//| _stdev/_sizeX: Average deviation from the mean.
//}
[_predictions, _max_dev, _min_dev, _stdev/_sizeX]
int length = input(59)
var float[] prices = array.new_float(size=length, initial_value=open)
var int[] indices = array.new_int(size=length, initial_value=0)
if pivothigh(2, 2)
e = array.pop(id=prices)
i = array.pop(id=indices)
array.insert(id=prices, index=0, value=high[2])
array.insert(id=indices, index=0, value=bar_index[2])
if pivotlow(2, 2)
e = array.pop(id=prices)
i = array.pop(id=indices)
array.insert(id=prices, index=0, value=low[2])
array.insert(id=indices, index=0, value=bar_index[2])
[P, Pmax, Pmin, Pstdev] = f_array_polyreg(indices, prices)
//|----------------------------------------------------------------------------||
//|----------------------------------------------------------------------------||
//|----------------------------------------------------------------------------||
//|----------------------------------------------------------------------------||
//|----------------------------------------------------------------------------||
//|----------------------------------------------------------------------------||
color _pr_mid_col = input(color.blue)
color _pr_std_col = input(color.aqua)
color _pr_max_col = input(color.purple)
f_init_mid()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_mid_col, style=line.style_solid, width=2)
f_init_std()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_std_col, style=line.style_dashed, width=1)
f_init_max()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_max_col, style=line.style_dotted, width=1)
var line pr_mid00 = f_init_mid(), var line pr_min00 = f_init_max(), var line pr_max00 = f_init_max()
var line pr_mid01 = f_init_mid(), var line pr_min01 = f_init_max(), var line pr_max01 = f_init_max()
var line pr_mid02 = f_init_mid(), var line pr_min02 = f_init_max(), var line pr_max02 = f_init_max()
var line pr_mid03 = f_init_mid(), var line pr_min03 = f_init_max(), var line pr_max03 = f_init_max()
var line pr_mid04 = f_init_mid(), var line pr_min04 = f_init_max(), var line pr_max04 = f_init_max()
var line pr_mid05 = f_init_mid(), var line pr_min05 = f_init_max(), var line pr_max05 = f_init_max()
var line pr_mid06 = f_init_mid(), var line pr_min06 = f_init_max(), var line pr_max06 = f_init_max()
var line pr_mid07 = f_init_mid(), var line pr_min07 = f_init_max(), var line pr_max07 = f_init_max()
var line pr_mid08 = f_init_mid(), var line pr_min08 = f_init_max(), var line pr_max08 = f_init_max()
var line pr_mid09 = f_init_mid(), var line pr_min09 = f_init_max(), var line pr_max09 = f_init_max()
var line pr_lower00 = f_init_std(), var line pr_upper00 = f_init_std()
var line pr_lower01 = f_init_std(), var line pr_upper01 = f_init_std()
var line pr_lower02 = f_init_std(), var line pr_upper02 = f_init_std()
var line pr_lower03 = f_init_std(), var line pr_upper03 = f_init_std()
var line pr_lower04 = f_init_std(), var line pr_upper04 = f_init_std()
var line pr_lower05 = f_init_std(), var line pr_upper05 = f_init_std()
var line pr_lower06 = f_init_std(), var line pr_upper06 = f_init_std()
var line pr_lower07 = f_init_std(), var line pr_upper07 = f_init_std()
var line pr_lower08 = f_init_std(), var line pr_upper08 = f_init_std()
var line pr_lower09 = f_init_std(), var line pr_upper09 = f_init_std()
f_pr_mid_line_selector(_i)=>(_i==0?pr_mid00:(_i==1?pr_mid01:(_i==2?pr_mid02:(_i==3?pr_mid03:(_i==4?pr_mid04:(_i==5?pr_mid05:(_i==6?pr_mid06:(_i==7?pr_mid07:(_i==8?pr_mid08:(_i==9?pr_mid09:pr_mid00))))))))))
f_pr_max_line_selector(_i)=>(_i==0?pr_max00:(_i==1?pr_max01:(_i==2?pr_max02:(_i==3?pr_max03:(_i==4?pr_max04:(_i==5?pr_max05:(_i==6?pr_max06:(_i==7?pr_max07:(_i==8?pr_max08:(_i==9?pr_max09:pr_max00))))))))))
f_pr_min_line_selector(_i)=>(_i==0?pr_min00:(_i==1?pr_min01:(_i==2?pr_min02:(_i==3?pr_min03:(_i==4?pr_min04:(_i==5?pr_min05:(_i==6?pr_min06:(_i==7?pr_min07:(_i==8?pr_min08:(_i==9?pr_min09:pr_min00))))))))))
f_pr_upper_line_selector(_i)=>(_i==0?pr_upper00:(_i==1?pr_upper01:(_i==2?pr_upper02:(_i==3?pr_upper03:(_i==4?pr_upper04:(_i==5?pr_upper05:(_i==6?pr_upper06:(_i==7?pr_upper07:(_i==8?pr_upper08:(_i==9?pr_upper09:pr_upper00))))))))))
f_pr_lower_line_selector(_i)=>(_i==0?pr_lower00:(_i==1?pr_lower01:(_i==2?pr_lower02:(_i==3?pr_lower03:(_i==4?pr_lower04:(_i==5?pr_lower05:(_i==6?pr_lower06:(_i==7?pr_lower07:(_i==8?pr_lower08:(_i==9?pr_lower09:pr_lower00))))))))))
int pr_fractions = 10
int pr_size = array.size(id=P)
int pr_step = max(pr_size / pr_fractions, 1)
for _i = 0 to pr_size - pr_step - 1 by pr_step
int _next_step_index = _i + pr_step
int _line = _i / pr_step
line.set_xy1(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i))
line.set_xy2(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step))
line.set_xy1(id=f_pr_max_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pmax)
line.set_xy2(id=f_pr_max_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pmax)
line.set_xy1(id=f_pr_min_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pmin)
line.set_xy2(id=f_pr_min_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pmin)
line.set_xy1(id=f_pr_upper_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pstdev)
line.set_xy2(id=f_pr_upper_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pstdev)
line.set_xy1(id=f_pr_lower_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) - Pstdev)
line.set_xy2(id=f_pr_lower_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) - Pstdev)
//@JA - Code from below was my strategy edits.
minval = line.get_y1(f_pr_min_line_selector(pr_size))
maxval = line.get_y1(f_pr_max_line_selector(pr_size))
plot(minval,color=color.green)
plot(maxval,color=color.red)
plot(close,color=color.yellow)
var inLong = false
var inShort = false
sinceShort = barssince(inLong == true)
sinceLong = barssince(inShort == true)
allowLongs = input(title="Allow Longs",type=input.bool,defval=true)
allowShorts = input(title="Allow Shorts",type=input.bool,defval=true)
closeNoShort = input(title="Close instead of Short", type=input.bool, defval=false)
closeNoLong = input(title="Close instead of Long", type=input.bool, defval=false)
// === INPUT BACKTEST RANGE ===
FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 1980, title = "From Year", minval = 1980)
ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 2017)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
// -- END BACKTEST RANGE --
//@JA - This is required so it works the first time onward
//plot(sinceLong,color=color.green)
//plot(sinceShort,color=color.red)
// avgLong = ema(sinceLong,length*10)
// avgShort = ema(sinceShort,length*10)
//plot(avgLong,color=color.green)
//plot(avgShort,color=color.red)
if(window()==true)
if(crossunder(close,maxval))
if(closeNoShort==false and allowShorts==true)
strategy.entry("short",false)
inShort := true
inLong := false
if(closeNoShort==true and allowShorts==false)
strategy.close("long") //@JA - Then close the strategy instead of going into short
inLong := false
if(crossover(close,minval))
if(closeNoLong==false and allowLongs==true)
strategy.entry("long",true)
inLong := true
inShort := false
if(closeNoLong==true and allowLongs==false)
strategy.close("short") //@JA - Then close the strategy instead of going into short
inShort := false
// //@JA - If going long and a long cross shows again and the minimum time for long has elapsed.
// if( strategy.position_size > 0 and crossunder(close,minval) and sinceLong>=10 )
// strategy.entry("short cancel",false)
// inShort := true
// inLong := false
// if( strategy.position_size < 0 and crossover(close,maxval) and sinceShort>=10 )
// strategy.entry("long cancel",true)
// inLong := true
//TRAILING STOP LOSS -----------------------------------------------------------
useTrailing = input(title="Use Trailing Stop Losses",type=input.bool,defval=false)
longTrailPerc = input(title="Trail Long Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=10) * 0.01
shortTrailPerc = input(title="Trail Short Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=4.6) * 0.01
// Create the variables that keep track of the stop price for being short or long. These values are always changing in a trailing stop loss based on if the bar is higher or lower than the previous.
longStopPrice = 0.0, shortStopPrice = 0.0
//Calculate the LONG stop price accounting for the percentage
longStopPrice := if (strategy.position_size > 0)
stopValue = close * (1 - longTrailPerc)
max(stopValue, longStopPrice[1])
else
0
//Calculate the SHORT stop price accounting for the percentage
shortStopPrice := if (strategy.position_size < 0)
stopValue = close * (1 + shortTrailPerc)
min(stopValue, shortStopPrice[1])
else
999999
// Plot stop loss values for confirmation
// plot(series=(strategy.position_size > 0) ? longStopPrice : na,
// color=color.green, style=plot.style_cross,
// linewidth=2, title="Long Trail Stop")
// plot(series=(strategy.position_size < 0) ? shortStopPrice : na,
// color=color.red, style=plot.style_cross,
// linewidth=2, title="Short Trail Stop")
//Exit if trailing stop loss conditions met to lock in profits.
if (strategy.position_size > 0 and useTrailing==true)
strategy.exit(id="TS X Long", stop=longStopPrice)
if (strategy.position_size < 0 and useTrailing==true)
strategy.exit(id="TS X Short", stop=shortStopPrice)
//END TRAILING STOP LOSS --------------------------------------------------------
|
Hull Moving Average vs Candle | https://www.tradingview.com/script/lc6FSl0Z-Hull-Moving-Average-vs-Candle/ | SeaSide420 | https://www.tradingview.com/u/SeaSide420/ | 599 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SeaSide420. Any timeFrame/pair , Hull Moving Average vs Candle
//@version=4
strategy("Hull Moving Average vs Candle",shorttitle="HMA-vs-Candle",overlay=true,default_qty_type=strategy.percent_of_equity,default_qty_value=100,commission_type=strategy.commission.cash_per_order,commission_value=1.00,slippage=1)
Period=input(title="Hull MA Period",type=input.integer,defval=50,minval=1)
Resolution=input(title="Candle Resolution", type=input.resolution,defval="D")
Price=input(title="Source of Price",type=input.source,defval=open)
HMA=hma(Price,Period)
Candle=security(syminfo.tickerid,Resolution,Price,barmerge.gaps_off,barmerge.lookahead_off)
change_color=HMA>Candle?color.green:color.red
plot1=plot(Candle,color=change_color,title="Candle Line",linewidth=2,transp=50)
plot2=plot(HMA[1],color=change_color,title="Hull MA Line",linewidth=2,transp=50)
fill(plot1,plot2,color=change_color,transp=50)
strategy.close("BUY",when=Price<HMA and HMA<Candle,comment="close buy entry")
strategy.close("SELL",when=Price>HMA and HMA>Candle,comment="close sell entry")
if (Price>HMA and HMA>Candle and Price>Price[1])
strategy.entry("BUY",strategy.long)
if (Price<HMA and HMA<Candle and Price<Price[1])
strategy.entry("SELL",strategy.short)
// /L'-,
// ,'-. /MM . . / L '-,
// . _,--dMMMM\ /MMM `.. / '-,
// : _,--, )MMMMMMMMM),. `QMM ,<> /_ '-,'
// ; ___,--. \MM( `-' )M//MM\ ` ,',.; .-'* ; .'
// | \MMMMMM) \MM\ ,dM//MMM/ ___ < ,; `. )`--' /
// | \MM()M MMM)__ /MM(/MP' ___, \ \ ` `. `. /__, ,'
// | MMMM/ MMMMMM( /MMMMP'__, \ | / `. `-,_\ /
// | MM /MMM---' `--'_ \ |-' |/ `./ .\----.___
// | /MM' `--' __,- \"" |-' |_, `.__) . .F. )-.
// | `--' \ \ |-' |_, _,-/ J . . . J-'-. `-.,
// | __ \`. | | | \ / _ |. . . . \ `-. F
// | ___ / \ | `| ' __ \ | /-' F . . . . \ '`
// | \ \ \ / | __ / \ | |,-' __,- J . . . . . \
// | | / |/ __,- \ ) \ / |_,- __,--' |. .__.----,'
// | |/ ___ \ |'. |/ __,--' `.-;;;;;;;;;\
// | ___ \ \ | | ` __,--' /;;;;;;;;;;;;.
// | \ \ |-'\ ' __,--' /;;;;;;;;;;;;;;\
// \ | | / | __,--' `--;;/ \;-'\
// \ | |/ __,--' / / \ \
// \ | __,--' / / \ \
// \|__,--' _,-;M-K, ,;-;\
// <;;;;;;;; '-;;;;
// ~ priceless artwork by SeaSide420 |
Automated - Fibs with Limit only orders | https://www.tradingview.com/script/qo9K5S7r-Automated-Fibs-with-Limit-only-orders/ | CryptoRox | https://www.tradingview.com/u/CryptoRox/ | 342 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CryptoRox
//@version=4
//Paste the line below in your alerts to run the built-in commands.
//{{strategy.order.alert_message}}
strategy(title="Fibs limit only", shorttitle="Strategy", overlay=true, precision=8, pyramiding=1000, commission_type=strategy.commission.percent, commission_value=0.04)
//Settings
testing = input(false, "Live")
//Use epochconverter or something similar to get the current timestamp.
starttime = input(1600976975, "Start Timestamp") * 1000
//Wait XX seconds from that timestamp before the strategy starts looking for an entry.
seconds = input(60, "Start Delay") * 1000
testPeriod = testing ? time > starttime + seconds : 1
leverage = input(1, "Leverage")
tp = input(1.0, "Take Profit %") / leverage
dca = input(-1.0, "DCA when < %") / leverage *-1
fibEntry = input("1", "Entry Level", options=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])
//Strategy Calls
equity = strategy.equity
avg = strategy.position_avg_price
symbol = syminfo.tickerid
openTrades = strategy.opentrades
closedTrades = strategy.closedtrades
size = strategy.position_size
//Fibs
lentt = input(60, "Pivot Length")
h = highest(lentt)
h1 = dev(h, lentt) ? na : h
hpivot = fixnan(h1)
l = lowest(lentt)
l1 = dev(l, lentt) ? na : l
lpivot = fixnan(l1)
z = 400
p_offset= 2
transp = 60
a=(lowest(z)+highest(z))/2
b=lowest(z)
c=highest(z)
fib0 = (((hpivot - lpivot)) + lpivot)
fib1 = (((hpivot - lpivot)*.21) + lpivot)
fib2 = (((hpivot - lpivot)*.3) + lpivot)
fib3 = (((hpivot - lpivot)*.5) + lpivot)
fib4 = (((hpivot - lpivot)*.62) + lpivot)
fib5 = (((hpivot - lpivot)*.7) + lpivot)
fib6 = (((hpivot - lpivot)* 1.00) + lpivot)
fib7 = (((hpivot - lpivot)* 1.27) + lpivot)
fib8 = (((hpivot - lpivot)* 2) + lpivot)
fib9 = (((hpivot - lpivot)* -.27) + lpivot)
fib10 = (((hpivot - lpivot)* -1) + lpivot)
notna = nz(fib10[60])
entry = 0.0
if fibEntry == "1"
entry := fib10
if fibEntry == "2"
entry := fib9
if fibEntry == "3"
entry := fib0
if fibEntry == "4"
entry := fib1
if fibEntry == "5"
entry := fib2
if fibEntry == "6"
entry := fib3
if fibEntry == "7"
entry := fib4
if fibEntry == "8"
entry := fib5
if fibEntry == "9"
entry := fib6
if fibEntry == "10"
entry := fib7
profit = avg+avg*(tp/100)
pause = 0
pause := nz(pause[1])
paused = time < pause
fill = 0.0
fill := nz(fill[1])
count = 0.0
count := nz(fill[1])
filled = count > 0 ? entry > fill-fill/100*dca : 0
signal = testPeriod and notna and not paused and not filled ? 1 : 0
neworder = crossover(signal, signal[1])
moveorder = entry != entry[1] and signal and not neworder ? true : false
cancelorder = crossunder(signal, signal[1]) and not paused
filledorder = crossunder(low[1], entry[1]) and signal[1]
last_profit = 0.0
last_profit := nz(last_profit[1])
if neworder and signal
strategy.order("New", 1, 0.0001, alert_message='New Order|e=binancefuturestestnet s=btcusdt b=long q=0.0011 fp=' + tostring(entry))
if moveorder
strategy.order("Move", 1, 0.0001, alert_message='Move Order|e=binancefuturestestnet s=btcusdt b=long c=order|e=binancefuturestestnet s=btcusdt b=long q=0.0011 fp=' + tostring(entry))
if filledorder and size < 1
fill := entry
count := count+1
pause := time + 60000
p = close+close*(tp/100)
strategy.entry("Filled", 1, 1, alert_message='Long Filled|e=binancefuturestestnet s=btcusdt b=short c=order|delay=1|e=binancefuturestestnet s=btcusdt b=long c=position q=100% ro=1 fp=' + tostring(p))
if filledorder and size >= 1
fill := entry
count := count+1
pause := time + 60000
strategy.entry("Filled", 1, 1, alert_message='Long Filled|e=binancefuturestestnet s=btcusdt b=short c=order|delay=1|e=binancefuturestestnet s=btcusdt b=long c=position q=100% ro=1 fp=' + tostring(profit))
if cancelorder and not filledorder
pause := time + 60000
strategy.order("Cancel", 1, 0.0001, alert_message='Cancel Order|e=binancefuturestestnet s=btcusdt b=long c=order')
if filledorder
last_profit := profit
closeit = crossover(high, profit) and size >= 1
if closeit
strategy.entry("Close ALL", 0, 0, alert_message='Profit')
count := 0
fill := 0.0
last_profit := 0.0
//Plots
bottom = signal ? color.green : filled ? color.red : color.white
plot(entry, "Entry", bottom) |
3 Higher High Price & Vol - BTST next day Gap up | https://www.tradingview.com/script/wP3r9JNT-3-Higher-High-Price-Vol-BTST-next-day-Gap-up/ | SharemarketRaja | https://www.tradingview.com/u/SharemarketRaja/ | 256 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SharemarketRaja
//@version=4
//Scanner available
strategy("3 Higher High Price & Vol", overlay=true)
volma = sma(volume, 20)
PriceHH = high > high[1] and high[1] > high[2]
VolHH = volume > volume[1] and volume[1] > volume[2]
Volma = volume > volma and volume[1] > volma[1] and volume[2] > volma[2]
Allgreen = close > open and close[1] > open[1] and close[2] > open[2]
PriceLL = low < low[1] and low[1] < low[2]
Allred = close < open and close[1] < open[1] and close[2] < open[2]
Qty = 100
Buy = (PriceHH == true and VolHH == true and Volma == true and Allgreen == true) and time("15", "1515-1530")
Reversal = (PriceLL == true and VolHH == true and Volma == true and Allred == true) and time("15", "1515-1530")
plotshape(Buy, style=shape.arrowup, size=size.large, color=color.green, location=location.belowbar)
plotshape(Reversal, style=shape.arrowup, size=size.large, color=color.red, location=location.belowbar)
strategy.entry(id="L", qty=Qty, long=true, when=Buy)
// strategy.entry(id="R", qty=Qty, long=true, when=Reversal)
// strategy.exit(id="LE", from_entry="L", profit=Profit, loss=Loss)
strategy.close_all(when=(time("15", "1500-1515")) ) |
ZVWAP strategy | https://www.tradingview.com/script/lGAXIACq-ZVWAP-strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 240 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
//This is based on Z distance from VWAP by Lazybear
strategy(title="ZVWAP[LB] strategy", overlay=false,pyramiding=2, default_qty_type=strategy.fixed, default_qty_value=3, initial_capital=10000, currency=currency.USD)
length=input(13,"length")
calc_zvwap(pds, source1) =>
mean = sum(volume*source1,pds)/sum(volume,pds)
vwapsd = sqrt(sma(pow(source1-mean, 2), pds) )
(close-mean)/vwapsd
upperTop=2.5 //input(2.5)
upperBottom=2.0 //input(2.0)
lowerTop=-0.5 //input(-0.5)
lowerBottom=-2.0 //input(-2.0)
buyLine=input(-0.5, title="OverSold Line",minval=-2, maxval=3)
sellLine=input(2.0, title="OverBought Line",minval=-2, maxval=3)
fastEma=input(13, title="Fast EMA",minval=1, maxval=50)
slowEma=input(55, title="Slow EMA",minval=10, maxval=200)
stopLoss =input(5, title="Stop Loss",minval=1)
hline(0, title="Middle Line", linestyle=hline.style_dotted, color=color.green)
ul1=plot(upperTop, "OB High")
ul2=plot(upperBottom, "OB Low")
fill(ul1,ul2, color=color.red)
ll1=plot(lowerTop, "OS High")
ll2=plot(lowerBottom, "OS Low")
fill(ll1,ll2, color=color.green)
zvwapVal=calc_zvwap(length,close)
plot(zvwapVal,title="ZVWAP",color=color.purple, linewidth=2)
longEmaVal=ema(close,slowEma)
shortEmaVal=ema(close,fastEma)
vwapVal=vwap(hlc3)
zvwapDipped=false
for i = 1 to 10
zvwapDipped := zvwapDipped or zvwapVal[i]<=buyLine
longCondition= shortEmaVal > longEmaVal and zvwapDipped and crossover(zvwapVal,0)
barcolor(longCondition ? color.yellow: na)
strategy.entry(id="ZVWAPLE", long=true, when= longCondition and strategy.position_size<1)
//Add
strategy.entry(id="ZVWAPLE", comment="Add", long=true, when= strategy.position_size>1 and close<strategy.position_avg_price and crossover(zvwapVal,0))
//calculate stop Loss
stopLossVal = strategy.position_avg_price - (strategy.position_avg_price*stopLoss*0.01)
strategy.close(id="ZVWAPLE",comment="SL Exit", when=close<stopLossVal) //close all on stop loss
strategy.close(id="ZVWAPLE",comment="TPExitAll", qty=strategy.position_size , when= crossunder(zvwapVal,sellLine)) //close all zvwapVal>sellLine |
STRATEGY TESTER ENGINE - ON CHART DISPLAY - PLUG & PLAY | https://www.tradingview.com/script/fKIMrSVd-STRATEGY-TESTER-ENGINE-ON-CHART-DISPLAY-PLUG-PLAY/ | FiatDropout | https://www.tradingview.com/u/FiatDropout/ | 117 | strategy | 4 | CC-BY-SA-4.0 | // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/
// © alexgrover
//@version=4
strategy("Grid System With Fake Martingale",process_orders_on_close=true, initial_capital=100)
point = input(1.)
os = input(1,"Order Size")
mf = input(2.,"Martingale Multiplier")
anti = input(false,"Anti Martingale")
//------------------------------------------------------------------------------
baseline = 0.
baseline := nz(close > baseline[1] + point or close < baseline[1] - point ?
close : baseline[1],close)
//------------------------------------------------------------------------------
size = 0.
lossnew = change(strategy.losstrades)
win = change(strategy.wintrades)
if anti
size := win ? size[1]*mf : lossnew ? 1 : nz(size[1],os)
else
size := lossnew ? size[1]*mf : win ? 1 : nz(size[1],os)
upper = baseline + point*size
lower = baseline - point*size
//------------------------------------------------------------------------------
if baseline > baseline[1] and strategy.opentrades == 0
strategy.entry("Buy",strategy.long,qty=os)
strategy.exit("buy/tp/sl","Buy",stop=lower,limit=upper)
if baseline < baseline[1] and strategy.opentrades == 0
strategy.entry("Sell",strategy.short,qty=os)
strategy.exit("sell/tp/sl","Sell",stop=upper,limit=lower)
//------------------------------------------------------------------------------
// STRATEGY TESTER ENGINE - ON CHART DISPLAY - PLUG & PLAY
//@FiatDropout
eq = strategy.equity //+ strategy.openprofit //USE THIS IF YOU NEED TO CHECK MAX GAINED BASED ON UNREALISED PnL and CANDLE MOVEMENT. THIS WILL CHANGE DD CALCCULATION AS WELL // CURRENT EQUITY
loss = strategy.grossloss //GROSS LOSS SINCE START
gain = strategy.grossprofit //GROSS LOSS SINCE START
in = strategy.initial_capital-100 //STARTING CAPITAL IN PERCENT
total = strategy.closedtrades
winners = strategy.wintrades
losers = strategy.losstrades
rmax = 0.
rmax := max(eq,nz(rmax[1]))
lmax = 0.
lmax := max(loss,nz(loss[1]))
gmax = 0.
gmax := max(gain,nz(gain[1]))
inmax = 0.
inmax := max(in,nz(in[1]))
tmax = 0.
tmax := max(total,nz(total[1]))
dd = -((rmax-eq)/rmax*100) //CURRENT DRAWDOWN
ddm = lowest(dd,200) //MAX DRAWDOWN
pfactor = gmax/lmax //PROFIT FACTOR
ppercent = winners/total*100 //PROFIT PERCENTAGE
//----
css = eq > in ? #0cb51a : #e65100
css2 = eq > loss ? color.blue : color.blue
css3 = dd > 0 ? color.red : color.red
css4 = dd > ddm ? color.orange : na
a = plot(eq,"Current Profit(%)",#2196f3,2,transp=0)
b = plot(rmax,"Maximum Gained(%)",css,2,transp=0)
c = plot(inmax, "Starting Cap(%)", color.white,2,transp=0)
d = plot(dd, "Current Drawdown(%)", color.fuchsia,2,transp=0)
e = plot(ddm, "Max Drawdown(%)", color.red,2,transp=0)
plot(lmax, "Gross Loss(%)", color.red,2,transp=0)
plot(gmax, "Gross Gain(%)", color.green,2,transp=0)
plot(pfactor, "Profit Factor", color.orange,2,transp=0)
plot(tmax,"Total CLosed Trades", color.aqua,2,transp=0)
plot(winners,"Trades Won", color.green,2,transp=0)
plot(losers, "Trades Lost", color.red,2,transp=0)
plot(ppercent,"Profit Percentage(%)", color.lime,2,transp=0)
bgcolor(eq <= 0 and dd <= -100 ? color.red : na,title= "LIQUIDATION",transp=55)
fill(a,b,css,80)
fill(a,c,css2,60)
fill(c,d,css3,35)
fill(d,e,css4,30)
|
SMA Strategy | https://www.tradingview.com/script/MdfNQ43u-SMA-Strategy/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 151 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © melihtuna
//@version=4
strategy("SMA Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, currency=currency.USD, commission_value=0.1, commission_type=strategy.commission.percent)
smaB1 = input(title="smaB1",defval=377)
smaB2 = input(title="smaB2",defval=200)
smaS1 = input(title="smaS1",defval=377)
smaS2 = input(title="smaS2",defval=200)
smawidth = 2
plot(sma(close, smaB1), color = #EFB819, linewidth=smawidth, title='smaB1')
plot(sma(close, smaB2), color = #FF23FD, linewidth=smawidth, title='smaB2')
plot(sma(close, smaS1), color = #000000, linewidth=smawidth, title='smaS1')
plot(sma(close, smaS2), color = #c48dba, linewidth=smawidth, title='smaS2')
// === INPUT BACKTEST RANGE ===
FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2020, title = "From Year", minval = 2017)
ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 2017)
// === FUNCTION EXAMPLE ===
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() => time >= start and time <= finish ? true : false
longCondition = crossover(sma(close, smaB1),sma(close, smaB2))
if (window() and longCondition)
strategy.entry("BUY", strategy.long)
shortCondition = crossover(sma(close, smaS2),sma(close, smaS1))
if (window() and shortCondition)
strategy.entry("SELL", strategy.short)
|
ADX strategy (considering ADX and +DI only ) | https://www.tradingview.com/script/G4RNcGXg-ADX-strategy-considering-ADX-and-DI-only/ | mohanee | https://www.tradingview.com/u/mohanee/ | 427 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
//ADX strategy
SmoothedTrueRange=0.00
SmoothedDirectionalMovementPlus=0.00
SmoothedDirectionalMovementMinus=0.00
strategy(title="ADX strategy", overlay=false,pyramiding=3, default_qty_type=strategy.fixed, default_qty_value=3, initial_capital=10000, currency=currency.USD)
len = input(11, title="ADX Length", minval=1)
threshold = input(30, title="threshold", minval=5)
fastEma=input(13, title="Fast EMA",minval=1, maxval=50)
slowEma=input(55, title="Slow EMA",minval=10, maxval=200)
stopLoss =input(8, title="Stop Loss",minval=1) //
TrueRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0
DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? max(nz(low[1])-low, 0): 0
SmoothedTrueRange:= nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1])/len) + TrueRange
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1])/len) + DirectionalMovementPlus
SmoothedDirectionalMovementMinus:= nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1])/len) + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100
ADX = sma(DX, len)
plot(DIPlus, color=color.green, title="DI+")
//plot(DIMinus, color=color.red, title="DI-")
plot(ADX, color=color.black, title="ADX")
hline(threshold, color=color.black, linestyle=hline.style_dashed)
fastEmaVal=ema(close,fastEma)
slowEmaVal=ema(close,slowEma)
//long condition
longCondition= ADX < threshold and crossover(DIPlus,ADX) and fastEmaVal > slowEmaVal
barcolor(longCondition ? color.yellow: na)
strategy.entry(id="ADXLE", long=true, when= longCondition and strategy.position_size<1)
barcolor(strategy.position_size>1 ? color.blue: na)
bgcolor(strategy.position_size>1 ? color.blue: na)
//Add
strategy.entry(id="ADXLE", comment="Add", long=true, when= strategy.position_size>1 and close<strategy.position_avg_price and crossover(DIPlus,ADX) )
//calculate stop Loss
stopLossVal = strategy.position_avg_price - (strategy.position_avg_price*stopLoss*0.01)
strategy.close(id="ADXLE",comment="SL Exit", when=close<stopLossVal) //close all on stop loss
//exit condition
exitCondition= ADX > threshold and crossunder(DIPlus,ADX) // and fastEmaVal > slowEmaVal
strategy.close(id="ADXLE",comment="TPExitAll", qty=strategy.position_size , when= exitCondition) //close all |
EMA crossover - BTC/USD 4hr | https://www.tradingview.com/script/ocbewlnh-EMA-crossover-BTC-USD-4hr/ | str1nger | https://www.tradingview.com/u/str1nger/ | 24 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © str1nger
//@version=4
strategy(title="BTC - 4hr - Long/Short", shorttitle="BTC - 4hr - Long/Short", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=75,commission_type=strategy.commission.percent, commission_value=0.075)//////<---Uses a percentage of starting equity
//DATE RANGE//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2020, minval=2000, maxval=2100)
endDate = input(title="End Date", type=input.integer,
defval=1, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=12, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2021, minval=2000, maxval=2100)
inDateRange = (time >= timestamp("Europe/London", startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp("Europe/London", endYear, endMonth, endDate, 0, 0))
//EMAs//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LONG
//11,33,3,40
lof= input(11, title="Long Open - Fast", step=1)
los= input(33, title="Long Open - Slow", step=1)
lcf= input(3, title="Long Close - Fast", step=1)
lcs= input(40, title="Long Close - Slow", step=1)
ema_long_open_fast = ema(close, lof)
ema_long_open_slow = ema(close, los)
ema_long_close_fast= ema(close, lcf)
ema_long_close_slow = ema(close, lcs)
//SHORT
//5,11,4,7
sof= input(5, title="Short Open - Fast", step=1)
sos= input(11, title="Short Open - Slow", step=1)
scf= input(4, title="Short Close - Fast", step=1)
scs= input(7, title="Short Close - Slow", step=1)
ema_short_open_fast = ema(close, sof)
ema_short_open_slow = ema(close, sos)
ema_short_close_fast = ema(close, scf)
ema_short_close_slow = ema(close, scs)
//CONDITIONS///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LONG
openlong = crossover(ema_long_open_fast, ema_long_open_slow)
closelong = crossover(ema_long_close_slow, ema_long_close_fast)
//1.7%
long_loss_percent = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1.7) * 0.01
long_stop_price = strategy.position_avg_price * (1 - long_loss_percent)
//SHORT
openshort = crossover(ema_short_open_slow, ema_short_open_fast)
closeshort = crossover(ema_short_close_fast, ema_short_close_slow)
//0.4%
short_loss_percent = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.4) * 0.01
short_stop_price = strategy.position_avg_price * (1 + short_loss_percent)
//PLOT EMAs////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LONG
plot(ema_long_open_fast, "Long EMA open lower", linewidth=1, color=color.green)
plot(ema_long_open_slow, "Long EMA close upper", linewidth=1, color=color.green)
plot(ema_long_close_fast, "Long close lower", linewidth=1, color=color.red)
plot(ema_long_close_slow, "Long close upper", linewidth=1, color=color.red)
//SHORT
plot(ema_short_open_fast, "Short open fast", linewidth=1, color=color.green)
plot(ema_short_open_slow, "Short open slow", linewidth=1, color=color.green)
plot(ema_short_close_fast, "Short close fast", linewidth=1, color=color.red)
plot(ema_short_close_slow, "Short close slow", linewidth=1, color=color.red)
//LONG-TERM TRENDS
//LONG 144
long_term_trend_longs= input(144, title="Long-term trend - Longs", step=1)
lttl= ema(close, long_term_trend_longs)
plot(lttl, "Long-term trend - Longs", linewidth=2, color=color.blue)
//SHORT 89
long_term_trend_shorts= input(89, title="Long-term trend - Shorts", step=1)
ltts = ema(close, long_term_trend_shorts)
plot(ltts, "Long-term trend - Shorts", linewidth=2, color=color.blue)
//STRATEGY//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LONG
if (inDateRange and openlong and (close > lttl))
strategy.entry("OL", long=true, comment="##insert open long comment here##")
if (inDateRange and closelong)
strategy.close("OL", comment="##insert close long comment here##")
if strategy.position_size > 0
strategy.exit("L-SL", stop=long_stop_price, comment="##insert long stop-loss comment here##")
//SHORT
if (inDateRange and openshort and (close < ltts))
strategy.entry("OS", long=false, comment="##insert open short comment here##")
if (inDateRange and closeshort)
strategy.close("OS", comment="##insert close short comment here##")
if strategy.position_size < 0
strategy.exit("S-SL", stop=short_stop_price, comment="##inster short stop-loss comment here##")
|
SSL Backtester With ATR SL TP and Money Management | https://www.tradingview.com/script/tu4HlGFa-SSL-Backtester-With-ATR-SL-TP-and-Money-Management/ | JBTrippin | https://www.tradingview.com/u/JBTrippin/ | 43 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © comiclysm
//@version=4
strategy("SSL Backtester", overlay=false)
//--This strategy will simply test the effectiveness of the SSL using
//--money management and an ATR-derived stop loss
//--USER INPUTS
two_digit = input(false, "Check this for 2-digit pairs (JPY, Gold, Etc)")
ssl_period = input(16, "SSL Period")
atr_period = input(14, "ATR Period")
atr_stop_factor = input(1.5, "ATR Stop Loss Factor")
atr_target_factor = input(1.0, "ATR Target Factor")
use_mm = input(true, "Check this to use Money Management")
position_size = input(1000, "Position size (for Fixed Risk)")
risk = input(0.01, "Risk % in Decimal Form")
//--INDICATORS------------------------------------------------------------
//--SSL
sma_high = sma(high, ssl_period)
sma_low = sma(low, ssl_period)
ssl_value = 0
ssl_value := close > sma_high ? 1 : close < sma_low ? -1 : ssl_value[1]
ssl_low = ssl_value < 0 ? sma_high : sma_low
ssl_high = ssl_value < 0 ? sma_low : sma_high
//--Average True Range
atr = atr(atr_period)
//--TRADE LOGIC----------------------------------------------------------
signal_long = ssl_value > 0 and ssl_value[1] < 0
signal_short = ssl_value < 0 and ssl_value[1] > 0
//--RISK MANAGMENT-------------------------------------------------------
balance = strategy.netprofit + strategy.initial_capital
risk_pips = atr*10000*atr_stop_factor
if(two_digit)
risk_pips := risk_pips / 100
risk_in_value = balance * risk
point_value = syminfo.pointvalue
risk_lots = risk_in_value / point_value / risk_pips
final_risk = use_mm ? risk_lots * 10000 : position_size
//--TRADE EXECUTION-----------------------------------------------------
if (signal_long)
stop_loss = close - atr * atr_stop_factor
target = close + atr * atr_target_factor
strategy.entry("Long", strategy.long, final_risk)
strategy.exit("X", "Long", stop=stop_loss, limit=target)
if (signal_short)
stop_loss = close + atr * atr_stop_factor
target = close - atr * atr_target_factor
strategy.entry("Short", strategy.short, final_risk)
strategy.exit("X", "Short", stop=stop_loss, limit=target)
//--PLOTTING-----------------------------------------------------------
plot(ssl_low, "SSL", color.red, linewidth=1)
plot(ssl_high, "SSL", color.lime, linewidth=1)
|
Koala System EURUSD 15min | https://www.tradingview.com/script/wtx6cq4I-Koala-System-EURUSD-15min/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 194 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("Koala Script",initial_capital=1000,
commission_type=strategy.commission.cash_per_contract,
commission_value=0.000065,
slippage=3)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 8, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
len = input(3, minval=1, title="Length")
src = input(hl2, title="Source")
smma = 0.0
sma1 = sma(src, len)
smma := na(smma[1]) ? sma1 : (smma[1] * (len - 1) + src) / len
len2 = input(6, minval=1, title="Length")
src2 = input(hl2, title="Source")
smma2 = 0.0
sma2 = sma(src2, len2)
smma2 := na(smma2[1]) ? sma2 : (smma2[1] * (len2 - 1) + src2) / len2
len3 = input(9, minval=1, title="Length")
src3 = input(hl2, title="Source")
smma3 = 0.0
sma3 = sma(src3, len3)
smma3 := na(smma3[1]) ? sma3 : (smma3[1] * (len3 - 1) + src3) / len3
len4 = input(50, minval=1, title="Length")
src4 = input(close, title="Source")
smma4 = 0.0
sma4 = sma(src4, len4)
smma4 := na(smma4[1]) ? sma4 : (smma4[1] * (len4 - 1) + src4) / len4
len5 = input(200, minval=1, title="Length")
src5 = input(close, title="Source")
out5 = ema(src5, len5)
timeinrange(res, sess) => time(res, sess) != 0
london=timeinrange(timeframe.period, "0300-1045")
londonEntry=timeinrange(timeframe.period, "0300-0845")
time_cond = time >= startDate and time <= finishDate and londonEntry
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
srcc = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
// Calculating
fast_ma = sma_source ? sma(srcc, fast_length) : ema(srcc, fast_length)
slow_ma = sma_source ? sma(srcc, slow_length) : ema(srcc, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
longCond = close > out5 and close > smma4 and close > smma3 and close > smma2 and close > smma and londonEntry and smma > smma2 and smma2>smma3 and smma3>smma4 and smma4>out5
shortCond = close < out5 and close < smma4 and close < smma3 and close < smma2 and close < smma and londonEntry and smma < smma2 and smma2<smma3 and smma3<smma4 and smma4<out5
//longCond2 = crossover(close,out5) and crossover(close,smma4) and crossover(close,smma3) and crossover(close,smma2) and crossover(close,smma) and time_cond
//shortCond2 = crossunder(close,out5) and crossunder(close,smma4) and crossunder(close,smma3) and crossunder(close,smma2) and crossunder(close,smma) and time_cond
length=input(14, title="ATR Length")
mult=input(1.0, title="Percentage Multiplier (for ex., 0.7 = 70%)", step=0.1, minval=0.1, maxval=5.0)
oa=input(false, title="Show actual ATR")
ii=syminfo.pointvalue==0
s=ii?na:oa?atr(length):(syminfo.pointvalue * mult * atr(length))
tp=input(300,title="tp")
sl=input(300,title="sl")
//tp = s*10000
//sl= s*10000
//if(tp>300)
// tp:=300
//if(sl>300)
// sl:=300
//if(sl<150)
// sl:=150
//if(tp<150)
// tp:=150
//MONEY MANAGEMENT--------------------------------------------------------------
balance = strategy.netprofit + strategy.initial_capital //current balance
floating = strategy.openprofit //floating profit/loss
risk = input(3,type=input.float,title="Risk %")/100 //risk % per trade
//Calculate the size of the next trade
temp01 = balance * risk //Risk in USD
temp02 = temp01/sl //Risk in lots
temp03 = temp02*100000 //Convert to contracts
size = temp03 - temp03%1000 //Normalize to 1000s (Trade size)
if(size < 10000)
size := 10000 //Set min. lot size
strategy.entry("long",1,size,when=longCond )
strategy.exit("closelong","long", profit=tp,loss=sl)
//strategy.close("long",when= crossunder(close[4],smma4) and close[4] > close[3] and close[3]>close[2] and close[2] > close[1] and close[1] > close)
strategy.entry("short",0,size,when=shortCond )
strategy.exit("closeshort","short", profit=tp,loss=sl)
//strategy.close("short",when= crossover(close[4],smma4) and close[4] < close[3] and close[3]< close[2] and close[2] < close[1] and close[1] < close)
strategy.close_all(when = not london)
maxEntry=input(2,title="max entries")
strategy.risk.max_intraday_filled_orders(maxEntry) |
First Script, buy/sell on EMA | https://www.tradingview.com/script/UZZLjsO2-First-Script-buy-sell-on-EMA/ | dejoski | https://www.tradingview.com/u/dejoski/ | 40 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dejoski
//@version=4
strategy(title="My Strategy ", default_qty_type = strategy.percent_of_equity,overlay=true, default_qty_value=100)
fastLength = input(12, minval=1), slowLength=input(26,minval=1)
signalLength=input(9,minval=1)
// fastLength = 12, signalLength = 26
fastMA = ema(close, fastLength)
slowMA = ema(close, slowLength)
macd = fastMA - slowMA
signal = sma(macd, signalLength)
hist = macd - signal
pricedif7 = close-close[15]
// plot(rsi(open,7))
fastMA2 = ema(close[1], fastLength)
slowMA2 = ema(close[1], slowLength)
macd2 = fastMA2 - slowMA2
signal2 = sma(macd2, signalLength)
hist2 = macd2 - signal2
// outSignal = security(tickerid, res, signal)
sigdif = signal-signal2
histdif = hist - hist2
// plot(histdif)
fastMA3 = ema(close[2], fastLength)
slowMA3 = ema(close[2], slowLength)
macd3 = fastMA3 - slowMA3
signal3 = sma(macd3, signalLength)
hist3 = macd3 - signal3
// outSignal = security(tickerid, res, signal)
sigdif2 = signal-signal3
histdif2 = hist2 - hist3
// plot(histdif2)
hist_momentum = histdif+histdif2
momentum = (abs(hist_momentum)/(open/10))
fastMA7 = ema(close[10], fastLength)
slowMA7 = ema(close[10], slowLength)
macd7 = fastMA7 - slowMA7
signal7 = sma(macd7, signalLength)
hist7 = macd7 - signal7
// outSignal = security(tickerid, res, signal)
sigdif7 = signal-signal7
histdif7 = hist - hist7
// plot(histdif7)
// plot(outSignal[1])
// percent_red = (5+hist)/(5+(signal))
// macd = fastMA - slowMA
// signal = sma(macd, 9)
//these were on
// plot(pricedif7)
// plot(histdif, color=color.green)
// plot(histdif2, color=color.green)
// plot(hist_momentum, color=color.orange)
// plot((momentum), color=color.orange)
// plot(sigdif7)
// plot(macd, color=color.blue)
// plot(signal, color=color.orange)
// plot(hist, color=color.red)
// plot(percent_red, color=color.green)
GoodMacd = false
madc_threshold = 0.5
sell_threshold = -0.5
if (signal>=madc_threshold)
GoodMacd := true
if (signal<madc_threshold)
GoodMacd := false
// t = "ESD:" + ticker + "_EARNINGS"
// esti = security(t, "D", open, true)
// earn = security(t, "D", close, true)
// plot(esti, style=circles, linewidth=4)
// plot(earn, style=cross, linewidth=4)
// longCondition = crossover(sma(close, 14), sma(close, 28))
esd = "EARNINGS"
t = tickerid(prefix = "ESD", ticker=syminfo.prefix + ";" + syminfo.ticker + ";" + esd)
prefix = syminfo.prefix //input("NASDAQ", "Exchange Prefix")
tick = syminfo.ticker // input("TSLA", "Ticker")
earning = security("ESD_FACTSET:" + prefix + ";" + tick + ";EARNINGS", "D", close, true)
c = security(t, "D", close, true)
o = security(t, "D", open, true)
h = security(t, "D", high, true)
// h2 = security(t, "D", high[1], true, lookahead = barmerge.lookahead_on)
u = security(t, "D", updatetime, true)
// c - earning
// o - estimate
// h - date (in unix time)
// u - period ending (in unix time)
// last_c = c
// last_c := c?c:nz(last_c[1])
last_earnings_time = h
last_earnings_time := h?h:last_earnings_time[1]
t_minus = time/1000-last_earnings_time
max = 0.0
max := t_minus>nz(max[1]) or max[1]>22820200.00?t_minus:nz(max[1])
// plotchar(max, "check", "", location = location.top)
// plotchar(c, location=location.absolute, color=color.green, size=size.tiny)
// plotchar(t_minus>=max-172800?true:na, location=location.absolute, color=color.red, size=size.tiny)
emaplot = input (true, title="Show EMA on chart")
len = input(8, minval=1, title="ema Length")
src = close
out = ema(src, len)
up = out > out[1]
down = out < out[1]
buy = up ? true : down ? false : false
mycolor = up ? color.green : down ? color.red : color.blue
plot(out and emaplot ? out :na, title="EMA", color=mycolor, linewidth=3)
// if (GoodMacd and (macd >= signal))
// if (GoodMacd and hist> 0)
sigdif_thresh = 0.0
days = 7
days_in_sec = days*86400
time_before_earnings = days_in_sec
earnings_soon = t_minus>=(max-time_before_earnings)?true:na
// plotshape(earnings_soon)
plotchar(earnings_soon,"Exit all, earnings soon!", location=location.bottom, color=color.orange, size=size.tiny)
if (buy and not earnings_soon)
strategy.close("short")
strategy.entry("long", strategy.long, when = strategy.position_size == 0 )
if (not buy and not earnings_soon)
strategy.close("long")
strategy.entry("short", strategy.short, when = strategy.position_size == 0 )
if (earnings_soon)
strategy.close("short")
strategy.close("long")
|
Two level TP + TrailStp exits example | https://www.tradingview.com/script/tWS24Z2K-Two-level-TP-TrailStp-exits-example/ | adolgov | https://www.tradingview.com/u/adolgov/ | 160 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov
//@version=4
strategy("Two level TP + TrailStp exits example", overlay=false, default_qty_value = 100)
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
trailingPoints = input(1000)
trailingOffset = input(300)
takeProfitPoints = input(1000)
strategy.exit("partial", qty_percent = 50, profit = takeProfitPoints)
strategy.exit("full", trail_points = trailingPoints, trail_offset = trailingOffset)
profitPercent(price) =>
posSign = strategy.position_size > 0 ? 1 : strategy.position_size < 0 ? -1 : 0
(price - strategy.position_avg_price) / strategy.position_avg_price * posSign * 100
p1 = plot(profitPercent(high), style=plot.style_linebr, title = "open profit % upper bound")
p2 = plot(profitPercent(low), style=plot.style_linebr, title = "open profit % lower bound")
fill(p1, p2, color = color.red) |
SuperTrend STRATEGY | https://www.tradingview.com/script/P5Gu6F8k/ | KivancOzbilgic | https://www.tradingview.com/u/KivancOzbilgic/ | 15,453 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KivancOzbilgic
//@version=4
strategy("SuperTrend STRATEGY", overlay=true)
Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
barcoloring = input(title="Bar Coloring On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
FromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2018, title = "From Year", minval = 999)
ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 999)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() => time >= start and time <= finish ? true : false
longCondition = buySignal
if (longCondition)
strategy.entry("BUY", strategy.long, when = window())
shortCondition = sellSignal
if (shortCondition)
strategy.entry("SELL", strategy.short, when = window())
buy1= barssince(buySignal)
sell1 = barssince(sellSignal)
color1 = buy1[1] < sell1[1] ? color.green : buy1[1] > sell1[1] ? color.red : na
barcolor(barcoloring ? color1 : na) |
Coppock Curve Strategy | https://www.tradingview.com/script/p814r9C5-Coppock-Curve-Strategy/ | RolandoSantos | https://www.tradingview.com/u/RolandoSantos/ | 516 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RolandoSantos
//@version=4
strategy(title = "Coppock Curve", shorttitle = "Copp Curve Strat", default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)
//Make inputs that set the take profit %
longProfitPerc = input(title="Take Profit % (How much stock has to rise from entry to trigger take profit) Using tighter % will have higher win rates (try 5% as an example). Using looser will produce bigger winners w/ lower win rates.", minval=0.0, step=0.1, defval=50) / 100
tp = input(25, "Take Profit % QTY (How much profit you want to take after take profit target is triggered)")
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
//Use NYSE for Copp Curve entries and exits//
security = input("NYA", title="Change this if you want to see Copp Curve calculated for current ticker. All Copp Curve calculations are base on NYSE Composite")
ticker = security(security,"", close)
///Copp Curve////
instructions =input(title="Standard Copp settings are (10, 14, 11) however, DOUBLE these lengths as alternate settings to (20,28,22) and you will find it may produce better results, but less trades", defval="-")
wmaLength = input(title="WMA Length (Experiment changing this to longer lengths for less trades, but higher win %)", type=input.integer, defval=10)
longRoCLength = input(title="Long RoC Length", type=input.integer, defval=14)
shortRoCLength = input(title="Short RoC Length", type=input.integer, defval=11)
source = ticker
curve = wma(roc(source, longRoCLength) + roc(source, shortRoCLength), wmaLength)
///Lower Band Plot///
band1 = hline(0)
band0 = hline(100)
band2 = hline(-100)
fill(band1, band0, color=color.green, transp=90)
fill(band2, band1, color=color.red, transp=90)
copp_color = curve[1] < curve[0] ? curve[0] >= 0 ? #00ffff : #ffb74d : curve[0] >= 0 ? #009b9b : #f57c00
plot(curve, color=copp_color, style=plot.style_histogram)
///Trade Conditions///
Bull = curve > 0
Bear = curve < 0
/// Start date
startDate = input(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", defval=1970, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
///Entries and Exits//
if (Bull and afterStartDate)
strategy.entry("Long", strategy.long, comment = "LE")
if (Bear and afterStartDate)
strategy.close("Long", qty_percent=100, comment="close")
// Submit exit orders based on take profit price
if (strategy.position_size > 0 and afterStartDate)
strategy.exit(id="Long Take Profit", qty_percent=tp, limit=longExitPrice)
|
BV's ICHIMOKU CLOUD - All Signals | https://www.tradingview.com/script/g2YGKu0q-BV-s-ICHIMOKU-CLOUD-All-Signals/ | BVTradingJournal | https://www.tradingview.com/u/BVTradingJournal/ | 237 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vuagnouxb
//@version=4
strategy("BV's ICHIMOKU CLOUD SIGNAL TESTER", overlay=true)
// Signal imputs
signalChoice = input(title = "SIGNAL - Choose your signal", defval = "Tenkan/Kijun", options = ["Tenkan/Kijun", "Tenkan/Kijun+Kumo", "Price/Tenkan", "Price/Tenkan+Kumo", "Price/Kijun", "Price/Kijun+Kumo", "Price/Kumo", "Kumo Color"])
JPYPair = input(type = input.bool, title = "ATR - Check if JPY Pair ", defval = false)
//------------------------------------------------------------------------
//---------- ICHIMOKU CLOUD Calculation ----------- INPUT
//------------------------------------------------------------------------
conversionPeriods = input(9, minval=1, title="Conversion Line Periods"),
basePeriods = input(26, minval=1, title="Base Line Periods")
laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Periods"),
displacement = input(26, minval=1, title="Displacement")
donchian(len) => avg(lowest(len), highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
plot(conversionLine, color=#0496ff, title="Conversion Line")
plot(baseLine, color=#991515, title="Base Line")
plot(close, offset = -displacement + 1, color=#459915, title="Lagging Span")
p1 = plot(leadLine1, offset = displacement - 1, color=color.green,
title="Lead 1")
p2 = plot(leadLine2, offset = displacement - 1, color=color.red,
title="Lead 2")
fill(p1, p2, color = leadLine1 > leadLine2 ? color.green : color.red)
kumoHigh = max(leadLine1[displacement-1], leadLine2[displacement-1])
kumoLow = min(leadLine1[displacement-1], leadLine2[displacement-1])
// -- Trade entry signals
continuationSignalLong = signalChoice == "Tenkan/Kijun" ? crossover(conversionLine, baseLine) :
signalChoice == "Tenkan/Kijun+Kumo" ? crossover(conversionLine, baseLine) and close > kumoHigh :
signalChoice == "Price/Tenkan" ? crossover(close, conversionLine) :
signalChoice == "Price/Tenkan+Kumo" ? crossover(close, conversionLine) and close > kumoHigh :
signalChoice == "Price/Kijun" ? crossover(close, baseLine) :
signalChoice == "Price/Kijun+Kumo" ? crossover(close, baseLine) and close > kumoHigh :
signalChoice == "Price/Kumo" ? crossover(close, kumoHigh) :
signalChoice == "Kumo Color" ? crossover(leadLine1, leadLine2) :
false
continuationSignalShort = signalChoice == "Tenkan/Kijun" ? crossunder(conversionLine, baseLine) :
signalChoice == "Tenkan/Kijun+Kumo" ? crossunder(conversionLine, baseLine) and close < kumoLow :
signalChoice == "Price/Tenkan" ? crossunder(close, conversionLine) :
signalChoice == "Price/Tenkan+Kumo" ? crossunder(close, conversionLine) and close < kumoLow :
signalChoice == "Price/Kijun" ? crossunder(close, baseLine) :
signalChoice == "Price/Kijun+Kumo" ? crossunder(close, baseLine) and close < kumoLow :
signalChoice == "Price/Kumo" ? crossunder(close, kumoLow) :
signalChoice == "Kumo Color" ? crossunder(leadLine1, leadLine2) :
false
longCondition = continuationSignalLong
shortCondition = continuationSignalShort
//------------------------------------------------------------------------
//---------- ATR MONEY MANAGEMENT ------------
//------------------------------------------------------------------------
SLmultiplier = input(title = "ATR - Stop Loss Multiplier", type = input.float, defval = 1.5, step = 0.1)
TPmultiplier = input(title = "ATR - Take Profit Multiplier", type = input.float, defval = 1.0, step = 0.1)
pipAdjuster = JPYPair ? 1000 : 100000
ATR = atr(14) * pipAdjuster // 1000 for jpy pairs : 100000
SL = ATR * SLmultiplier
TP = ATR * TPmultiplier
//------------------------------------------------------------------------
//---------- TIME FILTER ------------
//------------------------------------------------------------------------
YearOfTesting = input(title = "Time - How many years of testing ?" , type = input.integer, defval = 3)
_time = 2020 - YearOfTesting
timeFilter = (year > _time)
//------------------------------------------------------------------------
//--------- ENTRY FUNCTIONS ----------- INPUT
//------------------------------------------------------------------------
if (longCondition and timeFilter)
strategy.entry("Long", strategy.long)
if (shortCondition and timeFilter)
strategy.entry("Short", strategy.short)
//------------------------------------------------------------------------
//--------- EXIT FUNCTIONS -----------
//------------------------------------------------------------------------
strategy.exit("ATR", from_entry = "Long", profit = TP, loss = SL)
strategy.exit("ATR", from_entry = "Short", profit = TP, loss = SL) |
Grid System With Fake Martingale | https://www.tradingview.com/script/MmqKTgfH-Grid-System-With-Fake-Martingale/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 375 | strategy | 4 | CC-BY-SA-4.0 | // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/
// © alexgrover
//@version=4
strategy("Grid System With Fake Martingale",process_orders_on_close=true)
point = input(1.)
os = input(1,"Order Size")
mf = input(2.,"Martingale Multiplier")
anti = input(false,"Anti Martingale")
//------------------------------------------------------------------------------
baseline = 0.
baseline := nz(close > baseline[1] + point or close < baseline[1] - point ?
close : baseline[1],close)
//------------------------------------------------------------------------------
size = 0.
loss = change(strategy.losstrades)
win = change(strategy.wintrades)
if anti
size := win ? size[1]*mf : loss ? 1 : nz(size[1],os)
else
size := loss ? size[1]*mf : win ? 1 : nz(size[1],os)
upper = baseline + point*size
lower = baseline - point*size
//------------------------------------------------------------------------------
if baseline > baseline[1] and strategy.opentrades == 0
strategy.entry("Buy",strategy.long,qty=os)
strategy.exit("buy/tp/sl","Buy",stop=lower,limit=upper)
if baseline < baseline[1] and strategy.opentrades == 0
strategy.entry("Sell",strategy.short,qty=os)
strategy.exit("sell/tp/sl","Sell",stop=upper,limit=lower)
//------------------------------------------------------------------------------
cap = strategy.initial_capital
eq = strategy.equity
rmax = 0.
rmax := max(eq,nz(rmax[1]))
//----
css = eq > cap ? #0cb51a : #e65100
a = plot(eq,"Equity",#2196f3,2,transp=0)
b = plot(rmax,"Maximum",css,2,transp=0)
fill(a,b,css,80) |
VFI strategy [based on VFI indicator published by UTS] | https://www.tradingview.com/script/5jxP6TDu-VFI-strategy-based-on-VFI-indicator-published-by-UTS/ | mohanee | https://www.tradingview.com/u/mohanee/ | 265 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//This strategy is based on VFI indicator published by UTS.
//more details of VFI indicator can be found at [url=http://mkatsanos.com/VFI.html]http://mkatsanos.com/VFI.html[/url]
// I have added buy line and sell line to the indicator and tested SPY stock/index on one hour chart
//@version=4
strategy(title="VFI strategy [based on VFI indicator published by UTS]", overlay=false,pyramiding=2, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)
// Const
kMaColor = color.aqua
kNeutralColor = color.gray
kBearColor = color.red
kBullColor = color.green
kAlma = "ALMA"
kEma = "EMA"
kSma = "SMA"
kWma = "WMA"
// Input
vfi_length = input(8, title="Length", minval=1) //default 130
vfi_coef = input(0.2, title="Coef", minval=0.1)
vfi_volCutoff = input(2.5, title="Volume Cutoff", minval=0.1)
vfi_smoothLen = input(3, title="Smoothing Period", minval=1)
vfi_smoothType = input(kEma, title="Smoothing Type", options=[kAlma, kEma, kSma, kWma])
//These are adde by me for the strategy purpose BEGIN
vfi_buyLine = input(-4, title="Buy Line", minval=-10)
vfi_sellLine = input(5, title="Sell Line", minval=-10)
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
//These are adde by me for the strategy purpose END
vfi_longEMA = input(200, title="Long EMA", minval=1)
vfi_shortEMA1 = input(50, title="short EMA1", minval=1)
vfi_shortEMA2 = input(9, title="short EM2A", minval=1)
vfi_showTrend = input(false, title="Visualize Trend")
vfi_showFill = input(true, title="Apply Filling")
vfi_showMa = input(true, title="Show Moving Average")
vfi_maType = input(kSma, title="Moving Average Type", options=[kAlma, kEma, kSma, kWma])
vfi_maLength = input(30, title="Moving Average Length", minval=1)
vfi_almaOffset = input(0.85, title="• ALMA - Offset (global setting)", minval=0.0, maxval=1.0, step=0.05) // more smoothness (closer to 1) vs. more responsiveness (closer to 0)
vfi_almaSigma = input(6.0, title="• ALMA - Sigma (global setting)", minval=0.0, step=0.05) // the larger sigma the smoother ALMA
// Functionality
isRising(sig) =>
sig > sig[1]
isFlat(sig) =>
sig == sig[1]
vfi_trendColor(sig) =>
isFlat(sig) ? kNeutralColor : isRising(sig) ? kBullColor : kBearColor
vfi_color(sig) =>
isFlat(sig) ? kNeutralColor : sig > 0 ? kBullColor : kBearColor
osc_color(sig) =>
sig == 0 ? kNeutralColor : sig > 0 ? kBullColor : kBearColor
smooth(t, sig, len) =>
ma = float(sig) // None
if t == kSma // Simple
ma := sma(sig, len)
if t == kEma // Exponential
ma := ema(sig, len)
if t == kWma // Weighted
ma := wma(sig, len)
if t == kAlma // Arnaud Legoux
ma := alma(sig, len, vfi_almaOffset, vfi_almaSigma)
ma
calc_vfi(fviPeriod, smoothType, smoothLen, coef, vCoef) =>
avg = nz(hlc3)
inter = log(avg) - log(avg[1])
vInter = stdev(inter, 30)
cutOff = coef * vInter * close
vAve = smooth(kSma, volume[1], fviPeriod)
vMax = vAve * vCoef
vC = min(volume, vMax)
mf = avg - avg[1]
vCp = iff(mf > cutOff, vC, iff(mf < -cutOff, -vC, 0))
sVfi = sum(vCp, fviPeriod) / vAve
vfi = smooth(smoothType, sVfi, smoothLen)
value_vfi = calc_vfi(vfi_length, vfi_smoothType, vfi_smoothLen, vfi_coef, vfi_volCutoff)
value_ma = smooth(vfi_maType, value_vfi, vfi_maLength)
longEMAval= ema(close, vfi_longEMA)
shortEMAval1= ema(close, vfi_shortEMA1)
shortEMAval2= ema(close, vfi_shortEMA2)
color_vfi = vfi_showTrend ? vfi_trendColor(value_vfi) : vfi_color(value_vfi)
color_osc = vfi_showFill ? osc_color(value_vfi) : na
color_ma = vfi_showMa ? kMaColor : na
// Drawings
plot_vfi = plot(value_vfi, title="VFI", color=color_vfi, linewidth=1)
plot_fill = plot(0, color=color_vfi, editable=false)
fill(plot_vfi, plot_fill, title="Oscillator Fill", color=color_osc, transp=75)
hline(vfi_buyLine, color=color.green, title="Buy Line", linewidth=2, linestyle=hline.style_dashed)
hline(vfi_sellLine, color=color.purple, title="Sell Line", linewidth=2, linestyle=hline.style_dashed)
plot(value_ma, title="MA", color=color_ma, linewidth=2)
strategy.entry(id="VFI LE", long=true, when=crossover(value_vfi,vfi_buyLine) and ( shortEMAval1 >= longEMAval ))
//strategy.close(id="VFI LE", comment="Exit", when=crossunder(value_vfi,vfi_sellLine))
strategy.close(id="VFI LE", comment="TP Exit", when=crossunder(value_vfi,vfi_sellLine) and close>strategy.position_avg_price)
//strategy.close(id="VFI LE", comment="Exit", when= (shortEMAval1 > shortEMAval2 ) and crossunder(close, shortEMAval2))
//stoploss
stopLossVal = strategy.position_avg_price - (strategy.position_avg_price*stopLoss*0.01)
strategy.close(id="VFI LE", comment="SL Exit", when=crossunder(value_vfi,vfi_sellLine) and close < stopLossVal)
|
Full strategy AllinOne with risk management MACD RSI PSAR ATR MA | https://www.tradingview.com/script/l7ELtgmb-Full-strategy-AllinOne-with-risk-management-MACD-RSI-PSAR-ATR-MA/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 3,033 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("EURUSD 1min strat RISK %% ", overlay=false, initial_capital = 1000)
// BACKTESTING RANGE
// From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 6, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2020, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
DST = 1 //day light saving for usa
//--- Europe
London = iff(DST==0,"0000-0900","0100-1000")
//--- America
NewYork = iff(DST==0,"0400-1500","0500-1600")
//--- Pacific
Sydney = iff(DST==0,"1300-2200","1400-2300")
//--- Asia
Tokyo = iff(DST==0,"1500-2400","1600-0100")
//-- Time In Range
timeinrange(res, sess) => time(res, sess) != 0
london = timeinrange(timeframe.period, London)
newyork = timeinrange(timeframe.period, NewYork)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate and (london or newyork)
//
//
// rsi
length = input( 5 )
overSold = input( 23 )
overBought = input( 72 )
price = close
vrsi = rsi(price, length)
co = crossover(vrsi, overSold)
cu = crossunder(vrsi, overBought)
// macd
fast_length_macd = input(title="Fast Length", type=input.integer, defval=12)
slow_length_macd = input(title="Slow Length", type=input.integer, defval=26)
src_macd = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=true)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=true)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src_macd, fast_length_macd) : ema(src_macd, fast_length_macd)
slow_ma = sma_source ? sma(src_macd, slow_length_macd) : ema(src_macd, slow_length_macd)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )
// sar
start = input(0.02)
increment = input(0.02)
maximum = input(0.2)
var bool uptrend = na
var float EP = na
var float SAR = na
var float AF = start
var float nextBarSAR = na
if bar_index > 0
firstTrendBar = false
SAR := nextBarSAR
if bar_index == 1
float prevSAR = na
float prevEP = na
lowPrev = low[1]
highPrev = high[1]
closeCur = close
closePrev = close[1]
if closeCur > closePrev
uptrend := true
EP := high
prevSAR := lowPrev
prevEP := high
else
uptrend := false
EP := low
prevSAR := highPrev
prevEP := low
firstTrendBar := true
SAR := prevSAR + start * (prevEP - prevSAR)
if uptrend
if SAR > low
firstTrendBar := true
uptrend := false
SAR := max(EP, high)
EP := low
AF := start
else
if SAR < high
firstTrendBar := true
uptrend := true
SAR := min(EP, low)
EP := high
AF := start
if not firstTrendBar
if uptrend
if high > EP
EP := high
AF := min(AF + increment, maximum)
else
if low < EP
EP := low
AF := min(AF + increment, maximum)
if uptrend
SAR := min(SAR, low[1])
if bar_index > 1
SAR := min(SAR, low[2])
else
SAR := max(SAR, high[1])
if bar_index > 1
SAR := max(SAR, high[2])
nextBarSAR := SAR + AF * (EP - SAR)
//plot(SAR, style=plot.style_cross, linewidth=3, color=color.orange)
//plot(nextBarSAR, style=plot.style_cross, linewidth=3, color=color.aqua)
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
//bb
length_bb = input(17, minval=1)
src_bb = input(close, title="Source")
mult_bb = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis_bb = sma(src_bb, length_bb)
dev_bb = mult_bb * stdev(src_bb, length_bb)
upper_bb = basis_bb + dev_bb
lower_bb = basis_bb - dev_bb
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
//plot(basis_bb, "Basis", color=#872323, offset = offset)
//p1_bb = plot(upper_bb, "Upper", color=color.teal, offset = offset)
//p2_bb = plot(lower_bb, "Lower", color=color.teal, offset = offset)
//fill(p1_bb, p2_bb, title = "Background", color=#198787, transp=95)
//ema
len_ema = input(10, minval=1, title="Length")
src_ema = input(close, title="Source")
offset_ema = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out_ema = ema(src_ema, len_ema)
//plot(out_ema, title="EMA", color=color.blue, offset=offset_ema)
//out_ema e emaul
//basis_bb e middle de la bb
//hist e histograma
// rsi cu band0 cross pt rsi
// confirmarea
shortCondition = (uptrend==false and crossunder(ema(src_ema, len_ema),sma(src_bb, length_bb)) and hist < 0 and vrsi < overSold) //and time_cond
longCondition = (uptrend==true and crossover(ema(src_ema, len_ema),sma(src_bb, length_bb)) and hist > 0 and vrsi > overBought ) //and time_cond
//tp=input(0.0025,type=input.float, title="tp")
//sl=input(0.001,type=input.float, title="sl")
//INDICATOR---------------------------------------------------------------------
//Average True Range (1. RISK)
atr_period = input(14, "Average True Range Period")
atr = atr(atr_period)
//MONEY MANAGEMENT--------------------------------------------------------------
balance = strategy.netprofit + strategy.initial_capital //current balance
floating = strategy.openprofit //floating profit/loss
risk = input(2,type=input.float,title="Risk %")/100 //risk % per trade
isTwoDigit = input(false,"Is this a 2 digit pair? (JPY, XAU, XPD...")
equity_protector = input(1 ,type=input.float, title="Equity Protection %")/100 //equity protection %
equity_protectorTP = input(2 ,type=input.float, title="Equity TP %")/100 //equity protection %
multtp = input(5,type=input.float, title="multi atr tp")
multsl = input(5,type=input.float, title="multi atr sl")
stop = atr*100000*input(1,"SL X")* multsl //Stop level
if(isTwoDigit)
stop := stop/100
target = atr*100000*input(1,"TP X")*multtp //Stop level
//Calculate current DD and determine if stopout is necessary
equity_stopout = false
if(floating<0 and abs(floating/balance)>equity_protector)
equity_stopout := true
equity_stopout2 = false
if(floating>0 and abs(floating/balance)>equity_protectorTP)
equity_stopout2 := true
//Calculate the size of the next trade
temp01 = balance * risk //Risk in USD
temp02 = temp01/stop //Risk in lots
temp03 = temp02*100000 //Convert to contracts
size = temp03 - temp03%1000 //Normalize to 1000s (Trade size)
if(size < 10000)
size := 10000 //Set min. lot size
//TRADE EXECUTION---------------------------------------------------------------
strategy.close_all(equity_stopout, comment="equity sl", alert_message = "equity_sl") //Close all trades w/equity protector
//strategy.close_all(equity_stopout2, comment="equity tp", alert_message = "equity_tp") //Close all trades w/equity protector
is_open = strategy.opentrades > 0
strategy.entry("long",true,size,oca_name="a",oca_type=strategy.oca.cancel,when=longCondition and not is_open) //Long entry
strategy.entry("short",false,size,oca_name="a",oca_type=strategy.oca.cancel,when=shortCondition and not is_open) //Short entry
strategy.exit("exit_long","long",loss=stop, profit=target) //Long exit (stop loss)
strategy.close("long",when=shortCondition) //Long exit (exit condition)
strategy.exit("exit_short","short",loss=stop, profit=target) //Short exit (stop loss)
strategy.close("short",when=longCondition) //Short exit (exit condition)
//strategy.entry("long", strategy.long,size,when=longCondition , comment="long" , alert_message = "long")
//strategy.entry("short", strategy.short, size,when=shortCondition , comment="short" , alert_message = "short")
//strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, alert_message = "closelong")
//strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, alert_message = "closeshort")
//strategy.exit("closelong", "long" ,size, profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong")
//strategy.exit("closeshort", "short" , size, profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
//strategy.close("long" , when=not (time_cond), comment="time", alert_message = "closelong" )
//strategy.close("short" , when=not (time_cond), comment="time", alert_message = "closeshort")
//strategy.close_all(when=not (time_cond), comment ='time')
|
Daytrade strategy RSI CCI EMA 4/8 | https://www.tradingview.com/script/5zEiJjGu-Daytrade-strategy-RSI-CCI-EMA-4-8/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 388 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy(title="Moving Average Exponential", shorttitle="EMA", overlay=true)
len4 = input(4, minval=1, title="Length_MA4")
src4 = input(close, title="Source")
offset4 = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out4 = ema(src4, len4)
plot(out4, title="EMA", color=color.blue, offset=offset4)
len8 = input(8, minval=1, title="Length_MA8")
src8 = input(close, title="Source")
offset8 = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out8 = ema(src8, len8)
plot(out8, title="EMA", color=color.blue, offset=offset8)
//rsioma
src = close, len = input(14, minval=1, title="Length")
up = rma(max(change(ema(src, len)), 0), len)
down = rma(-min(change(ema(src, len)), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
//plot(rsi, color=color.blue)
//band1 = hline(80)
//band0 = hline(20)
//fill(band1, band0, color=color.purple, transp=90)
//hline(50, color=color.gray, linestyle=plot.style_line)
sig = ema(rsi, 21)
//plot(sig, color=color.purple)
//woodie
cciTurboLength = input(title="CCI Turbo Length", type=input.integer, defval=6, minval=3, maxval=14)
cci14Length = input(title="CCI 14 Length", type=input.integer, defval=14, minval=7, maxval=20)
source = close
cciTurbo = cci(source, cciTurboLength)
cci14 = cci(source, cci14Length)
last5IsDown = cci14[5] < 0 and cci14[4] < 0 and cci14[3] < 0 and cci14[2] < 0 and cci14[1] < 0
last5IsUp = cci14[5] > 0 and cci14[4] > 0 and cci14[3] > 0 and cci14[2] > 0 and cci14[1] > 0
histogramColor = last5IsUp ? color.green : last5IsDown ? color.red : cci14 < 0 ? color.green : color.red
// Exit Condition
// Exit Condition
a = input(12)*10
b = input(15)*10
c = a*syminfo.mintick
d = b*syminfo.mintick
longCondition = crossover(out4, out8) and (rsi >= 65 and cci14>=0)
shortCondition = crossunder(out4, out8) and (rsi <=35 and cci14<=0)
long_stop_level = float(na)
long_profit_level1 = float(na)
long_profit_level2 = float(na)
long_even_level = float(na)
short_stop_level = float(na)
short_profit_level1 = float(na)
short_profit_level2 = float(na)
short_even_level = float(na)
long_stop_level := longCondition ? close - c : long_stop_level [1]
long_profit_level1 := longCondition ? close + d : long_profit_level1 [1]
//long_profit_level2 := longCondition ? close + d : long_profit_level2 [1]
//long_even_level := longCondition ? close + 0 : long_even_level [1]
short_stop_level := shortCondition ? close + c : short_stop_level [1]
short_profit_level1 := shortCondition ? close - d : short_profit_level1 [1]
//short_profit_level2 := shortCondition ? close - d : short_profit_level2 [1]
//short_even_level := shortCondition ? close + 0 : short_even_level [1]
//ha
// === Input ===
//ma1_len = input(1, title="MA 01")
//ma2_len = input(40, title="MA 02")
// === MA 01 Filter ===
//o=ema(open,ma1_len)
//cc=ema(close,ma1_len)
//h=ema(high,ma1_len)
//l=ema(low,ma1_len)
// === HA calculator ===
//ha_t = heikinashi(syminfo.tickerid)
//ha_o = security(ha_t, timeframe.period, o)
//ha_c = security(ha_t, timeframe.period, cc)
//ha_h = security(ha_t, timeframe.period, h)
//ha_l = security(ha_t, timeframe.period, l)
// === MA 02 Filter ===
//o2=ema(ha_o, ma2_len)
//c2=ema(ha_c, ma2_len)
//h2=ema(ha_h, ma2_len)
//l2=ema(ha_l, ma2_len)
// === Color def ===
//ha_col=o2>c2 ? color.red : color.lime
// === PLOTITING===
//plotcandle(o2, h2, l2, c2, title="HA Smoothed", color=ha_col)
tp=input(120)
sl=input(96)
strategy.entry("long", strategy.long, when = longCondition)
//strategy.close("long", when = o2>c2 , comment="ha_long")
strategy.entry("short", strategy.short , when =shortCondition )
//strategy.close("short", when = o2<=c2 , comment = "ha_short" )
//strategy.close("long",when=long_profit_level1 or long_stop_level , comment="tp/sl")
//strategy.close("short",when=short_profit_level1 or short_stop_level , comment="tp/sl")
strategy.exit("x_long","long",profit = tp, loss = sl) //when = o2>c2)
strategy.exit("x_short","short",profit = tp, loss = sl) //when = o2<c2)
|
MACD+ Strategy [SystemAlpha] | https://www.tradingview.com/script/DDSoV1Tu-MACD-Strategy-SystemAlpha/ | systemalphatrader | https://www.tradingview.com/u/systemalphatrader/ | 197 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © systemalphatrader
//@version=4
strategy(title="MACD Strategy", shorttitle="MACD Strategy [PUBLIC]", overlay=true, initial_capital=10000, currency='USD',
default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.04)
// == /MAIN INPUT ==
/////////////////////////////////////
//*STRATEGY LOGIC *//
/////////////////////////////////////
// == MACD ==
fastLength = input(12, title="Fast Length")
slowlength = input(26, title="Slow Length")
MACDLength = input(9, title="MACD Length")
MACD = ema(close, fastLength) - ema(close, slowlength)
aMACD = ema(MACD, MACDLength)
delta = MACD - aMACD
// Calc breakouts
buySignal = crossover(delta, 0)
shortSignal = crossunder(delta,0)
// == /MACD ==
//////////////////////////
//* STRATEGY COMPONENT *//
//////////////////////////
// === BACKTEST RANGE ===
From_Year = input(defval = 2017, title = "BACKTEST: From Year")
From_Month = input(defval = 1, title = "BACKTEST: From Month", minval = 1, maxval = 12)
From_Day = input(defval = 1, title = "BACKTEST: From Day", minval = 1, maxval = 31)
To_Year = input(defval = 9999, title = "BACKTEST: To Year")
To_Month = input(defval = 1, title = "BACKTEST: To Month", minval = 1, maxval = 12)
To_Day = input(defval = 1, title = "BACKTEST: To Day", minval = 1, maxval = 31)
Start = timestamp(From_Year, From_Month, From_Day, 00, 00) // backtest start window
Finish = timestamp(To_Year, To_Month, To_Day, 23, 59) // backtest finish window
testPeriod() =>
time >= Start and time <= Finish ? true : false
// === /BACKTEST RANGE ===
// === STRATEGY ===
// Make input option to configure trade direction
tradeDirection = input(title="Trade Direction", defval="Both", options=["Long", "Short", "Both"])
// Translate input into trading conditions
longOK = (tradeDirection == "Long") or (tradeDirection == "Both")
shortOK = (tradeDirection == "Short") or (tradeDirection == "Both")
// == STRATEGY ENTRIES/EXITS ==
longCondition = longOK and buySignal and testPeriod()
shortcondition = shortOK and shortSignal and testPeriod()
// === STRATEGY - LONG POSITION EXECUTION ===
if longCondition
strategy.entry("Long", strategy.long)
// === STRATEGY - SHORT POSITION EXECUTION ===
if shortcondition
strategy.entry("Short", strategy.short)
// === /STRATEGY ===
//EOF |
Candle checker for long/short for scalping/day trading | https://www.tradingview.com/script/cg0RYN3n-Candle-checker-for-long-short-for-scalping-day-trading/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 125 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("My Script")
greenCandle = (close > open)
redCandle = (close < open)
//if(close[9] < close[8] and close[8] < close[7] and close[7] < close[6] and close[6] < close[5] and close[5] < close[4] and close[4] < close[3] and close[3] < close[2] and close[2] < close[1] and close[1] < close)
if(close[11] < close[10] and close[10] < close[9] and close[9] < close[8] and close[8] < close[7] and close[7] < close[6] and close[6] < close[5] and close[5] < close[4] and close[4] < close[3] and close[3] < close[2] and close[2] < close[1] and close[1] < close)
strategy.entry("long",1)
if(close[11] > close[10] and close[10] > close[9] and close[9] > close[8] and close[8] > close[7] and close[7] > close[6]and close[6] > close[5] and close[5] > close[4] and close[4] > close[3] and close[3] > close[2] and close[2] > close[1] and close[1] > close)
strategy.entry("short",0)
if(redCandle)
strategy.close("long")
if(greenCandle)
strategy.close("short")
tp = input(150)
sl = input(50)
strategy.exit("tp/sl","long", loss=sl, profit=tp)
strategy.exit("tp/sl","short", loss=sl, profit=tp) |
VWAP and RSI strategy | https://www.tradingview.com/script/oDnkONvx-VWAP-and-RSI-strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 631 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="VWAP and RSI strategy [EEMANI] v2", overlay=false,pyramiding=2, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)
//This strategy combines VWAP and RSI indicators
//BUY RULE
//1. EMA50 > EMA 200
//2. if current close > vwap session value and close>open
//3. check if RSI3 is dipped below 10 for any of last 10 candles
//EXIT RULE
//1. RSI3 crossing down 90 level
//STOP LOSS EXIT
//1. As configured --- default is set to 5%
int barCount = 0
// variables BEGIN
longEMA = input(200, title="Long EMA", minval=1)
shortEMA = input(50, title="short EMA", minval=1)
rsi1 = input(3,title="RSI Period", minval=1)
rsi_buy_line = input(15,title="RSI Buy Line", minval=5)
rsi_sell_line = input(90,title="RSI Sell Line", minval=50)
add_on_divergence=input(true,title="Add on RSI divergence")
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
//variables END
longEMAval= ema(close, longEMA)
shortEMAval= ema(close, shortEMA)
rsiVal=rsi(close,rsi1)
vwapVal=vwap(hlc3)
// Drawings
plot_rsi = plot(rsiVal, title="RSI", color=color.purple, linewidth=1)
//plot_fill = plot(0, color=color.green, editable=false)
//fill(plot_rsi, plot_fill, title="Oscillator Fill", color=color.blue, transp=75)
hline(rsi_buy_line, color=color.green, title="Buy Line", linewidth=2, linestyle=hline.style_dashed)
hline(rsi_sell_line, color=color.purple, title="Sell Line", linewidth=2, linestyle=hline.style_dashed)
//plot(value_ma, title="MA", color=color_ma, linewidth=2)
rsiDipped=false
for i = 1 to 10
rsiDipped := rsiDipped or rsiVal[i]<rsi_buy_line
//rsiDipped = rsiVal[1]<rsi_buy_line or rsiVal[2]<rsi_buy_line or rsiVal[3]<rsi_buy_line or rsiVal[4]<rsi_buy_line or rsiVal[5]<rsi_buy_line or rsiVal[6]<rsi_buy_line or rsiVal[7]<rsi_buy_line or rsiVal[8]<rsi_buy_line or rsiVal[9]<rsi_buy_line or rsiVal[10]<rsi_buy_line
longCondition= shortEMAval > longEMAval and close>open and close>vwapVal and open>vwapVal and rsiDipped
//Entry
strategy.entry(id="VWAP_RSI LE", comment="VR LE" , long=true, when= longCondition and strategy.position_size<1 ) //and rsiDipped
//Add
//barCount:=nz(barssince(longCondition),1)
barCount := strategy.position_size>0 ? (barCount[1]+1) : 0
addCondition = add_on_divergence and barCount[1] > 1 and strategy.position_size>=1 and close<=close[barCount[1]] and rsiVal>rsiVal[barCount+1] and close>open and close>vwapVal //and open>vwapVal
strategy.entry(id="VWAP_RSI LE", comment="Add " , long=true, when= addCondition ) //and rsiDipped comment="Add " +tostring(barCount[1],"####")
bgcolor(add_on_divergence and addCondition ? color.green : na,transp=0)
//Take profit Exit
strategy.close(id="VWAP_RSI LE", comment="TP Exit", when=crossunder(rsiVal,90) )
//stoploss
stopLossVal = strategy.position_avg_price - (strategy.position_avg_price*stopLoss*0.01)
strategy.close(id="VWAP_RSI LE", comment="SL Exit", when= close < stopLossVal)
|
Gap Down Reversal Strategy | https://www.tradingview.com/script/1krAOcR5-Gap-Down-Reversal-Strategy/ | RolandoSantos | https://www.tradingview.com/u/RolandoSantos/ | 366 | strategy | 2 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RolandoSantos
//@version=2
strategy(title="Gap Down reversal strat", overlay=true, pyramiding=1, default_qty_type = strategy.cash, default_qty_value = 10000, initial_capital = 10000 )
/// Start date
startDate = input(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", defval=2009, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
// Configure trail stop level with input options (optional)
longTrailPerc = input(title="Trail Long Loss (%)",
type=float, minval=0.0, step=0.1, defval=5.0) * 0.01
// Calculate trading conditions
gap_d_r = close[1] < open[1] and open < low[1] and close > open
// Plot Shapes
plotshape(gap_d_r, style=shape.triangleup, location=location.belowbar)
///plotshape(gap_u_r, style=shape.triangledown, location=location.abovebar)
// Determine trail stop loss prices
longStopPrice = 0.0 ///, shortStopPrice = 0.0
longStopPrice := if (strategy.position_size > 0)
stopValue = open * (1 - longTrailPerc)
max(stopValue, longStopPrice[1])
else
0
// Plot stop loss values for confirmation
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
color=red, style=circles,
linewidth=1, title="Long Trail Stop")
// Entry orders
if (afterStartDate and gap_d_r)
strategy.entry(id="EL", long=true)
// Exit orders for trail stop loss price
if (strategy.position_size > 0)
strategy.exit(id="Stop out", stop=longStopPrice)
|
Simple and efficient 1h strategy | https://www.tradingview.com/script/o0mu3bHS-Simple-and-efficient-1h-strategy/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 129 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 8, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
DST = 1 //day light saving for usa
//--- Europe
London = iff(DST==0,"0000-0900","0100-1000")
//--- America
NewYork = iff(DST==0,"0400-1300","0500-1400")
//--- Pacific
Sydney = iff(DST==0,"1300-2200","1400-2300")
//--- Asia
Tokyo = iff(DST==0,"1500-2400","1600-0100")
//-- Time In Range
timeinrange(res, sess) => time(res, sess) != 0
london = timeinrange(timeframe.period, London)
newyork = timeinrange(timeframe.period, NewYork)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate and (london or newyork)
strategy("4 8 RSI", overlay=true)
len = input(10, minval=1, title="Length")
src = input(hl2, "Source", type = input.source)
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
tp=input(500,"tp pip")
sl=input(500,"sl pip")
longCondition = crossover(ema(close, 4), ema(close, 8)) and rsi > rsi[1] and crossover(rsi,50) and time_cond
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
strategy.exit("longtp","long",profit=tp,loss=sl)
// strategy.close("long",when=crossunder(ema(close, 4), ema(close, 8)) or crossover(rsi,50), comment="cross_short")
shortCondition = crossunder(ema(close, 4), ema(close, 8)) and rsi < rsi[1] and crossunder(rsi,50) and time_cond
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
strategy.exit("shorttp","short",profit=tp,loss=sl)
// strategy.close("short", when=crossover(ema(close, 4), ema(close, 8)) or crossover(rsi,50), comment="cross_long")
strategy.close_all(when = not time_cond, comment="time", alert_message="time") |
SOJA PIVOT | https://www.tradingview.com/script/EeRgpJ7Z/ | ParaBellum68 | https://www.tradingview.com/u/ParaBellum68/ | 18 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ParaBellum68
//@version=4
strategy(title="SOJA PIVOT", shorttitle="SOJA PIVOT")
soja = ((cmo(close,5) > 25) and (cmo(close,5) < 70) and (close> close[1]) and (bbw(close,50,1) < 0.6) and (sum(volume,5)> 250000) and (obv[5]>15))
TP = 2.1 * hlc3[1]- high[1]
TP2 = TP + high[1] - low[1]
SL = avg(close,14) - 3*atr(14)
strategy.entry("buy", true, 1, when = soja == 1)
strategy.close("buy", when = close > TP, qty_percent = 25)
strategy.close("buy", when = close > TP2, qty_percent = 25)
strategy.exit("stop", "exit", when = close < SL)
|
percentrank strategy | https://www.tradingview.com/script/YOGMYvw8-percentrank-strategy/ | Alex_Dyuk | https://www.tradingview.com/u/Alex_Dyuk/ | 49 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Alex_Dyuk
//@version=4
strategy(title="percentrank", shorttitle="percentrank")
src = input(close, title="Source")
len = input(title="lookback - Период сравнения", type=input.integer, defval=10, minval=2)
scale = input(title="scale offset - смещение шкалы", type=input.integer, defval=50, minval=0, maxval=100)
level_1 = input(title="sygnal line 1", type=input.integer, defval=30)
level_2 = input(title="sygnal line 2", type=input.integer, defval=-30)
prank = percentrank(src,len)-scale
plot(prank, style = plot.style_columns)
plot(level_2, style = plot.style_line, color = color.red)
plot(level_1, style = plot.style_line, color = color.green)
longCondition = (crossunder(level_1, prank) == true)
if (longCondition)
strategy.entry("Long", strategy.long)
longExitCondition = (crossover(level_2, prank) == true)
if (longExitCondition)
strategy.close("Long")
shortCondition = (crossover(level_2, prank) == true)
if (shortCondition)
strategy.entry("Short", strategy.short)
shortexitCondition = (crossunder(level_1, prank) == true)
if (shortexitCondition)
strategy.close("Short")
|
MARKET DYNAMICS HH LL BREAKOUT | https://www.tradingview.com/script/xyov8Du1-MARKET-DYNAMICS-HH-LL-BREAKOUT/ | sincereLizard | https://www.tradingview.com/u/sincereLizard/ | 326 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sincereLizard
//@version=4
strategy(title="MD BANKNIFTY STRATEGY ", overlay=true,initial_capital=300000, default_qty_value=1)
strat_dir_input = input(title="Strategy Direction", defval="all", options=["long", "short", "all"])
strat_dir_value = strat_dir_input == "long" ? strategy.direction.long : strat_dir_input == "short" ? strategy.direction.short : strategy.direction.all
////
strategy.risk.allow_entry_in(strat_dir_value)
testStartYear = input(2016, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
//Stop date if you want to use a specific range of dates
testStopYear = input(2022, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
sl_inp = (input(2.0, title='Stop Loss %', type=input.float))/100
tp_inp = (input(7.0, title='Take Profit %', type=input.float))/100
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
//Higher High or Lower Low Entry Inputs
price = input(close)
LookBack = input(26)
Highest = highest(LookBack)
Lowest = lowest(LookBack)
long = price > Highest[1]
short = price < Lowest[1]
avg_price = strategy.position_avg_price
stop_level = avg_price * (1 - sl_inp)
take_level = avg_price * (1 + tp_inp)
//Safety Confirmation Inputs - Helps to thin out false breakouts or break downs
length = input(10)
High_Guard = highest(length)
Low_Guard = lowest(length)
length2 = input(1)
long1 = long == 1 and (Highest[1] > High_Guard[length2])
short1 = short == 1 and Lowest[1] < Low_Guard[length2]
long_exit = short1 or (close < stop_level) or (close > take_level)
short_exit = long1 or (close > take_level) or (close < stop_level)
if strat_dir_input == "long"
strategy.entry("Long", strategy.long, when=long1 and testPeriod())
strategy.close(id = "Long", when = long_exit)
if strat_dir_input == "short"
strategy.entry("Short", strategy.short, when=short1 and testPeriod())
strategy.close(id = "Short", when = short_exit)
if strat_dir_input =="all"
strategy.entry("Long",strategy.long, when=long1 and testPeriod())
strategy.entry("Short", strategy.short, when=short1 and testPeriod())
|
Grab Trading System | https://www.tradingview.com/script/1HAKnNRc-Grab-Trading-System/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 3,024 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue
//@version=4
strategy("Grab Trading System", overlay = true)
flb = input(defval = 80, title = "Longterm Period", minval = 1)
slb = input(defval = 21, title = "Shortterm Period", minval = 1)
showtarget = input(defval = true, title = "Show Target")
showtrend = input(defval = true, title = "Show Trend")
major_resistance = highest(flb)
major_support = lowest(flb)
minor_resistance = highest(slb)
minor_support = lowest(slb)
var int trend = 0
trend := high > major_resistance[1] ? 1 : low < major_support[1] ? -1 : trend
strategy.entry("Buy", true, when = trend == 1 and low[1] == minor_support[1] and low > minor_support)
strategy.entry("Sell", false, when = trend == -1 and high[1] == minor_resistance[1] and high < minor_resistance)
if strategy.position_size > 0
strategy.exit("Buy", stop = major_support, comment = "Stop Buy")
if high[1] == minor_resistance[1] and high < minor_resistance
strategy.close("Buy", comment ="Close Buy")
if strategy.position_size < 0
strategy.exit("Sell", stop = major_resistance, comment = "Stop Sell")
if low[1] == minor_support[1] and low > minor_support
strategy.close("Sell", comment ="Close Sell")
if strategy.position_size != 0 and change(trend)
strategy.close_all()
majr = plot(major_resistance, color = showtrend and trend == -1 and trend[1] == -1 ? color.red : na)
majs = plot(major_support, color = showtrend and trend == 1 and trend[1] == 1 ? color.lime : na)
minr = plot(minor_resistance, color = showtarget and trend == 1 and strategy.position_size > 0 ? color.yellow : na, style = plot.style_circles)
mins = plot(minor_support, color = showtarget and trend == -1 and strategy.position_size < 0 ? color.yellow : na, style = plot.style_circles)
fill(majs, mins, color = showtrend and trend == 1 and trend[1] == 1 ? color.new(color.lime, 85) : na)
fill(majr, minr, color = showtrend and trend == -1 and trend[1] == -1 ? color.new(color.red, 85) : na)
|