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
|
---|---|---|---|---|---|---|---|---|
Donchian Channel Strategy [for free bot] | https://www.tradingview.com/script/KZuFvEYa-donchian-channel-strategy-for-free-bot/ | AlgoTrading_CC | https://www.tradingview.com/u/AlgoTrading_CC/ | 960 | 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/
// © algotradingcc
// Strategy testing and optimisation for free trading bot
//@version=4
strategy("Donchian Channel Strategy [for free bot]", overlay=true, default_qty_type= strategy.percent_of_equity, initial_capital = 1000, default_qty_value = 20, commission_type=strategy.commission.percent, commission_value=0.036)
//Long optopns
buyPeriodEnter = input(10, "Channel Period for Long enter position")
buyPeriodExit = input(10, "Channel Period for Long exit position")
isMiddleBuy = input(true, "Is exit on Base Line? If 'no' - exit on bottom line")
takeProfitBuy = input(2.5, "Take Profit (%) for Long position")
isBuy = input(true, "Allow Long?")
//Short Options
sellPeriodEnter = input(20, "Channel Period for Short enter position")
sellPeriodExit = input(20, "Channel Period for Short exit position")
isMiddleSell = input(true, "Is exit on Base Line? If 'no' - exit on upper line")
takeProfitSell = input(2.5, "Take Profit (%) for Short position")
isSell = input(true, "Allow Short?")
// Test Start
startYear = input(2005, "Test Start Year")
startMonth = input(1, "Test Start Month")
startDay = input(1, "Test Start Day")
startTest = timestamp(startYear,startMonth,startDay,0,0)
//Test End
endYear = input(2050, "Test End Year")
endMonth = input(12, "Test End Month")
endDay = input(30, "Test End Day")
endTest = timestamp(endYear,endMonth,endDay,23,59)
timeRange = time > startTest and time < endTest ? true : false
// Long&Short Levels
BuyEnter = highest(buyPeriodEnter)
BuyExit = isMiddleBuy ? ((highest(buyPeriodExit) + lowest(buyPeriodExit)) / 2): lowest(buyPeriodExit)
SellEnter = lowest(sellPeriodEnter)
SellExit = isMiddleSell ? ((highest(sellPeriodExit) + lowest(sellPeriodExit)) / 2): highest(sellPeriodExit)
// Plot Data
plot(BuyEnter, style=plot.style_line, linewidth=2, color=color.blue, title="Buy Enter")
plot(BuyExit, style=plot.style_line, linewidth=1, color=color.blue, title="Buy Exit", transp=50)
plot(SellEnter, style=plot.style_line, linewidth=2, color=color.red, title="Sell Enter")
plot(SellExit, style=plot.style_line, linewidth=1, color=color.red, title="Sell Exit", transp=50)
// Calc Take Profits
TakeProfitBuy = 0.0
TakeProfitSell = 0.0
if strategy.position_size > 0
TakeProfitBuy := strategy.position_avg_price*(1 + takeProfitBuy/100)
if strategy.position_size < 0
TakeProfitSell := strategy.position_avg_price*(1 - takeProfitSell/100)
// Long Position
if isBuy and timeRange
strategy.entry("Long", strategy.long, stop = BuyEnter, when = strategy.position_size == 0)
strategy.exit("Long Exit", "Long", stop=BuyExit, limit = TakeProfitBuy, when = strategy.position_size > 0)
// Short Position
if isSell and timeRange
strategy.entry("Short", strategy.short, stop = SellEnter, when = strategy.position_size == 0)
strategy.exit("Short Exit", "Short", stop=SellExit, limit = TakeProfitSell, when = strategy.position_size < 0)
// Close & Cancel when over End of the Test
if time > endTest
strategy.close_all()
strategy.cancel_all()
|
ATR_Trade_strategy | https://www.tradingview.com/script/BvzhuW99-ATR-Trade-strategy/ | arameshraju | https://www.tradingview.com/u/arameshraju/ | 120 | 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/
// © arameshraju
//Thanks to Vamsikrishna Kona who planned this Idea in my mind. helped ot inprove it
//@version=4
strategy("ATR_Trade_strategy-2",shorttitle="ATR_Trade", overlay=true)
showMiddle = input(false, title="Show Middle Line", type=input.bool)
showEMA = input(true, title="Show EMA Line", type=input.bool)
showTypical = input(false, title="Show Typical Line", type=input.bool)
length = input(title="Length", defval=14, minval=1)
smoothing = input(title="Smoothing", defval="EMA", options=["RMA", "SMA", "EMA", "WMA"])
maxLoss = input(0.5, title="Max Loss on one Trade", type=input.float)
emaCount = input(10, title="EMA Periods", type=input.integer)
tradeQty = input(10, title="Trade Quanity", type=input.integer)
SlasMiddle = input(false, title="Stop Loss as Middle", type=input.bool)
onTypical = input(false, title="Trade on Typical", type=input.bool)
getSeries(_e, _timeFrame) => security(syminfo.tickerid, _timeFrame, _e, lookahead=barmerge.lookahead_on)
previousClose= getSeries(close[1], 'D')
previousHigh= getSeries(high[1], 'D')
previousLow= getSeries(low[1], 'D')
typicalPrice=(close+high+low)/3
mxloss=close*maxLoss
ma_function(source, length) =>
if smoothing == "RMA"
rma(source, length)
else
if smoothing == "SMA"
sma(source, length)
else
if smoothing == "EMA"
ema(source, length)
else
wma(source, length)
ATRH=ma_function(tr(true), length)+previousClose
ATRL=previousClose-ma_function(tr(true), length)
ATRM= (ATRH+ATRL)/2
plot(ATRH, title = "ATR-HIGH", color=#991515, transp=80)
plot(ATRL, title = "ATR-LOW", color=#991515, transp=80)
plot(showMiddle?ATRM:na, title = "ATR-MIDDLE", color=#80cbc4, transp=60)
plot(showTypical?typicalPrice:na, title = "ATR-MIDDLE", color=color.black)
plot(showEMA?ema(close, emaCount):na, color=color.blue)
lognCondition = onTypical? typicalPrice> (ATRH):close> (ATRH*1.01)
shortCondition = onTypical ? typicalPrice< (ATRL) : close< (ATRL)
// if onTypical
// lognCondition=typicalPrice> (ATRH)
// shortCondition = typicalPrice< (ATRL)
// else
// lognCondition=close> (ATRH*1.01)
// shortCondition = close< (ATRL)
if(lognCondition and year>2009)
strategy.entry("Buy", strategy.long, tradeQty,when=strategy.position_size <= 0)
if(shortCondition and year>2009)
strategy.entry("sell", strategy.short, tradeQty,when=strategy.position_size > 0)
strategy.close("buy", when = close < ema(close, emaCount), comment = "close if blow ema")
strategy.close("sell", when = close > ema(close, emaCount), comment = "close if blow ema")
strategy.close("buy", when = (close < ATRM) and SlasMiddle, comment = "close if blow ATRM")
strategy.close("sell", when = (close > ATRM) and SlasMiddle, comment = "close if ABOVE ATRM")
strategy.exit("Buy", "long", loss = mxloss)
strategy.exit("sell", "long", loss = mxloss)
//plot(strategy.equity) |
Trend trader Strategy | https://www.tradingview.com/script/BNXptz3U-Trend-trader-Strategy/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 113 | 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")
plot(close)
//if you want acess to the better version of this, just message me :) |
ARR-Pivote-India-Stategy | https://www.tradingview.com/script/1QDo390H-ARR-Pivote-India-Stategy/ | arameshraju | https://www.tradingview.com/u/arameshraju/ | 154 | 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/
// © arameshraju
//Reference credit goes to All
//@version=4
strategy("ARR-Pivote-India-Stategy",shorttitle="ARR-PP-Ind", overlay=true)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © arameshraju
//User Input
showPrevDayHighLow = input(false, title="Show previous day's High & Low(PDH/PDL)", type=input.bool)
showPivoteLine = input(true, title="Show Pivot Point(PP)", type=input.bool)
showPivoteR1Line = input(false, title="Show Pivot Point Resistance (R1)", type=input.bool)
showPivoteS1Line = input(false, title="Show Pivot Point Support (S1)", type=input.bool)
showTypicalPriceLine = input(true, title="Show True Price", type=input.bool)
tradeLong = input(true, title="Trade on Long Entry", type=input.bool)
tradeShort = input(false, title="Trade on Short Entry", type=input.bool)
maxLoss = input(0.5, title="Max Loss on one Trade", type=input.float)
tradeOn=input(title="Trade base Level", type=input.string,
options=["PP", "PDH", "PDL","R1","S1"], defval="PP")
closeHrs = input(13, title="Close all trade @ Hours", type=input.integer)
sessSpec = input("0915-1530", title="Session time", type=input.session)
// Defaults
// Colors
cColor = color.black
rColor = color.red
sColor = color.green
// Line style & Transparency
lStyle = plot.style_line
lTransp = 35
// Get High & Low
getSeries(_e, _timeFrame) => security(syminfo.tickerid, _timeFrame, _e, lookahead=barmerge.lookahead_on)
is_newbar(res, sess) =>
t = time(res, sess)
na(t[1]) and not na(t) or t[1] < t
newbar = is_newbar("375", sessSpec)
// Today's Session Start timestamp
y = year(timenow)
m = month(timenow)
d = dayofmonth(timenow)
// Start & End time for Today
start = timestamp(y, m, d, 09, 15)
end = start + 86400000
PrevDayHigh = getSeries(high[1], 'D')
PrevDayLow = getSeries(low[1], 'D')
PrevDayClose = getSeries(close[1], 'D')
PivoteLine=(PrevDayHigh+PrevDayLow+PrevDayClose) /3
PivoteR1=(PivoteLine*2) -PrevDayLow
PivoteS1=(PivoteLine*2) -PrevDayHigh
orbPrevDayOpen = getSeries(open[1], 'D')
orbPrevDayClose = getSeries(close[1], 'D')
//** True Price
TypicalPrice=(high[1]+low[1]+close[1])/3
//Preview Day High line
_pdh = line.new(start, PrevDayHigh, end, PrevDayHigh, xloc.bar_time, color=color.red, style=line.style_solid, width=2)
line.delete(_pdh[1])
_pdl = line.new(start, PrevDayLow, end, PrevDayLow, xloc.bar_time, color=color.green, style=line.style_solid, width=2)
line.delete(_pdl[1])
_Pp = line.new(start, PrevDayLow, end, PrevDayLow, xloc.bar_time, color=color.green, style=line.style_dashed, width=2)
line.delete(_Pp[1])
//Previous Day Low Line
l_pdh = label.new(start, PrevDayHigh, text="PD", xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
label.delete(l_pdh[1])
l_pdl = label.new(start, PrevDayLow, text="PD", xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
label.delete(l_pdl[1])
//Pivote Line
l_pp = label.new(start, PivoteLine, text="PP", xloc=xloc.bar_time, textcolor=color.black, style=label.style_none)
label.delete(l_pp[1])
l_R1 = label.new(start, PivoteR1, text="R1", xloc=xloc.bar_time, textcolor=color.fuchsia, style=label.style_none)
label.delete(l_pp[1])
l_SR = label.new(start, PivoteS1, text="S2", xloc=xloc.bar_time, textcolor=color.navy, style=label.style_none)
label.delete(l_pp[1])
plot(showTypicalPriceLine?TypicalPrice:na , title='TP', color=rColor)
plot(showPrevDayHighLow?PrevDayHigh:na , title=' PDH', color=rColor)
plot(showPrevDayHighLow?PrevDayLow:na, title=' PDL', color=sColor)
plot(showPivoteLine?PivoteLine:na, title=' PP', color=color.black)
plot(showPivoteR1Line?PivoteR1:na, title=' R1', color=color.fuchsia)
plot(showPivoteS1Line?PivoteS1:na, title=' S1', color=color.navy)
// Today's Session Start timestamp
// Start & End time for Today
//endTime = timestamp(t, m, d, 15, 00)
tradeEventPrice= if string("PDH")==tradeOn
PrevDayHigh
else if string("PDL")==tradeOn
PrevDayLow
else if string("R1")==tradeOn
PivoteR1
else if string("S1")==tradeOn
PivoteS1
else if string("TR")==tradeOn
TypicalPrice
else
PivoteLine
//tradeEventPrice=PrevDayHigh
if (open < tradeEventPrice) and ( close >tradeEventPrice ) and ( hour < (closeHrs-2) ) and tradeLong
strategy.entry("buy", strategy.long, 1, when=strategy.position_size <= 0)
if (open > tradeEventPrice) and ( close <tradeEventPrice ) and ( hour < (closeHrs-2) ) and tradeShort
strategy.entry("Sell", strategy.short, 1, when=strategy.position_size <= 0)
mxloss=orbPrevDayClose*maxLoss
strategy.exit("exit", "buy", loss = mxloss)
strategy.exit("exit", "Sell", loss = mxloss)
strategy.close_all(when = hour == closeHrs , comment = "close all entries")
|
Grid Like Strategy | https://www.tradingview.com/script/oxvR5vMy-Grid-Like-Strategy/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 1,929 | 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
// Don't trade me!
//@version=4
strategy("Grid Like Strategy",overlay=true,process_orders_on_close=true)
point = input(2.)
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)
upper = baseline + point
lower = baseline - point
//----
size = 0.
loss = change(strategy.losstrades)
win = change(strategy.wintrades)
if anti
size := win ? size[1]*mf : loss ? os : nz(size[1],os)
else
size := loss ? size[1]*mf : win ? os : nz(size[1],os)
//----
if baseline > baseline[1]
strategy.entry("Buy",strategy.long,qty=size)
strategy.exit("buy/tp/sl","Buy",stop=lower,limit=upper)
if baseline < baseline[1]
strategy.entry("Sell",strategy.short,qty=size)
strategy.exit("sell/tp/sl","Sell",stop=upper,limit=lower)
//----
plot(baseline,"Plot",#2157f3,2) |
MM tester | https://www.tradingview.com/script/0oH3f6yZ/ | diariodeunscalper | https://www.tradingview.com/u/diariodeunscalper/ | 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/
// © luisgzafra
//@version=4
strategy("MM tester", overlay=true)
// Inputs
//
int ema1 = input(title="MM1", defval=14, minval=0)
int ema2 = input(title="MM2", defval=28, minval=0)
//
tipo_MM = input(title="MM type", options=["EMA", "SMA"], defval="EMA")
//
MM1 = tipo_MM == "EMA"? ema(close, ema1) : sma(close, ema1)
MM2 = tipo_MM == "EMA"? ema(close, ema2) : sma(close, ema2)
//
plot (MM1, color = color.black)
plot (MM2, color = MM1 > MM2? color.red : color.green, linewidth=2)
//
longCondition = crossover(MM1, MM2)
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
//
shortCondition = crossunder(MM1, MM2)
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
// END |
S&P Bear Warning Indicator | https://www.tradingview.com/script/Opsgy6Zr-S-P-Bear-Warning-Indicator/ | gary_trades | https://www.tradingview.com/u/gary_trades/ | 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/
// © gary_trades
//THIS SCRIPT HAS BEEN BUIL TO BE USED AS A S&P500 SPY CRASH INDICATOR (should not be used as a strategy).
//THIS SCRIPT HAS BEEN BUILT AS A STRATEGY FOR VISUALIZATION PURPOSES ONLY AND HAS NOT BEEN OPTIMISED FOR PROFIT.
//The script has been built to show as a lower indicator and also gives visual SELL signal on top when conditions are met. BARE IN MIND NO STOP LOSS, NOR ADVANCED EXIT STRATEGY HAS BEEN BUILT.
//As well as the chart SELL signal an alert has also been built into this script.
//The script utilizes a VIX indicator (marron line) and 50 period Momentum (blue line) and Danger/No trade zone(pink shading).
//When the Momentum line crosses down across the VIX this is a sell off but in order to only signal major sell offs the SELL signal only triggers if the momentum continues down through the danger zone.
//To use this indicator to identify ideal buying then you should only buy when Momentum line is crossed above the VIX and the Momentum line is above the Danger Zone.
//This is best used as a daily time frame indicator
//@version=4
strategy(title="S&P Bear Warning", shorttitle="Bear Warning", pyramiding=0,
currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100,
initial_capital=1000, commission_value=0.1)
//Momentum
len = input(50, minval=1, title="Length")
src = input(close, title="Source")
bandUpper = input( 5)
bandLower = input(-5)
// ————— Control plotting of each signal. You could use the same technique to be able to turn acc/dist on/off.
showVixFix = input(true)
showMomentum = input(true)
mom = src - src[len]
myAtr = atr(14)
plot(showMomentum ? mom : na, color=color.blue, title="MOM")
plot(showMomentum ? 0 : na, color=color.silver, title="MOM Zero line", style=plot.style_circles, transp=100)
plot(showMomentum ? myAtr : na, color=color.orange, title="ATR", transp=90)
//VIX
VIXFixLength = input(22,title="VIX Fix Length")
VIXFix = (highest(close,VIXFixLength)-low)/(highest(close,VIXFixLength))*100
plot(showVixFix ? VIXFix : na, "VIXFix", color=color.maroon)
band1 = plot(showVixFix ? bandUpper : na, "Upper Band", color.red, 1, plot.style_line, transp=90)
band0 = plot(showVixFix ? bandLower : na, "Lower Band", color.red, 1, plot.style_line, transp=90)
fill(band1, band0, color=color.red, transp=85, title="Background")
//Identify Triggers
//Back Test Range
start = timestamp("America/New_York", 2000, 1, 1, 9,30)
end = timestamp("America/New_York", 2020, 7, 1, 0, 0)
//Momentum
Long1 = mom > bandUpper
Short1 = mom < bandLower
//VIX
Long2 = crossover(mom, VIXFix)
Short2 = crossunder(mom, VIXFix)
//Warning Alert
SellAlert = Short1
alertcondition(SellAlert, title="Sell SPY", message="Warning Selling off {{ticker}}, price= {{close}}")
//Entry and Exit
if time >= start and time <= end
strategy.entry("SELL", false, when = Short1)
strategy.close("SELL", when = Long2) |
ADX_TSI_Bol Band Trend Chaser | https://www.tradingview.com/script/3eAT532t-ADX-TSI-Bol-Band-Trend-Chaser/ | gary_trades | https://www.tradingview.com/u/gary_trades/ | 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/
// © gary_trades
//This script has been designed to be used on trending stocks as a low risk trade with minimal drawdown, utilising 200 Moving Average, Custom Bollinger Band, TSI with weighted moving average and ADX strength.
//Backtest dates are set to 2010 - 2020 and all other filters (moving average, ADX, TSI , Bollinger Band) are not locked so they can be user amended if desired.
//Buy signal is given when trading above the 200 moving average + 5 candles have closed above the upper custom Bollinger + the TSI is positive + ADX is above 20.
//As back testing proved that this traded better only in tends then some Sell/Short conditions have been removed and this focueses on Long orders.
//Only requires 2 additional lines of code to add shorting orders.
//Close for either long or short trades is signaled once the TSI crosses in the opposite direction indicating change in trend strength or if stop loss is trggered.
//Further optimization could be achieved by adding a stop loss.
//NOTE: This only shows the lower indicators however for visualization you can use my script "CUSTOM BOLLINGER WITH SMA", which is the upper indicators in this stratergy.
//------------
//@version=4
strategy(shorttitle="Trend Chaser", title="ADX_TSI_Bol Band Trend Chaser", overlay=false, pyramiding=0,
currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10,
initial_capital=10000, commission_value=0.1)
//------------
//Custom Bollinger Band
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(0.382, minval=0.001, maxval=50, title="StdDev")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=color.gray, offset = offset, display=display.none)
p1 = plot(upper, "Upper", color=color.gray, offset = offset, display=display.none)
p2 = plot(lower, "Lower", color=color.gray, offset = offset, display=display.none)
fill(p1, p2, title = "Background", color=#787B86, transp=85)
//------------
//Moving Average
MAlen = input(200, minval=1, title="Length")
MAout = sma(src, MAlen)
plot(MAout, color=color.black, title="MA", offset=offset, linewidth=2, display=display.none)
//------------
//True Strength WMA
TSlong = input(title="Long Length", type=input.integer, defval=25)
TSshort = input(title="Short Length", type=input.integer, defval=13)
TSsignal = input(title="Signal Length", type=input.integer, defval=52)
double_smooth(src, TSlong, TSshort) =>
fist_smooth = wma(src, TSlong)
wma(fist_smooth, TSshort)
price = close
pc = change(price)
double_smoothed_pc = double_smooth(pc, TSlong, TSshort)
double_smoothed_abs_pc = double_smooth(abs(pc), TSlong, TSshort)
tsi_value = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
tsi2 = wma(tsi_value, TSsignal)
plot(tsi_value, color=color.blue)
plot(wma(tsi_value, TSsignal), color=color.red)
hline(0, title="Zero")
//------------
//ADX
adxlen = input(13, title="ADX Smoothing")
dilen = input(13, title="DI Length")
keyLevel = input(20, title="Keylevel for ADX")
dirmov(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)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
plot(sig, color=color.black, title="ADX", style=plot.style_histogram, transp=40)
plot(20, color=color.green, title="ADX Keyline", linewidth=1)
//------------
//Identify Triggers
//Back Test Range
start = timestamp("America/New_York", 2010, 1, 1, 9,30)
end = timestamp("America/New_York", 2020, 7, 1, 0, 0)
//Custom Bollinger Band
Long1 = close > upper[5] and close[5] > upper [6]
Short1 = close < lower[5] and close[5] < lower [6]
//Moving Average
Long2 = close >= MAout[1]
Short2 = close <= MAout[1]
//True Strength WMA
Long3 = tsi_value > tsi2
Short3 = tsi_value < tsi2
//ADX
ADXkey = adx(dilen, adxlen) > 20 and adx(dilen, adxlen) < 100
//Buy
Buy = Long1 and Long2 and Long3 and ADXkey
CloseLong = crossunder(tsi_value,tsi2)
//Short
Sell = Short1 and Short2 and Short3 and ADXkey
CloseShort = crossover(tsi_value,tsi2)
//------------
//Entry and Exit
if time >= start and time <= end
strategy.entry("Long", true, when = Buy)
strategy.close("Long", when = CloseLong)
|
simple but effective | https://www.tradingview.com/script/jBvH2o3M-simple-but-effective/ | tucomprend | https://www.tradingview.com/u/tucomprend/ | 270 | 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/
// © tucomprend
//@version=4
strategy("simple but effective", overlay=true)
v1low = input(3, minval=1)
v1high = input(3, minval=1)
v2open = input(9, minval=1)
plot (sma(open, v2open))
plot (sma(high, v1high))
plot (sma(low, v1low))
longCondition = crossover(sma(high, v1high), sma(open, v2open))
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(sma(low, v1low), sma(open, v2open))
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short) |
Donchian Strat EXMO | https://www.tradingview.com/script/3rlTqNFH-Donchian-Strat-EXMO/ | pskoroplas | https://www.tradingview.com/u/pskoroplas/ | 67 | 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/
// © pskoroplas
//@version=4
strategy("Donchian Strat EXMO", overlay=true)
long_per = input(defval = 20, title = "Long Period")
h = highest(high, long_per)
l = lowest(low, long_per)
plot(l)
plot(h)
perc = close/100
if h[1] < h[2]
strategy.order("BUY", true, stop = h)
//strategy.exit("BUY", profit = 400)
if l[1] > l[2]
strategy.order("SELL", false, stop = l)
//strategy.exit("SELL", profit = 400)
|
Channel Break [for free bot] | https://www.tradingview.com/script/8vuKM6ZP-Channel-Break-for-free-bot/ | AlgoTrading_CC | https://www.tradingview.com/u/AlgoTrading_CC/ | 617 | 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/
// Strategy testing and optimisation for free Bitmex trading bot
// © algotradingcc
//@version=4
strategy("Channel Break [for free bot]", overlay=true, default_qty_type= strategy.percent_of_equity, initial_capital = 1000, default_qty_value = 20, commission_type=strategy.commission.percent, commission_value=0.075)
//Options
buyPeriod = input(13, "Channel Period for Long position")
sellPeriod = input(18, "Channel Period for Short position")
isMiddleExit = input(true, "Is exit on Base Line?")
takeProfit = input(46, "Take Profit (%) for position")
stopLoss = input(9, "Stop Loss (%) for position")
// Test Start
startYear = input(2005, "Test Start Year")
startMonth = input(1, "Test Start Month")
startDay = input(1, "Test Start Day")
startTest = timestamp(startYear,startMonth,startDay,0,0)
//Test End
endYear = input(2050, "Test End Year")
endMonth = input(12, "Test End Month")
endDay = input(30, "Test End Day")
endTest = timestamp(endYear,endMonth,endDay,23,59)
timeRange = time > startTest and time < endTest ? true : false
// Long&Short Levels
BuyEnter = highest(buyPeriod)
BuyExit = isMiddleExit ? (highest(buyPeriod) + lowest(buyPeriod)) / 2: lowest(buyPeriod)
SellEnter = lowest(sellPeriod)
SellExit = isMiddleExit ? (highest(sellPeriod) + lowest(sellPeriod)) / 2: highest(sellPeriod)
// Plot Data
plot(BuyEnter, style=plot.style_line, linewidth=2, color=color.blue, title="Buy Enter")
plot(BuyExit, style=plot.style_line, linewidth=1, color=color.blue, title="Buy Exit", transp=50)
plot(SellEnter, style=plot.style_line, linewidth=2, color=color.red, title="Sell Enter")
plot(SellExit, style=plot.style_line, linewidth=1, color=color.red, title="Sell Exit", transp=50)
// Calc Take Profits & Stop Loss
TP = 0.0
SL = 0.0
if strategy.position_size > 0
TP := strategy.position_avg_price*(1 + takeProfit/100)
SL := strategy.position_avg_price*(1 - stopLoss/100)
if strategy.position_size > 0 and SL > BuyExit
BuyExit := SL
if strategy.position_size < 0
TP := strategy.position_avg_price*(1 - takeProfit/100)
SL := strategy.position_avg_price*(1 + stopLoss/100)
if strategy.position_size < 0 and SL < SellExit
SellExit := SL
// Long Position
if timeRange and strategy.position_size <= 0
strategy.entry("Long", strategy.long, stop = BuyEnter)
strategy.exit("Long Exit", "Long", stop=BuyExit, limit = TP, when = strategy.position_size > 0)
// Short Position
if timeRange and strategy.position_size >= 0
strategy.entry("Short", strategy.short, stop = SellEnter)
strategy.exit("Short Exit", "Short", stop=SellExit, limit = TP, when = strategy.position_size < 0)
// Close & Cancel when over End of the Test
if time > endTest
strategy.close_all()
strategy.cancel_all()
|
Simple SMA Strategy Backtest Part 4 | https://www.tradingview.com/script/oosij7fN-Simple-SMA-Strategy-Backtest-Part-4/ | HPotter | https://www.tradingview.com/u/HPotter/ | 270 | 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
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)
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)
strategy.entry("Long", strategy.long)
if (possig == -1)
strategy.entry("Short", strategy.short)
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) |
Close Trade at end of day | https://www.tradingview.com/script/3qbvi1wm-Close-Trade-at-end-of-day/ | daytraderph | https://www.tradingview.com/u/daytraderph/ | 244 | 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/
// © daytraderph
//@version=4
strategy("Close Trade at end of day ", overlay=true,process_orders_on_close=true)
i_dateFilter = input(false, "═════ Date Range Filtering ═════")
i_fromYear = input(2020, "From Year", minval = 1900)
i_fromMonth = input(6, "From Month", minval = 1, maxval = 12)
i_fromDay = input(23, "From Day", minval = 1, maxval = 31)
i_toYear = input(2999, "To Year", minval = 1900)
i_toMonth = input(1, "To Month", minval = 1, maxval = 12)
i_toDay = input(1, "To Day", minval = 1, maxval = 31)
fromDate = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00)
toDate = timestamp(i_toYear, i_toMonth, i_toDay, 23, 59)
f_tradeDateIsAllowed() => not i_dateFilter or (time >= fromDate and time <= toDate)
numBars = 1
t = time('D')
if t == t[1]
numBars := nz(numBars[1]) + 1
else
numBars := 1
bool secondCandle= false
if numBars == 1
secondCandle :=true
open_session=input(type=input.session,defval="0915-1530")
session = time("1", open_session)
validSession=(na(session) ? 0 : 1)
float h1=na
float l1=na
h1:= valuewhen(secondCandle, high, 0)
l1:= valuewhen(secondCandle, low, 0)
longEntryPrice = h1 +2
longStopPrice = l1 -10000
longTargetPrice = longEntryPrice + 10000
shortEntryPrice= l1 -2
shortTargetPrice = shortEntryPrice - 10000
shortStopPrice = h1 +10000
longCondition = crossover ( high,longEntryPrice ) and f_tradeDateIsAllowed()
longTargetHit = crossover (high,longTargetPrice ) and f_tradeDateIsAllowed()
longStopHit = crossunder ( low,longStopPrice ) and f_tradeDateIsAllowed()
strategy.entry( "BNFL", long=true, when=longCondition)
if longTargetHit
strategy.close("BNFL", comment="LTH")
if longStopHit
strategy.close("BNFL", comment="LSH")
shortCondition = crossunder ( low,shortEntryPrice ) and f_tradeDateIsAllowed()
shortTargetHit = crossunder (low,shortTargetPrice ) and f_tradeDateIsAllowed()
shortStopHit = crossover ( high,shortStopPrice ) and f_tradeDateIsAllowed()
strategy.entry( "BNFS", long=true, when=shortCondition)
if shortTargetHit
strategy.close("BNFS", comment="STH")
if shortStopHit
strategy.close("BNFS", comment="SSH")
barOpenTime = time
tt=timestamp(year(time), month(time), dayofmonth(time), hour(time), 2)
if ( hour(time) == 15 and minute(time) > 25 )
strategy.close("BNFS", comment="SCM")
if ( hour(time) == 15 and minute(time) > 25 )
strategy.close("BNFL", comment="SCM")
if validSession ==0
strategy.close("BNFL", comment="SC")
strategy.close("BNFS", comment="SC")
|
Optimized Trend Tracker - Strategy Version | https://www.tradingview.com/script/ycDUERPO-Optimized-Trend-Tracker-Strategy-Version/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 512 | 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("Optimized Trend Tracker - Strategy Version", shorttitle="OTT-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)
src = input(close, title="Source")
pds=input(1, "OTT Period", minval=1)
percent=input(0.1, "OTT Percent", type=input.float, step=0.1, minval=0)
condition = input(title="Condition", defval="Support Line Crossing Signals", options=["Price/OTT Crossing Signals", "Support Line Crossing Signals"])
showsupport = input(title="Show Support Line?", type=input.bool, defval=true)
highlight = input(title="Show OTT Color Changes?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
barcoloing = input(title="Barcolor On/Off ?", type=input.bool, defval=true)
showlabels = input(title="Show OTT BUY/SELl Labels?", 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 = 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) // 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"
alpha=2/(pds+1)
ud1=src>src[1] ? src-src[1] : src
dd1=src<src[1] ? src[1]-src : src
UD=sum(ud1,9)
DD=sum(dd1,9)
CMO=(UD-DD)/(UD+DD)
k= abs(CMO)
Var=0.0
Var:=(alpha*k*src)+(1-alpha*k)*nz(Var[1])
fark=Var*percent*0.01
longStop = Var - fark
longStopPrev = nz(longStop[1], longStop)
longStop := Var > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = Var + fark
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := Var < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and Var > shortStopPrev ? 1 : dir == 1 and Var < longStopPrev ? -1 : dir
MT = dir==1 ? longStop: shortStop
OTT=Var>MT ? MT*(200+percent)/200 : MT*(200-percent)/200
plot(showsupport ? Var : na, color=#0585E1, linewidth=2, title="Support Line")
OTTC = highlight ? OTT[2] > OTT[3] ? color.green : color.red : #B800D9
pALL=plot(nz(OTT[2]), color=OTTC, linewidth=2, title="OTT", transp=0)
buySignalk = window() and crossover(Var, OTT[2])
sellSignallk = window() and crossunder(Var, OTT[2])
buySignalc = window() and crossover(src, OTT[2])
sellSignallc = window() and crossunder(src, OTT[2])
plotshape(condition == "Support Line Crossing Signals" ? showlabels and buySignalk ? OTT*0.995 : na : showlabels and buySignalc ? OTT*0.995 : na, title="BUY", text="BUY", location=location.belowbar, style=shape.labelup, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
plotshape(condition == "Support Line Crossing Signals" ? showlabels and sellSignallk ? OTT*1.005 : na : showlabels and sellSignallc ? OTT*1.005 : na, title="SELL", text="SELL", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=#0F18BF, textcolor=color.white, transp=0)
ottBuyColor=#77DD77
ottSellColor=#FF0000
vColor = strategy.position_size > 0 ? ottBuyColor : ottSellColor
if condition == "Support Line Crossing Signals"
strategy.entry("BUY", true, 1, when = buySignalk)
strategy.entry("SELL", false, 1, when = sellSignallk)
else
strategy.entry("BUY", true, 1, when = buySignalc)
strategy.entry("SELL", false, 1, when = sellSignallc)
mPlot = plot(close, title="", style=plot.style_circles, linewidth=0,display=display.none)
longFillColor = highlighting ? (Var>OTT ? color.green : na) : na
shortFillColor = highlighting ? (Var<OTT ? color.red : na) : na
fill(mPlot, pALL, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, pALL, title="DownTrend Highligter", color=shortFillColor)
barcolor(barcoloing ? vColor : na)
|
charl macd ema rsi | https://www.tradingview.com/script/lAhCLSmQ-charl-macd-ema-rsi/ | CharlmFx | https://www.tradingview.com/u/CharlmFx/ | 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/
// © mbuthiacharles4
//Good with trending markets
//@version=4
strategy("CHARL MACD EMA RSI")
fast = 12, slow = 26
fastMA = ema(close, fast)
slowMA = ema(close, slow)
macd = fastMA - slowMA
signal = sma(macd, 9)
ema = ema(close, input(200))
rsi = rsi(close, input(14))
//when delta > 0 and close above ema buy
delta = macd - signal
buy_entry= close>ema and delta > 0
sell_entry = close<ema and delta<0
var bought = false
var sold = false
var reversal = false
if (buy_entry and bought == false and rsi <= 70)
strategy.entry("Buy",true , when=buy_entry)
bought := true
strategy.close("Buy",when= delta<0 or rsi > 70)
if (delta<0 and bought==true)
bought := false
//handle sells
if (sell_entry and sold == false and rsi >= 30)
strategy.entry("Sell",false , when=sell_entry)
sold := true
strategy.close("Sell",when= delta>0 or rsi < 30)
if (delta>0 and sold==true)
sold := false
if (rsi > 70 or rsi < 30)
reversal := true
placing = rsi > 70 ? high :low
label.new(bar_index, placing, style=label.style_flag, color=color.blue, size=size.tiny)
if (reversal == true)
if (rsi < 70 and sold == false and delta < 0)
strategy.entry("Sell",false , when= delta < 0)
sold := true
reversal := false
else if (rsi > 30 and bought == false and delta > 0)
strategy.entry("Buy",true , when= delta > 0)
bought := true
reversal := false
|
Etlers Instantenous Trendline | https://www.tradingview.com/script/TfyKYVfO-Etlers-Instantenous-Trendline/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 225 | 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/
// © greenmask9, @cheatcountry
//@version=4
strategy(title= "Etlers Instantenous Trendline", shorttitle = "Instantenous Trendline", overlay=true)
//commission_type=strategy.commission.percent, commission_value=.5
//
//Capital Management
capitaltype = input(defval="Initial", title="Capital Settings", options=["Initial", "Growing","Manual"], type=input.string)
manualcapital = input(title="Manual Position Size", defval=100.3, type=input.float)
leverage = input(title="Leverage", defval=1, type=input.float)
capitalsystem(capitaltype) =>
v1 = floor(strategy.initial_capital/close) * leverage
v2 = floor((strategy.initial_capital + strategy.netprofit)/close) * leverage
v3 = manualcapital
capitaltype== "Initial"? v1 : capitaltype == "Growing" ? v2 : v3
ordersize=capitalsystem(capitaltype)
//Targets, Stops
percentages = input(title="Percentage stop 🎯", defval=true)
targetpercentage = input(title="Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
stoppercentage = input(title="Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
longtp = strategy.position_avg_price * (1 + targetpercentage)
shorttp = strategy.position_avg_price * (1 - targetpercentage)
longStopPrice = strategy.position_avg_price * (1 - stoppercentage)
shortStopPrice = strategy.position_avg_price * (1 + stoppercentage)
//Cheatcountry's part
// Copyright (c) 2019-present, Franklin Moormann (cheatcountry)
// Ehlers Instantaneous Trendline V2 [CC] script may be freely distributed under the MIT license.
inp = input(title="Source", type=input.source, defval=hl2)
res = input(title="Resolution", type=input.resolution, defval="")
src = security(syminfo.tickerid, res, inp[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
alpha = input(title="Alpha", type=input.float, defval=0.07, minval=0.01, step = 0.01)
itrend = 0.0
itrend := bar_index < 7 ? (src + (2 * nz(src[1])) + nz(src[2])) / 4 : ((alpha - (pow(alpha, 2) / 4)) * src) + (0.5 * pow(alpha, 2) * nz(src[1])) -
((alpha - (0.75 * pow(alpha, 2))) * nz(src[2])) + (2 * (1 - alpha) * nz(itrend[1])) - (pow(1 - alpha, 2) * nz(itrend[2]))
trigger = (2 * itrend) - nz(itrend[2])
sig = trigger > itrend ? 1 : trigger < itrend ? -1 : 0
itColor = sig > 0 ? color.green : sig < 0 ? color.red : color.black
plot(trigger, title="Trigger", color=itColor, linewidth=2)
plot(itrend, title="ITrend", color=color.black, linewidth=1)
//End Cheatcountry's part
//Things
buy = crossover(trigger, itrend)
sell = crossunder(trigger, itrend)
if (buy)
strategy.entry("Buy", strategy.long, ordersize)
if (percentages)
strategy.exit( "Buy", from_entry="Buy", stop=longStopPrice, limit= longtp)
// if (target and stop)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", profit=targetticks, loss=stopnumberticks)
// if (target and not stop)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", profit=targetticks)
// if (stop and not target)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", loss=stopnumberticks)
//strategy.close("Buy", buyend)
if (sell)
strategy.entry("Short", strategy.short, ordersize)
if (percentages)
strategy.exit( "Short", from_entry="Short", stop=shortStopPrice, limit = shorttp)
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
color=color.red, style=plot.style_linebr,
linewidth=2, title="Long Stop Loss")
plot(series=(strategy.position_size < 0) ? shortStopPrice : na,
color=color.red, style=plot.style_linebr,
linewidth=2, title="Short Stop Loss")
plot(series=(strategy.position_size > 0) ? longtp : na,
color=color.lime, style=plot.style_linebr,
linewidth=2, title="Long Stop Loss")
plot(series=(strategy.position_size < 0) ? shorttp : na,
color=color.lime, style=plot.style_linebr,
linewidth=2, title="Short Stop Loss")
|
Double Exponential Moving Average 8-20-63 Strategy | https://www.tradingview.com/script/AbRhwDeX-Double-Exponential-Moving-Average-8-20-63-Strategy/ | Noldo | https://www.tradingview.com/u/Noldo/ | 1,017 | 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
//Quoted by Author HighProfit
//Lead-In
strategy("Double Exponential Moving Average 8-20-63 Strategy",
shorttitle="DEMA-8-20-63",
overlay=true,
max_bars_back = 5000,
initial_capital=100000,
max_bars_back = 5000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100,
commission_type=strategy.commission.percent,
commission_value=0.1,
pyramiding = 0)
short = input(8, minval=1)
srcShort = input(ohlc4, title="Source Dema 1")
long = input(20, minval=1)
srcLong = input(low, title="Source Dema 2")
long2 = input(63, minval=1)
srcLong2 = input(close, title="Source Dema 3")
e1 = ema(srcShort, short)
e2 = ema(e1, short)
dema1 = 2 * e1 - e2
plot(dema1, color=color.green, linewidth=2)
e3 = ema(srcLong, long)
e4 = ema(e3, long)
dema2 = 2 * e3 - e4
plot(dema2, color=color.blue, linewidth=2)
e5 = ema(srcLong2, long2)
e6 = ema(e5, long2)
dema3 = 2 * e5 - e6
plot(dema3, color=color.black, linewidth=2)
longC = dema1 > dema2 and dema1 > dema3
shortC = dema1 < dema2 and dema1 < dema3
alertlong = longC and not longC[1]
alertshort = shortC and not shortC[1]
strategy.entry("Long" , strategy.long , when = longC ,comment="Long")
strategy.entry("Short", strategy.short, when = shortC,comment="Short")
// Alerts
alertcondition(longC , title='Long' , message=' Buy Signal ')
alertcondition(shortC , title='Short', message=' Sell Signal ')
|
Ehlers Bandpass Filter | https://www.tradingview.com/script/rdWkaPU9-Ehlers-Bandpass-Filter/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 123 | 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/
// © greenmask9, @cheatcountry
//@version=4
strategy(title= "Ehlers Bandpass Filter", shorttitle = "Bandpass Filter", overlay=false)
//commission_type=strategy.commission.percent, commission_value=.5
//
//Capital Management
capitaltype = input(defval="Initial", title="Capital Settings", options=["Initial", "Growing","Manual"], type=input.string)
manualcapital = input(title="Manual Position Size", defval=100.3, type=input.float)
leverage = input(title="Leverage", defval=1, type=input.float)
capitalsystem(capitaltype) =>
v1 = floor(strategy.initial_capital/close) * leverage
v2 = floor((strategy.initial_capital + strategy.netprofit)/close) * leverage
v3 = manualcapital
capitaltype== "Initial"? v1 : capitaltype == "Growing" ? v2 : v3
ordersize=capitalsystem(capitaltype)
//Targets, Stops
percentages = input(title="Percentage stop 🎯", defval=true)
targetpercentage = input(title="Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1.3) * 0.01
stoppercentage = input(title="Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.6) * 0.01
longtp = strategy.position_avg_price * (1 + targetpercentage)
shorttp = strategy.position_avg_price * (1 - targetpercentage)
longStopPrice = strategy.position_avg_price * (1 - stoppercentage)
shortStopPrice = strategy.position_avg_price * (1 + stoppercentage)
//Cheatcountry's part
// Copyright (c) 2019-present, Franklin Moormann (cheatcountry)
// Ehlers Bandpass Filter script may be freely distributed under the MIT license.
inp = input(title="Source", type=input.source, defval=close)
res = input(title="Resolution", type=input.resolution, defval="")
rep = input(title="Allow Repainting?", type=input.bool, defval=false)
src = security(syminfo.tickerid, res, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]
length = input(title="Length", type=input.integer, defval=20, minval=1)
bw = input(title="Bandwidth", type=input.float, defval=0.3, minval=0.01, step = 0.01)
pi = 2 * asin(1)
twoPiPrd1 = 0.25 * bw * 2 * pi / length
twoPiPrd2 = 1.5 * bw * 2 * pi / length
beta = cos(2 * pi / length)
gamma = 1.0 / cos(2 * pi * bw / length)
alpha1 = gamma - sqrt((gamma * gamma) - 1)
alpha2 = (cos(twoPiPrd1) + sin(twoPiPrd1) - 1) / cos(twoPiPrd1)
alpha3 = (cos(twoPiPrd2) + sin(twoPiPrd2) - 1) / cos(twoPiPrd2)
hp = 0.0
hp := ((1 + (alpha2 / 2)) * (src - nz(src[1]))) + ((1 - alpha2) * nz(hp[1]))
bp = 0.0
bp := bar_index > 2 ? (0.5 * (1 - alpha1) * (hp - nz(hp[2]))) + (beta * (1 + alpha1) * nz(bp[1])) - (alpha1 * nz(bp[2])) : 0
peak = 0.0
peak := 0.991 * nz(peak[1])
peak := abs(bp) > peak ? abs(bp) : peak
signal = peak != 0 ? bp / peak : 0
trigger = 0.0
trigger := ((1 + (alpha3 / 2)) * (signal - nz(signal[1]))) + ((1 - alpha3) * nz(trigger[1]))
sig = trigger > nz(trigger[1]) ? 1 : trigger < nz(trigger[1]) ? -1 : 0
sigColor = sig > 0 ? color.green : sig < 0 ? color.red : color.black
plot(signal, title="Signal", color=sigColor, linewidth=2)
plot(trigger, title="Trigger", color=color.black, linewidth=1)
//End Cheatcountry's part
//Things
buy = crossover(trigger, signal)
sell = crossunder(trigger, signal)
if (buy)
strategy.entry("Buy", strategy.long, ordersize)
if (percentages)
strategy.exit( "Buy", from_entry="Buy", stop=longStopPrice, limit= longtp)
// if (target and stop)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", profit=targetticks, loss=stopnumberticks)
// if (target and not stop)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", profit=targetticks)
// if (stop and not target)
// strategy.exit( "Set Value tp/sl", from_entry="Buy", loss=stopnumberticks)
//strategy.close("Buy", buyend)
if (sell)
strategy.entry("Short", strategy.short, ordersize)
if (percentages)
strategy.exit( "Short", from_entry="Short", stop=shortStopPrice, limit = shorttp)
//plot(series=(strategy.position_size > 0) ? longStopPrice : na,
// color=color.red, style=plot.style_linebr,
// linewidth=2, title="Long Stop Loss")
//plot(series=(strategy.position_size < 0) ? shortStopPrice : na,
// color=color.red, style=plot.style_linebr,
// linewidth=2, title="Short Stop Loss")
//plot(series=(strategy.position_size > 0) ? longtp : na,
// color=color.lime, style=plot.style_linebr,
// linewidth=2, title="Long Stop Loss")
//plot(series=(strategy.position_size < 0) ? shorttp : na,
// color=color.lime, style=plot.style_linebr,
// linewidth=2, title="Short Stop Loss")
|
CCI-RSI MR | https://www.tradingview.com/script/nJENARTz-CCI-RSI-MR/ | monikabhay | https://www.tradingview.com/u/monikabhay/ | 82 | 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/
// © sg1999
//@version=4
// >>>>>strategy name
strategy(title = "CCI-RSI MR", shorttitle = "CCI-RSI MR", overlay = true)
// >>>>input variables
// 1. risk per trade as % of initial capital
risk_limit = input(title="Risk Limit (%)", type=input.float, minval=0.1, defval=2.0, step=0.1)
// 2. drawdown
Draw_down = input(title="Max Drawdown (x ATR)", type=input.float, minval=0.5, maxval=10, defval=2.0, step=0.1)
// 3. type of stop loss to be used
original_sl_type = input(title="SL Based on", defval="Close Price", options=["Close Price","Last Traded Price"])
// 4. entry signal validity for bollinger strategies
dist_from_signal= input(title="Entry distance from signal", type=input.integer, minval=1, maxval=20, defval=3, step=1)
cross_val = input(title="Cross(over/under) validity", type=input.integer, minval=1, maxval=5, defval=3, step=1) // cross(under/over) of either RSI or CCI is valid for 'n' no.of days
// 5. multiple exit points
exit_1_pft_pct = input(title="1st exit when reward is", type=input.float, minval=0.5, maxval=100, defval=1.0, step=0.1)
exit_1_qty_pct = input(title="1st exit quantity %", type=input.float, minval=1, maxval=100, defval=100, step=5)
exit_2_pft_pct = input(title="2nd exit when reward is", type=input.float, minval=0.5, maxval=100, defval=1.5, step=0.1)
sl_trail_pct = input(title="Trailing SL compared to original SL", type=input.float, minval=0.5, maxval=100, defval=0.5, step=0.5)
//show signal bool
plotBB = input(title="Show BB", type=input.bool, defval=true)
plotSignals = input(title="Show Signals", type=input.bool, defval=true)
// 6. date range to be used for backtesting
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 = 1990, 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 = 2022, title = "Thru Year", type = input.integer, minval = 1970)
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
// >>>>>strategy variables
//input variables
current_high = highest(high, 5) // swing high (5 period)
current_low = lowest(low, 5) // swing low (5 period)
current_ma = sma(close, 5) // Simple Moving average (5 period)
atr_length = atr(20) // ATR (20 period)
CCI = cci(close,20) // CCI (20 period)
RSI = rsi(close,14) // RSI (14 period)
RSI_5 = sma (RSI, 5) // Simple moving average of RSI (5 period)
// 1. for current candle
long_entry = false
short_entry = false
risk_reward_ok = false
sl_hit_flag = false
tsl_hit_flag = false
sl_cross = false
// 2. across candles
var RSI_short = false //short signal boolean
var RSI_long = false //long signal boolean
var cci_sell = false //sellsignal crossunder boolean
var cci_buy = false //buy signal crossover boolean
var bar_count_long = 0 // Number of bars after a long signal
var bar_count_short = 0 // Number of bars after a short signal
var candles_on_trade = 0
var entry_price = 0.00
var sl_price = 0.00
var qty = 0
var exit_1_qty = 0
var exit_2_qty = 0
var exit_1_price = 0.0
var exit_2_price = 0.0
var hold_high = 0.0 // variable used to calculate Trailing sl
var hold_low = 0.0 // variable used to calculate Trailing sl
var tsl_size = 0.0 // Trailing Stop loss size(xR)
var sl_size = 0.0 // Stop loss size (R)
var tsl_price = 0.0 //Trailing stoploss price
// >>>>>strategy conditions.
// Bollinger bands (2 std)
[mBB0,uBB0,lBB0] = bb(close,20,2)
uBB0_low= lowest(uBB0,3) // lowest among upper BB of past 3 periods
lBB0_high= highest(lBB0,3) //highest among upper BB of past 3 periods
//RSI and CCI may not necessarily crossunder on the same candle.
t_sell_RSI = sum( crossunder(RSI,RSI_5)? 1 : 0, cross_val) == 1 // checks if crossunder has happened in the last 3 candles (including the current candle)
t_sell_CCI = sum( crossunder(CCI,100)? 1 : 0, cross_val) == 1
t_buy_RSI = sum( crossover(RSI,RSI_5)? 1 : 0, cross_val) == 1 //checks if crossover has happened in the last 3 candles (including the current candle)
t_buy_CCI = sum( crossover(CCI,-100) ? 1 : 0, cross_val) == 1
// CONDITIONS FOR A SELL signal
if t_sell_RSI and t_sell_CCI and (current_high >= uBB0_low)
cci_sell := true
bar_count_short := 0
if cci_sell and strategy.position_size ==0
bar_count_short := bar_count_short + 1
if cci_sell and bar_count_short<= dist_from_signal and close <= current_ma and strategy.position_size ==0
RSI_short := true
//conditions for a BUY signal
if t_buy_RSI and t_buy_CCI and (current_low <= lBB0_high) // or current_low_close <= lBB01_high)
cci_buy := true
bar_count_long := 0
if cci_buy and strategy.position_size ==0
bar_count_long := bar_count_long + 1
if cci_buy and bar_count_long<= dist_from_signal and close >= current_ma and strategy.position_size ==0
RSI_long := true
if RSI_long and RSI_short
RSI_long := false
RSI_short := false
// >>>>>entry and target specifications
if strategy.position_size == 0 and RSI_short
short_entry := true
entry_price := close
sl_price := current_high + syminfo.mintick // (swing high + one tick) is the stop loss
sl_size := abs(entry_price - sl_price)
candles_on_trade := 0
tsl_size := abs(entry_price - sl_price)*sl_trail_pct // Here sl_trail_pct is the multiple of R which is used to calculate TSL size
if strategy.position_size == 0 and RSI_long
long_entry := true
entry_price := close
sl_price := current_low - syminfo.mintick //(swing low - one tick) is the stop loss
candles_on_trade := 0
sl_size := abs(entry_price - sl_price)
tsl_size := abs(entry_price - sl_price)*sl_trail_pct // Here sl_trail_pct is the multiple of R which is used to calculate TSL size
if long_entry and short_entry
long_entry := false
short_entry := false
// >>>>risk evaluation criteria
//>>>>> quantity determination and exit point specifications.
if (long_entry or short_entry) and strategy.position_size == 0 // Based on our risk (R), no.of lots is calculated by considering a risk per trade limit formula
qty := round((strategy.equity) * (risk_limit/100)/(abs(entry_price - sl_price)*syminfo.pointvalue))
exit_1_qty := round(qty * (exit_1_qty_pct/100))
exit_2_qty := qty - (exit_1_qty)
if long_entry
exit_1_price := entry_price + (sl_size * exit_1_pft_pct)
exit_2_price := entry_price + (sl_size * exit_2_pft_pct)
if short_entry
exit_1_price := entry_price - (sl_size * exit_1_pft_pct)
exit_2_price := entry_price - (sl_size * exit_2_pft_pct)
// trail SL after 1st target is hit
if abs(strategy.position_size) == 0
hold_high := 0
hold_low := 0
if strategy.position_size > 0 and high > exit_1_price
if high > hold_high or hold_high == 0
hold_high := high
tsl_price := hold_high - tsl_size
if strategy.position_size < 0 and low < exit_1_price
if low < hold_low or hold_low == 0
hold_low := low
tsl_price := hold_low + tsl_size
//>>>> entry conditons
if long_entry and strategy.position_size == 0
strategy.cancel("BUY", window()) // add another window condition which considers day time (working hours)
strategy.order("BUY", strategy.long, qty, comment="BUY @ "+ tostring(entry_price),when=window())
if short_entry and strategy.position_size == 0
strategy.cancel("SELL", window()) // add another window condition which considers day time (working hours)
strategy.order("SELL", strategy.short, qty, comment="SELL @ "+ tostring(entry_price),when=window())
//>>>> exit conditons
tsl_hit_flag := false
//exit at tsl
if strategy.position_size > 0 and close < tsl_price and abs(strategy.position_size)!=qty
strategy.order("EXIT at TSL", strategy.short, abs(strategy.position_size), comment="EXIT TSL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
tsl_hit_flag := true
cci_sell := false
cci_buy := false
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at SL",true)
if strategy.position_size < 0 and close > tsl_price and abs(strategy.position_size)!=qty
strategy.order("EXIT at TSL", strategy.long, abs(strategy.position_size), comment="EXIT TSL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
tsl_hit_flag := true
cci_sell := false
cci_buy := false
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at SL",true)
//>>>>exit at sl
if strategy.position_size > 0 and original_sl_type == "Close Price" and close < sl_price and abs(strategy.position_size)==qty
strategy.cancel("EXIT at SL", true)
strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size),stop= sl_price, comment="EXIT SL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
sl_hit_flag := true
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at TSL",true)
if strategy.position_size < 0 and original_sl_type == "Close Price" and close > sl_price and abs(strategy.position_size)==qty
strategy.cancel("EXIT at SL", true)
strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop = sl_price, comment="EXIT SL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
sl_hit_flag := true
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at TSL",true)
//>>>>>for ltp sl setting
if strategy.position_size > 0 and original_sl_type == "Last Traded Price" and abs(strategy.position_size) ==qty
strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size),stop= sl_price, comment="EXIT SL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at TSL",true)
if strategy.position_size < 0 and original_sl_type == "Last Traded Price" and abs(strategy.position_size) ==qty
strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop = sl_price, comment="EXIT SL @ "+ tostring(close))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
strategy.cancel("EXIT 1", true)
strategy.cancel("EXIT 2", true)
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at TSL",true)
//>>>>>exit at target
if strategy.position_size > 0 and abs(strategy.position_size) == qty and not tsl_hit_flag
strategy.order("EXIT 1", strategy.short, exit_1_qty, limit=exit_1_price, comment="EXIT TG1 @ "+ tostring(exit_1_price))
strategy.cancel("Exit Drawd",true)
cci_sell := false
cci_buy := false
if strategy.position_size > 0 and abs(strategy.position_size) < qty and abs(strategy.position_size) != qty and not tsl_hit_flag
strategy.order("EXIT 2", strategy.short, exit_2_qty, limit=exit_2_price, comment="EXIT TG2 @ "+ tostring(exit_2_price))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at SL", true)
if strategy.position_size < 0 and abs(strategy.position_size) == qty and not tsl_hit_flag
strategy.order("EXIT 1", strategy.long, exit_1_qty, limit=exit_1_price, comment="EXIT TG1 @ "+ tostring(exit_1_price))
strategy.cancel("Exit Drawd",true)
cci_buy := false
cci_sell := false
if strategy.position_size < 0 and abs(strategy.position_size) < qty and abs(strategy.position_size) != qty
strategy.order("EXIT 2", strategy.long, exit_2_qty, limit=exit_2_price, comment="EXIT TG2 @ "+ tostring(exit_2_price))
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
strategy.cancel("Exit Drawd",true)
strategy.cancel("EXIT at SL", true)
//>>>>>>drawdown execution
if strategy.position_size < 0 and original_sl_type == "Close Price" and not tsl_hit_flag
strategy.cancel("Exit Drawd",true)
strategy.order("Exit Drawd", strategy.long, abs(strategy.position_size), stop= (entry_price + Draw_down*atr_length) ,comment="Drawdown exit S")
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
if strategy.position_size > 0 and original_sl_type == "Close Price" and not tsl_hit_flag and not sl_hit_flag
strategy.cancel("Exit Drawd",true)
strategy.order("Exit Drawd", strategy.short, abs(strategy.position_size), stop= (entry_price - Draw_down*atr_length) ,comment="Drawdown exit B")
RSI_short := false
RSI_long := false
bar_count_long := 0
bar_count_short := 0
cci_buy := false
cci_sell := false
//>>>>to add sl hit sign
if strategy.position_size != 0 and sl_hit_flag //For symbols on chart
sl_cross := true
//>>>>>cancel all pending orders if the trade is booked
strategy.cancel_all(strategy.position_size == 0 and not (long_entry or short_entry))
//>>>>plot indicators
p_mBB = plot(plotBB ? mBB0 : na, color=color.teal)
p_uBB = plot(plotBB ? uBB0 : na, color=color.teal, style=plot.style_stepline)
p_lBB = plot(plotBB ? lBB0 : na, color=color.teal, style=plot.style_stepline)
plot(sma(close,5), color=color.blue, title="MA")
//>>>>plot signals
plotshape(plotSignals and RSI_short, style=shape.triangledown, location=location.abovebar, color=color.red)
plotshape(plotSignals and RSI_long, style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(sl_cross, text= "Stoploss Hit",size= size.normal,style=shape.xcross , location=location.belowbar, color=color.red)
//>>>>plot signal high low
if strategy.position_size != 0
candles_on_trade := candles_on_trade + 1
if strategy.position_size != 0 and candles_on_trade == 1
line.new(x1=bar_index[1], y1=high[1], x2=bar_index[0], y2=high[1], color=color.black, width=2)
line.new(x1=bar_index[1], y1=low[1], x2=bar_index[0], y2=low[1], color=color.black, width=2)
//>>>>end of program
|
Ichimoku Kinko Hyo Strategy | https://www.tradingview.com/script/E8317mg6-Ichimoku-Kinko-Hyo-Strategy/ | mdeous | https://www.tradingview.com/u/mdeous/ | 134 | 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/
// © mdeous
//@version=4
strategy(
title="Ichimoku Kinko Hyo Strategy",
shorttitle="Ichimoku Strategy",
overlay=true,
pyramiding=0,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100,
initial_capital=1000,
currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.0
)
//
// SETTINGS
//
// Ichimoku
int TENKAN_LEN = input(title="Tenkan-Sen Length", defval=9, minval=1, step=1)
int KIJUN_LEN = input(title="Kijun-Sen Length", defval=26, minval=1, step=1)
int SSB_LEN = input(title="Senkou Span B Length", defval=52, minval=1, step=1)
int OFFSET = input(title="Offset For Chikou Span / Kumo", defval=26, minval=1, step=1)
// Strategy
int COOLDOWN = input(title="Orders Cooldown Period", defval=5, minval=0, step=1)
// bool USE_CHIKOU = input(title="Use Imperfect Chikou Position Detection", defval=false)
bool USE_CHIKOU = false
// Display
bool SHOW_INDICATOR = input(title="Show Ichimoku Kinko Hyo Indicator", defval=true)
//
// HELPERS
//
color _red = color.red
color _blue = color.blue
color _lime = color.lime
color _fuchsia = color.fuchsia
color _silver = color.silver
color _aqua = color.aqua
f_donchian(_len) => avg(lowest(_len), highest(_len))
//
// ICHIMOKU INDICATOR
//
float tenkan = f_donchian(TENKAN_LEN)
float kijun = f_donchian(KIJUN_LEN)
float ssa = avg(tenkan, kijun)
float ssb = f_donchian(SSB_LEN)
plot(SHOW_INDICATOR ? tenkan : na, title="Tenkan", color=_silver)
plot(SHOW_INDICATOR ? close : na, title="Chikou", offset=-OFFSET+1, color=_aqua)
_ssa = plot(SHOW_INDICATOR ? ssa : na, title="SSA", offset=OFFSET-1, color=_lime)
_ssb = plot(SHOW_INDICATOR ? ssb : na, title="SSB", offset=OFFSET-1, color=_red)
fill(_ssa, _ssb, color=ssa > ssb ? _lime : _fuchsia, transp=90)
//
// STRATEGY
//
// Check if price is "above or below" Chikou (i.e. historic price line):
// This detection is highly imperfect, as it can only know what was Chikou's
// position 2*offset candles in the past, therefore if Chikou crossed the price
// line in the last 2*offset periods it won't be detected.
// Use of this detection is disabled by default.
float _chikou_val = close[OFFSET*2+1]
float _last_val = close[OFFSET+1]
bool above_chikou = USE_CHIKOU ? _last_val > _chikou_val : true
bool below_chikou = USE_CHIKOU ? _last_val < _chikou_val : true
// Identify short-term trend with Tenkan
bool _above_tenkan = min(open, close) > tenkan
bool _below_tenkan = max(open, close) < tenkan
// Check price position compared to Kumo
bool _above_kumo = min(open, close) > ssa
bool _below_kumo = max(open, close) < ssb
// Check if Kumo is bullish or bearish
bool bullish_kumo = ssa > ssb
bool bearish_kumo = ssa < ssb
// Correlate indicators to confirm the trend
bool bullish_trend = _above_tenkan and _above_kumo and bullish_kumo
bool bearish_trend = _below_tenkan and _below_kumo and bearish_kumo
// Build signals
bool buy1 = (close > open) and ((close > ssa) and (open < ssa)) // green candle crossing over SSA
bool buy2 = bullish_kumo and bearish_kumo[1] // bullish Kumo twist
bool sell1 = (close < open) and ((close < ssb) and (open > ssb)) // red candle crossing under SSB
bool sell2 = bearish_kumo and bullish_kumo[1] // bearish Kumo twist
bool go_long = below_chikou and (bullish_trend and (buy1 or buy2))
bool exit_long = above_chikou and (bearish_trend and (sell1 or sell2))
//
// COOLDOWN
//
f_cooldown() =>
_cd_needed = false
for i = 1 to COOLDOWN by 1
if go_long[i]
_cd_needed := true
break
_cd_needed
go_long := COOLDOWN == 0 ? go_long : (f_cooldown() ? false : go_long)
//
// ORDERS
//
strategy.entry("buy", strategy.long, when=go_long)
strategy.close_all(when=exit_long)
//
// ALERTS
//
alertcondition(
condition=go_long,
title="Buy Signal",
message="{{exchange}}:{{ticker}}: A buy signal for {{strategy.position_size}} units has been detected (last close: {{close}})."
)
alertcondition(
condition=exit_long,
title="Sell Signal",
message="{{exchange}}:{{ticker}}: A sell signal for {{strategy.position_size}} units has been detected (last close: {{close}})."
)
|
Simple SMA Strategy Backtest | https://www.tradingview.com/script/36kUqFP8-Simple-SMA-Strategy-Backtest/ | HPotter | https://www.tradingview.com/u/HPotter/ | 266 | 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
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)
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)
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(reverse and pos == 1, -1,
iff(reverse and pos == -1, 1, pos))
if (possig == 1)
strategy.entry("Long", strategy.long)
if (possig == -1)
strategy.entry("Short", strategy.short)
if (possig == 0)
strategy.close_all()
nColor = BarColors ? possig == -1 ? color.red : possig == 1 ? color.green : color.blue : na
barcolor(nColor)
plot(nRes, title='SMA', color=#00ffaa, linewidth=2, style=plot.style_line) |
sa-strategy with HTF-TSL | https://www.tradingview.com/script/wy0ls91i-sa-strategy-with-HTF-TSL/ | ringashish | https://www.tradingview.com/u/ringashish/ | 31 | 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/
// © ringashish
//@version=4
strategy("sa-strategy with HTF-TSL", overlay=true)
Pd = input(title="ATR Period", type=input.integer, defval=4)
Factor = input(title="ATR Multiplier", type=input.float, step=0.1, defval=2)
ST= supertrend(Factor, Pd)
heikinashi_close = security(heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_low = security(heikinashi(syminfo.tickerid), timeframe.period, low)
heikinashi_open = security(heikinashi(syminfo.tickerid), timeframe.period, open)
heikinashi_high = security(heikinashi(syminfo.tickerid), timeframe.period, high)
heikinashi_close30 = security(heikinashi(syminfo.tickerid), "30", close)
//res1 = input("30", type=input.resolution, title="higher Timeframe")
//CCI TSL
res = input("240",type=input.resolution,title = "Higher Time Frame")
CCI = input(20)
ATR = input(5)
Multiplier=input(1,title='ATR Multiplier')
original=input(false,title='original coloring')
thisCCI = cci(close, CCI)
lastCCI = nz(thisCCI[1])
calcx()=>
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]
x
tempx = calcx()
calcswap() =>
swap = 0.0
swap := tempx>tempx[1]?1:tempx<tempx[1]?-1:swap[1]
swap
tempswap = calcswap()
swap2=tempswap==1?color.blue:color.orange
swap3=thisCCI >=0 ?color.blue:color.orange
swap4=original?swap3:swap2
//display current timeframe's Trend
plot(tempx,"CTF",color=swap4,transp=0,linewidth=2, style = plot.style_stepline)
htfx = security(syminfo.tickerid,res,tempx[1],lookahead = barmerge.lookahead_on)
htfswap4 = security(syminfo.tickerid,res,swap4[1],lookahead = barmerge.lookahead_on)
plot(htfx,"HTF",color=htfswap4,transp=0,linewidth=3,style = plot.style_stepline)
//supertrend
Supertrend(Factor, Pd) =>
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp = 0.0
TrendUp := heikinashi_close[1]>TrendUp[1] ? max(Up,TrendUp[1]) : Up
TrendDown = 0.0
TrendDown := heikinashi_close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = 0.0
Trend := heikinashi_close > TrendDown[1] ? 1: heikinashi_close< 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] = Supertrend(Factor, Pd)
// Security
//ST1_Trend_MTF = security(syminfo.tickerid, res1, Tsl,barmerge.lookahead_on)
//plot(ST1_Trend_MTF, "higher ST")
crossdn = crossunder(heikinashi_close,Tsl) or crossunder(heikinashi_close[1],Tsl) or crossunder(heikinashi_close[2],Tsl) or heikinashi_close < Tsl
crossup = crossover(heikinashi_close,Tsl) or crossover(heikinashi_close[1],Tsl) or crossover(heikinashi_close[2],Tsl) or heikinashi_close > Tsl
plot(Tsl,"ST",color = color.black,linewidth =2)
plot(ema(heikinashi_close,20),"EMA 20",color=color.red)
plot(hma(heikinashi_close,15),"HMA 15",color=color.green)
plot(ema(heikinashi_close,15),"EMA 15",color=color.black)
closedown = (heikinashi_close < hma(heikinashi_close,15) and heikinashi_high > hma(heikinashi_close,15)) or(heikinashi_close < ema(heikinashi_close,20) and heikinashi_high > ema(heikinashi_close,20))
closeup = (heikinashi_close > hma(heikinashi_close,15) and heikinashi_low < hma(heikinashi_close,15)) or (heikinashi_close > ema(heikinashi_close,20) and heikinashi_low < ema(heikinashi_close,20))
buy = heikinashi_open == heikinashi_low and closeup and crossup and close > htfx
//buy = heikinashi_open == heikinashi_low and heikinashi_close > ema(close,20) and heikinashi_low < ema(close,20) and crossup
buyexit = cross(close,tempx) //heikinashi_open == heikinashi_high //and heikinashi_close < ema(close,15) and heikinashi_high > ema(close,15)
//if heikinashi_close30[1] < ST1_Trend_MTF
//sell = heikinashi_open == heikinashi_high and heikinashi_close < ema(close,20) and heikinashi_high > ema(close,20) and rsi(close,14)<60 and crossdn
sell = heikinashi_open == heikinashi_high and closedown and rsi(close,14)<55 and crossdn and close < htfx
sellexit = cross(close,tempx) //heikinashi_open == heikinashi_low //and heikinashi_close > ema(close,15) and heikinashi_low < ema(close,15)
rg = 0
rg := buy ? 1 : buyexit ? 2 : nz(rg[1])
longLogic = rg != rg[1] and rg == 1
longExit = rg != rg[1] and rg == 2
//plotshape(longExit,"exit buy",style = shape.arrowup,location = location.belowbar,color = color.red, text ="buy exit", textcolor = color.red)
//plotshape(longLogic,"BUY",style = shape.arrowup,location = location.belowbar,color = color.green, text ="buy", textcolor= color.green)
nm = 0
nm := sell ? 1 : sellexit ? 2 : nz(nm[1])
shortLogic = nm != nm[1] and nm == 1
shortExit = nm != nm[1] and nm == 2
//plotshape(shortExit,"exit sell",style = shape.arrowup,location = location.belowbar,color = color.red, text ="sell exit", textcolor = color.red)
//plotshape(shortLogic,"SELL",style = shape.arrowup,location = location.belowbar,color = color.green, text ="sell", textcolor= color.green)
//Exit at particular time
ExitHour = input(title="Exit Hour Of Day", type=input.integer, defval=15, step = 5, maxval = 24, minval = 0)
ExitMint = input(title="Exit Minute Of Day", type=input.integer, defval=15, step = 5, maxval = 24, minval = 0)
bgc = input(title="Highlight Background Color?", type=input.bool, defval=true)
mRound(num,rem) => (floor(num/rem)*rem)
exitTime = (hour(time) >= ExitHour and (minute == mRound(ExitMint, timeframe.multiplier))) ? 1 : 0
exitTime := exitTime == 0 ? (hour(time) >= ExitHour and (minute + timeframe.multiplier >= ExitMint)) ? 1 : 0 : exitTime
MarketClose = exitTime and not exitTime[1]
alertcondition(exitTime and not exitTime[1], title="Intraday Session Close Time", message="Close All Positions")
bgcolor(exitTime and not exitTime[1] and bgc ? #445566 : na, transp =40)
longCondition = longLogic
if (longCondition)
strategy.entry("long", strategy.long)
shortCondition = shortLogic
if (shortCondition)
strategy.entry("short", strategy.short)
strategy.close("short", when =cross(close,tempx) or MarketClose)
strategy.close( "long", when =cross(close,tempx) or MarketClose ) |
EMA Crossover Strategy | https://www.tradingview.com/script/tnFHknMz-EMA-Crossover-Strategy/ | BrendanW98 | https://www.tradingview.com/u/BrendanW98/ | 608 | 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/
// © BrendanW98
//@version=4
strategy("My Strategy", overlay=true)
ema5 = ema(close, 9)
ema20 = ema(close, 21)
ema50 = ema(close, 55)
//RSI Signals
// Get user input
rsiSource = close
rsiLength = 14
rsiOverbought = 70
rsiOversold = 30
rsiMid = 50
// Get RSI value
rsiValue = rsi(rsiSource, rsiLength)
//See if RSI crosses 50
doBuy = crossover(rsiValue, rsiOversold) and rsiValue < 50
doSell = crossunder(rsiValue, rsiOverbought) and rsiValue > 50
emacrossover = crossover(ema5, ema20) and ema5 > ema50 and ema20 > ema50 and close > ema50
emacrossunder = crossunder(ema5, ema20) and ema5 < ema50 and ema20 < ema50 and close < ema50
//Entry and Exit
longCondition = emacrossover
closelongCondition = doSell
strategy.entry("Long", strategy.long, 10000.0, when=longCondition)
strategy.close("Long", when=closelongCondition)
shortCondition = emacrossunder
closeshortCondition = doBuy
strategy.entry("Short", strategy.short, 10000.0, when=shortCondition)
strategy.close("Short", when=closeshortCondition) |
longWickStrategy | https://www.tradingview.com/script/9lqUQ4Z3-longWickStrategy/ | ondrej17 | https://www.tradingview.com/u/ondrej17/ | 109 | 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/
// © ondrej17
//@version=4
strategy("longWickstrategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=0.1)
// Inputs
st_yr_inp = input(defval=2020, title='Backtest Start Year')
st_mn_inp = input(defval=01, title='Backtest Start Month')
st_dy_inp = input(defval=01, title='Backtest Start Day')
en_yr_inp = input(defval=2025, title='Backtest End Year')
en_mn_inp = input(defval=01, title='Backtest End Month')
en_dy_inp = input(defval=01, title='Backtest End Day')
sltp_inp = input(defval=0.8, title='N - % offset for N*SL and (2N)*TP')/100
// Dates
start = timestamp(st_yr_inp, st_mn_inp, st_dy_inp,00,00)
end = timestamp(en_yr_inp, en_mn_inp, en_dy_inp,00,00)
canTrade = time >= start and time <= end
// Indicators Setup
// Strategy Calcuations
lowerWick = (open > close) ? close-low : open - low
upperWick = (open > close) ? high-open : high-close
wickLength = max(lowerWick,upperWick)
candleLength = high-low
wickToCandleRatio = wickLength / candleLength
entryFilterCandleLength = candleLength > 0.75*atr(48)
// Entries and Exits
longCondition = entryFilterCandleLength and wickToCandleRatio > 0.5 and lowerWick > upperWick and canTrade and strategy.position_size == 0
shortCondition = entryFilterCandleLength and wickToCandleRatio > 0.5 and lowerWick < upperWick and canTrade and strategy.position_size == 0
strategy.entry("pendingLong", strategy.long, limit=low+wickLength/2, when = longCondition)
strategy.entry("pendingShort", strategy.short, limit=high-wickLength/2, when = shortCondition)
longStop = strategy.position_size > 0 ? strategy.position_avg_price*(1-sltp_inp) : na
longTP = strategy.position_size > 0 ? strategy.position_avg_price*(1+2*sltp_inp) : na
shortStop = strategy.position_size < 0 ? strategy.position_avg_price*(1+sltp_inp) : na
shortTP = strategy.position_size < 0 ? strategy.position_avg_price*(1-2*sltp_inp) : na
strategy.exit("longSLTP","pendingLong", stop=longStop, limit = longTP)
strategy.exit("shortSLTP","pendingShort", stop=shortStop, limit = shortTP)
plot(longStop, color=color.red, style=plot.style_linebr, linewidth=2)
plot(shortStop, color=color.red, style=plot.style_linebr, linewidth=2)
plot(longTP, color=color.green, style=plot.style_linebr, linewidth=2)
plot(shortTP, color=color.green, style=plot.style_linebr, linewidth=2)
plotLongCondition = longCondition ? high+abs(open-close) : na
plot(plotLongCondition, style=plot.style_circles, linewidth=4, color=color.green)
plotShortCondition = shortCondition ? high+abs(open-close) : na
plot(plotShortCondition, style=plot.style_circles, linewidth=4, color=color.red)
|
Trend Reversal / Potential pressure | https://www.tradingview.com/script/w58JPHxf-Trend-Reversal-Potential-pressure/ | BardiaB2 | https://www.tradingview.com/u/BardiaB2/ | 91 | 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/
// © BardiaB2
//@version=4
strategy("TR", calc_on_every_tick=true)
ATR=atr(7) * 1
trendMA = ema(close, 500)
is_trend_up = close>trendMA
is_red(i) => (close[i] < open[i]) ? 1 : 0
is_green(i) => is_red(i) ? 0 : 1
is_hammer(i) => is_red(i) ? ((high[i]-close[i]) < (high[i]-low[i])/3 ) : ((high[i]-open[i]) < (high[i]-low[i])/3 )
is_stick(i) => is_red(i) ? ((open[i]-low[i]) < (high[i]-low[i])/3 ) : ((close[i]-low[i]) < (high[i]-low[i])/3 )
if is_hammer(1) and is_red(2) and is_green(0) and close>close[1] and open[1]>open and low>low[1] and is_trend_up
strategy.entry("LE", strategy.long, 10000)
strategy.exit("TP/SL LE", "LE", stop = low[1]-ATR, limit=close+(high[1]-low[1])+ATR)
if is_stick(1) and is_green(2) and is_red(0) and close<close[1] and open[1]<open and high<high[1] and (not is_trend_up)
strategy.entry("SE", strategy.short, 10000)
strategy.exit("TP/SL SE", "SE", stop = high[1]+ATR, limit=close-(high[1]-low[1])-ATR)
|
Nifty Volume profile + VWAP + EMA | https://www.tradingview.com/script/MIi3WUU2-Nifty-Volume-profile-VWAP-EMA/ | aashish2137 | https://www.tradingview.com/u/aashish2137/ | 712 | 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/
// © aashish2137
//@version=4
strategy("NF VWAP and EMA",overlay=true)
// custom function
sym(s) => security(s,timeframe.period, volume)
// make the weighted index
A = (10.34*sym("NSE:HDFCBANK")/100+11.88*sym("NSE:RELIANCE")/100+7.2*sym("NSE:HDFC")/100+5.39*sym("NSE:ICICIBANK")/100+6.35*sym("NSE:INFY")/100+5.2*sym("NSE:TCS")/100+4.11*sym("NSE:KOTAKBANK")/100+4.32*sym("NSE:ITC")/100+2.18*sym("NSE:AXISBANK")/100+2.89*sym("NSE:LT")/100+3.69*sym("NSE:HINDUNILVR")/100+1.55*sym("NSE:SBIN")/100+1.3*sym("NSE:BAJFINANCE")/100+1.87*sym("NSE:MARUTI")/100+1.82*sym("NSE:INDUSINDBK")/100+3.1*sym("NSE:BHARTIARTL")/100+1.9*sym("NSE:ASIANPAINT")/100+1.5*sym("NSE:HCLTECH")/100+1.13*sym("NSE:BAJAJFINSV")/100+1.19*sym("NSE:NTPC")/100+1.57*sym("NSE:NESTLEIND")/100+0.93*sym("NSE:TITAN")/100+1.05*sym("NSE:M_M")/100+0.82*sym("NSE:TECHM")/100+1.28*sym("NSE:SUNPHARMA")/100+1.13*sym("NSE:ULTRACEMCO")/100+1.01*sym("NSE:POWERGRID")/100+0.76*sym("NSE:ONGC")/100+0.89*sym("NSE:BAJAJ_AUTO")/100+0.74*sym("NSE:COALINDIA")/100+0.69*sym("NSE:BPCL")/100+0.79*sym("NSE:WIPRO")/100+1*sym("NSE:BRITANNIA")/100+0.71*sym("NSE:TATASTEEL")/100+1.24*sym("NSE:DRREDDY")/100+0.66*sym("NSE:TATAMOTORS")/100+0.64*sym("NSE:IOC")/100+0.64*sym("NSE:UPL")/100+0.63*sym("NSE:EICHERMOT")/100+0.77*sym("NSE:HEROMOTOCO")/100)
colorofbar = open < close ? color.green : color.red
volumePeriod = input(14, "Period")
fastEmaPeriod = input(8, "Period")
slowEmaPeriod = input(5, "Period")
priceValue = (high + low + close) / 3
priceVolume = priceValue * A
cumulativePriceVolume = sum(priceVolume, volumePeriod)
cumulativeVolume = sum(A, volumePeriod)
vwapValue = cumulativePriceVolume / cumulativeVolume
fastEma = ema(close, fastEmaPeriod)
slowEma = ema(close, slowEmaPeriod)
plot(series=vwapValue, title="VWAP BNF", style=plot.style_line, color= color.black)
plot(series=fastEma, title="Fast EMA", style=plot.style_line, color= color.green)
plot(series=slowEma, title="Slow EMA", style=plot.style_line, color= color.red)
longCond = crossover(fastEma, slowEma)
shortCond = crossunder(fastEma, slowEma)
plotshape(series=longCond, title="Long", style=shape.cross, location=location.bottom, color=color.green, text="LONG", size=size.small)
plotshape(series=shortCond, title="Short", style=shape.cross, location=location.bottom, color=color.red, text="SHORT", size=size.small) |
RSI W Pattern strategy | https://www.tradingview.com/script/f80Cfpfp-RSI-W-Pattern-strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 663 | 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 W Pattern strategy", pyramiding=2, shorttitle="RSI W Pattern", overlay = false)
//Strategy Rules
//ema20 is above ema50
//RSI5 making W pattern in oversold area or just below 70 level , you can define the value for parameter buyRsiEntry --- dont go beyond 70
//Exit when RSI reaches 75
len = input(title="RSI Period", minval=1, defval=5)
buyRsiEntry = input(title="look for W pattern bottom edges well below RSI level (BUY) ", minval=10, defval=65, maxval=70)
//numberOfBars = input(title="Number of Bars in W pattern ", minval=4, defval=4, maxval=6)
emaL = input(title="Long Term EMA", minval=1, defval=50, maxval=200)
emaS = input(title="Short Term EMA", minval=1, defval=20, maxval=200)
stopLoss = input(title="Stop Loss %", minval=1, defval=8, maxval=10)
//rsiWp1=false
myRsi = rsi(close,len)
//longEmaVal=ema(close,emaL)
//shortEmaVal=ema(close,emaS)
entryEma=ema(close,5) // This is used as filetr for BUY
isEma20AboveEma50=ema(close,emaS)>ema(close,emaL) ? true : false
//W Pattern
//rsiWp1 = myRsi>myRsi[1] and myRsi>=30 and myRsi[1]<myRsi[2] and myRsi[2]>myRsi[3] and myRsi[3]<myRsi[4] //This is published one
rsiWp1 = myRsi>myRsi[1] and myRsi>=30 and myRsi[1]<myRsi[2] and myRsi[2]>myRsi[3] and myRsi[3]<myRsi[4] and (low[1]<=low[4] or low[3]<=low[4] ) // looking for recent low
//rsiWp1 = myRsi>myRsi[1] and myRsi>=30 and myRsi[1]<myRsi[2] and myRsi[2]>myRsi[3] and myRsi[3]<myRsi[4] //Ths one has 92% win rate and 4.593 prfit factor
//long condition filters
//1. ema20 > ema50
//2. Rsi5 has W pattern
//3. current RSI <= 65 (parameter buyRsiEntry) (dont go beyond 70 , becuase that is already overbought area)
//4. current price low/close is below 5 ema --- looking for pullback -- Optional
longCondition = isEma20AboveEma50 and rsiWp1 and (myRsi<=buyRsiEntry and myRsi>=30)
//and (low<entryEma or close<entryEma) --- if this optional required , add it to above condition
patternText=" W "
barcolor(longCondition?color.yellow:na)
//initial entry
strategy.entry("RSI_W_LE", comment="Buy" , long=true, when=longCondition )
//legging in to existing
strategy.entry("RSI_W_LE",comment="Add", long=true, when=strategy.position_size>0 and crossover(myRsi,10 ))
//calculate stoploss value
stopLossValue=strategy.position_avg_price - (strategy.position_avg_price*stopLoss/100)
rsiPlotColor=longCondition ?color.yellow:color.purple
plot(myRsi, title="RSI", linewidth=2, color=color.purple)
// plot(myRsi, title="RSI", linewidth=2, color=rsiWp1?color.yellow:color.purple)
//plot(myRsi[1], title="RSI", linewidth=2, color=rsiWp1==true?color.yellow:color.purple)
//plot(myRsi[2], title="RSI", linewidth=2, color=rsiWp1?color.yellow:color.purple)
//plot(myRsi[3], title="RSI", linewidth=2, color=rsiWp1?color.yellow:color.purple)
//plot(myRsi[4], title="RSI", linewidth=2, color=rsiWp1?color.yellow:color.purple)
hline(40, title="Middle Line", color=color.blue, linestyle=hline.style_dashed)
obLevel = hline(75, title="Overbought", color=color.red, linestyle=hline.style_dashed)
osLevel = hline(30, title="Oversold", color=color.purple, linestyle=hline.style_dashed)
fill(obLevel, osLevel, title="Background", color=#9915FF, transp=90)
plotshape(
longCondition ? myRsi[1] : na,
offset=-1,
title="W Pattern",
text=patternText,
style=shape.labelup,
location=location.absolute,
color=color.purple,
textcolor=color.yellow,
transp=0
)
bgcolor(strategy.position_size>0?color.green:na, transp=40, title='In Long Position')
//take profit or close when RSI reaches 75
takeProfit=crossover(myRsi,75)
//close when RSi reaches profit level
strategy.close("RSI_W_LE", comment="TP Exit", qty=strategy.position_size,when=crossover(myRsi,75) and close>strategy.position_avg_price )
//close everything when stoploss hit
longCloseCondition=close<(strategy.position_avg_price - (strategy.position_avg_price*stopLoss/100) ) //or crossunder(myRsi,30)
strategy.close("RSI_W_LE", comment="SL Exit", qty=strategy.position_size,when=longCloseCondition )
|
[Strategy] - EMA 10,20 59 with Profit Displayed | https://www.tradingview.com/script/pBTV21RO-Strategy-EMA-10-20-59-with-Profit-Displayed/ | mattehalen | https://www.tradingview.com/u/mattehalen/ | 108 | 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/
// © mattehalen
//@version=4
//study("EMA 10,20 59",overlay=true)
strategy("EMA 10,20 59",overlay=true, process_orders_on_close = true, default_qty_type = strategy.fixed, default_qty_value = 1000, initial_capital=250, currency=currency.USD)
infoBox = input(true, title="infoBox", type=input.bool)
infoBox2 = input(false, title="infoBox2", type=input.bool)
BuySellSignal_Bool = input(false, title="Buy & SellSignal", type=input.bool)
infoBoxSize = input(title="infoBoxSize", defval=size.large, options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge])
ema1Value = input(10)
ema2Value = input(20)
ema3Value = input(59)
maxLoss = input(3000)
ema1 = ema(close,ema1Value)
ema2 = ema(close,ema2Value)
ema3 = ema(close,ema3Value)
objcnt = 0
buyTitle = tostring(close[1])
myProfit = float(0)
plot(ema1,title="ema1",color=color.red,linewidth=2)
plot(ema2,title="ema2",color=color.green,linewidth=2)
plot(ema3,title="ema3",color=color.black,linewidth=2)
Buytrend = (ema1 and ema2 > ema3) and (ema1[1] and ema2[1] > ema3[1])
BarssinceBuyTrend = barssince(Buytrend)
BarssinceSellTrend = barssince(not Buytrend)
closeAtBuyTrend = close[1]
bgcolor(Buytrend ? color.green : color.red,transp=70)
BuySignal = Buytrend and not Buytrend[1] and BuySellSignal_Bool
BuySignalOut = Buytrend and (crossunder(ema1,ema2)) and BuySellSignal_Bool
BarssinceBuy = barssince(BuySignal)
bgcolor(BuySignal ? color.green : na , transp=30)
bgcolor(BuySignalOut ? color.black : na , transp=30)
plot(BarssinceBuy,title="BarssinceBuy",display=display.none)
SellSignal = not Buytrend and Buytrend[1] and BuySellSignal_Bool
SellSignalOut = not Buytrend and (crossover(ema1,ema2)) and BuySellSignal_Bool
BarssinceSell = barssince(SellSignal)
bgcolor(SellSignal ? color.red : na , transp=30)
bgcolor(SellSignalOut ? color.black : na , transp=30)
plot(BarssinceSell,title="BarssinceSell",display=display.none)
buyProfit = float(0)
cntBuy =0
sellProfit = float(0)
cntSell =0
buyProfit := Buytrend and not Buytrend[1]? nz(buyProfit[1]) + (close[BarssinceBuyTrend[1]]-close) : nz(buyProfit[1])
cntBuy := Buytrend and not Buytrend[1]? nz(cntBuy[1]) + 1: nz(cntBuy[1])
sellProfit := not Buytrend and Buytrend[1]? nz(sellProfit[1]) + (close-close[BarssinceSellTrend[1]]) : nz(sellProfit[1])
cntSell := not Buytrend and Buytrend[1]? nz(cntSell[1]) + 1 : nz(cntSell[1])
totalProfit = buyProfit + sellProfit
if (Buytrend and not Buytrend[1] and infoBox==true)
l = label.new(bar_index - (BarssinceBuyTrend[1]/2), na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceBuyTrend[1]]) + "\n" + "Profit = "+tostring(close[BarssinceBuyTrend[1]]-close) ,style=label.style_labelup, yloc=yloc.belowbar,color=color.red,size=infoBoxSize)
if (not Buytrend and Buytrend[1] and infoBox==true)
l = label.new(bar_index - (BarssinceSellTrend[1]/2), na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceSellTrend[1]]) + "\n" + "Profit = "+tostring(close-close[BarssinceSellTrend[1]]) ,style=label.style_labeldown, yloc=yloc.abovebar,color=color.green,size=infoBoxSize)
if (BuySignalOut and not BuySignalOut[1] and infoBox2==true)
// l = label.new(bar_index - (BarssinceBuy[0]/2), na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceBuy[0]]) + "\n" + "Profit = "+tostring(close-close[BarssinceBuy[0]]) ,style=label.style_labelup, yloc=yloc.belowbar,color=color.purple,size=infoBoxSize
l = label.new(bar_index, na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceBuy[0]]) + "\n" + "Profit = "+tostring(close-close[BarssinceBuy[0]]) ,style=label.style_labelup, yloc=yloc.belowbar,color=color.lime,size=infoBoxSize)
if (SellSignalOut and not SellSignalOut[1] and infoBox2==true)
// l = label.new(bar_index - (BarssinceSell[0]/2), na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceSell[0]]) + "\n" + "Profit = "+tostring(close[BarssinceSell[0]]-close) ,style=label.style_labeldown, yloc=yloc.abovebar,color=color.purple,size=infoBoxSize)
l = label.new(bar_index, na,text="Close = " + tostring(close) + "\n" + "Start = "+tostring(close[BarssinceSell[0]]) + "\n" + "Profit = "+tostring(close[BarssinceSell[0]]-close) ,style=label.style_labeldown, yloc=yloc.abovebar,color=color.fuchsia,size=infoBoxSize)
l2 = label.new(bar_index, na, 'buyProfit in pip = '+tostring(buyProfit)+"\n"+ 'cntBuy = '+tostring(cntBuy) +"\n"+ 'sellProfit in pip = '+tostring(sellProfit)+"\n"+ 'cntSell = '+tostring(cntSell) +"\n"+ 'totalProfit in pip = '+tostring(totalProfit) ,
color=totalProfit>0 ? color.green : color.red,
textcolor=color.white,
style=label.style_labeldown, yloc=yloc.abovebar,
size=size.large)
label.delete(l2[1])
//--------------------------------------------------
//--------------------------------------------------
if (Buytrend)
strategy.close("short", comment = "Exit short")
strategy.entry("long", true)
strategy.exit("Max Loss", "long", loss = maxLoss)
//if BuySignalOut
// strategy.close("long", comment = "Exit Long")
if (not Buytrend)
// Enter trade and issue exit order on max loss.
strategy.close("long", comment = "Exit Long")
strategy.entry("short", false)
strategy.exit("Max Loss", "short", loss = maxLoss)
//if SellSignalOut
// Force trade exit.
//strategy.close("short", comment = "Exit short")
//--------------------------------------------------
//--------------------------------------------------
//--------------------------------------------------
|
CoGrid Management | https://www.tradingview.com/script/3kMUl7fJ/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 887 | 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 = "CoGrid Management", shorttitle = "CoGrid💹", overlay = true, pyramiding = 1000, default_qty_value = 0)
// ———————————————————— Inputs
WOption = input('PRICE', " 》 WIDTH TYPE", options = ['PRICE','% PP'])
Width = input(500, " 》 WIDTH", type = input.float, minval = 0)
ppPeriod = input('Month', " 》 PP PERIOD", options = ['Day','Week','15D','Month'])
BuyType = input("CASH", " 》 BUY TYPE", options = ["CONTRACTS","CASH","% EQUITY"])
BuyQ = input(10000, " 》 QUANTITY TO BUY", type = input.float, minval = 0)
SellType = input('CONTRACTS', " 》 SELL TYPE", options = ["CONTRACTS","CASH","% EQUITY"])
SellQ = input(2, " 》 QUANTITY TO SELL", type = input.float, minval = 0)
// ———————————————————— Vars
// ————— Final Buy Price & Final Sell Price
var float FinalBuyPrice = na
var float FinalSellPrice = na
var float FinalOpenPrice = na
// ————— Average Price
var int nBuys = na
nBuys := nz(nBuys[1])
var int nSells = na
nSells := nz(nSells[1])
var float sumBuy = na
sumBuy := nz(sumBuy[1])
var float sumSell = na
sumSell := nz(sumSell[1])
var float sumQtyBuy = na
sumQtyBuy := nz(sumQtyBuy[1])
var float sumQtySell = na
sumQtySell := nz(sumQtySell[1])
var float AveragePrice = na
color Color = na
// ————— Fibonacci Pivots Level Calculation
var float PP = na
// ————— Backtest
BuyFactor = BuyType == "CONTRACTS" ? 1 : BuyType == "% EQUITY" ? (100 / (strategy.equity / close)) : close
SellFactor = SellType == "CASH" ? close : 1
BuyQuanTity = BuyQ / BuyFactor
SellQuanTity = SellQ / SellFactor
// ————— Width between levels
float GridWidth = WOption == 'PRICE' ? Width : PP * (Width/100)
// ————— Origin from Rounded Pivot Points or last Sell
var float PPdownOrigin = na
PPdownOrigin := floor(PP / GridWidth) * GridWidth
PPdownOrigin := (fixnan(FinalSellPrice[1]) <= PP ? (floor(fixnan(FinalSellPrice[1]) / GridWidth) * GridWidth) - GridWidth : floor(PP / GridWidth) * GridWidth)
// ————— Origin from Rounded Position Price
var float PPupOrigin = na
PPupOrigin := nz(PPupOrigin[1])
PPupOrigin := (ceil(fixnan(AveragePrice[1]) / GridWidth) * GridWidth) + GridWidth
// ———————————————————— Pivot Points
// ————— Pivot Points Period
res = ppPeriod == '15D' ? '15D' : ppPeriod == 'Week' ? 'W' : ppPeriod == 'Day' ? 'D' : 'M'
// ————— High, Low, Close Calc.
// "Function to securely and simply call `security()` so that it never repaints and never looks ahead" (@PineCoders)
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
phigh = f_secureSecurity(syminfo.tickerid, res, high)
plow = f_secureSecurity(syminfo.tickerid, res, low)
pclose = f_secureSecurity(syminfo.tickerid, res, close)
// ————— Fibonacci Pivots Level Calculation
PP := (phigh + plow + pclose) / 3
// ———————————————————— Grid Strategy
// ————— Grid Calculation
fGrid(_1, _2, _n) =>
_a = _1, _b = _2, _c = 0.0
for _i = 1 to _n
if _i == 1
_c := _a
else
_c := _a + _b
_a := _c
// ————— Buy at better Price
fBuyCondition(_n) =>
var float _ldown = na
_ldown := nz(_ldown[1])
var bool _pb = na
_pb := nz(_pb[1])
var bool _BuyCondition = na
_BuyCondition := nz(_BuyCondition[1])
for _i = 1 to _n
_ldown := fGrid(PPdownOrigin, -GridWidth, _i)
_pb := crossunder(low, _ldown) and high >= _ldown
_BuyCondition := na(FinalOpenPrice) ? _pb : _pb and _ldown < (FinalOpenPrice[1] - GridWidth / 4)
_BuyCondition
// ————— Sell at better Price
fSellCondition(_n) =>
var float _lup = na
_lup := nz(_lup[1])
var bool _ps = na
_ps := nz(_ps[1])
var bool _SellCondition = na
_SellCondition := nz(_SellCondition[1])
for _i = 1 to _n
_lup := fGrid(PPupOrigin, GridWidth, _i)
_ps := crossover(high, _lup) and low <= _lup
_SellCondition := na(FinalOpenPrice) ? _ps : _ps and _lup > (FinalOpenPrice[1] + GridWidth / 4)
_SellCondition
// ————— Final Trade Price, Average Price & Backtest
for _i = 1 to 15
// Buys
if fBuyCondition(_i)
FinalBuyPrice := fGrid(PPdownOrigin, -GridWidth, _i)
FinalSellPrice := na
FinalOpenPrice := fGrid(PPdownOrigin, -GridWidth, _i)
nBuys := nBuys + 1
nSells := na
sumBuy := FinalOpenPrice * BuyQuanTity + nz(sumBuy[1])
sumQtyBuy := BuyQuanTity + nz(sumQtyBuy[1])
AveragePrice := sumBuy / sumQtyBuy
Color := color.lime
// Numbering
label.new(x = time,
y = FinalOpenPrice,
text = ' ' + tostring(nBuys),
textcolor = color.lime,
style = label.style_none,
xloc = xloc.bar_time,
yloc = yloc.price,
size = size.small)
// Backtest Buys
strategy.entry("BUY", strategy.long, qty = BuyQuanTity)
else
// Sells
if fSellCondition(_i)
FinalBuyPrice := na
FinalSellPrice := fGrid(PPupOrigin, GridWidth, _i)
FinalOpenPrice := fGrid(PPupOrigin, GridWidth, _i)
nBuys := na
nSells := nSells + 1
sumBuy := na
sumQtyBuy := na
Color := color.orange
// Numbering
label.new(x = time,
y = FinalOpenPrice,
text = ' ' + tostring(nSells),
textcolor = color.orange,
style = label.style_none,
xloc = xloc.bar_time,
yloc = yloc.price,
size = size.small)
// Backtest Sells
strategy.close("BUY", qty = SellType != "% EQUITY" ? SellQuanTity : na, qty_percent = (SellType == "% EQUITY" ? SellQuanTity : na), comment = "SELL")
// ———————————————————— Plotting
// ————— Plotting Pivot Points
plot(PP, title = "PP", style = plot.style_circles, color = color.aqua, linewidth = 2)
// ————— Plotting the average price
plot(nBuys > 1 ? AveragePrice[1] : na, title = "Average Price", style = plot.style_circles, color = color.fuchsia, linewidth = 2)
// ————— Buy Shapes
fPlotBuySell(_n) =>
if fBuyCondition(_n)
fGrid(PPdownOrigin, -GridWidth, _n)
else
if fSellCondition(_n)
fGrid(PPupOrigin, GridWidth, _n)
plotshape(fPlotBuySell(1), title = "Buy/Sell 1", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(2), title = "Buy/Sell 2", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(3), title = "Buy/Sell 3", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(4), title = "Buy/Sell 4", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(5), title = "Buy/Sell 5", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(6), title = "Buy/Sell 6", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(7), title = "Buy/Sell 7", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(8), title = "Buy/Sell 8", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(9), title = "Buy/Sell 9", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(10), title = "Buy/Sell 10", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(11), title = "Buy/Sell 11", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(12), title = "Buy/Sell 12", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(13), title = "Buy/Sell 13", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(14), title = "Buy/Sell 14", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
plotshape(fPlotBuySell(15), title = "Buy/Sell 15", style = shape.diamond, location = location.absolute, color = Color, size = size.tiny)
// ————— Plotting Lines under PP
fBuySellLevel(_n) =>
if low < fGrid(PPdownOrigin, -GridWidth, _n) and PP > fGrid(PPdownOrigin, -GridWidth, _n)
fGrid(PPdownOrigin, -GridWidth, _n)
else
if high > fGrid(PPupOrigin, GridWidth, _n) and PP < fGrid(PPupOrigin, GridWidth, _n)
fGrid(PPupOrigin, GridWidth, _n)
plot(fBuySellLevel(1), title = "Level down/up 1", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(2), title = "Level down/up 2", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(3), title = "Level down/up 3", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(4), title = "Level down/up 4", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(5), title = "Level down/up 5", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(6), title = "Level down/up 6", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(7), title = "Level down/up 7", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(8), title = "Level down/up 8", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(9), title = "Level down/up 9", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(10), title = "Level down/up 10", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(11), title = "Level down/up 11", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(12), title = "Level down/up 12", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(13), title = "Level down/up 13", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(14), title = "Level down/up 14", style = plot.style_circles, color = high > PP ? color.green : color.red)
plot(fBuySellLevel(15), title = "Level down/up 15", style = plot.style_circles, color = high > PP ? color.green : color.red)
// by XaviZ💤 |
Tale Indicators Strategy | https://www.tradingview.com/script/jrY1mkXK-Tale-Indicators-Strategy/ | ehaarjee | https://www.tradingview.com/u/ehaarjee/ | 114 | 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/
// © ehaarjee, ECHKAY, JackBauer007
//@version=4
//study(title="Tale_indicators", overlay=true)
strategy("Tale Indicators Strategy", overlay=true, precision=8, max_bars_back=200, pyramiding=0, initial_capital=20000, commission_type="percent", commission_value=0.1)
len_fast = input(3, minval=1, title="FAST EMA")
src_fast = input(close, title="Source for Fast")
fastMA = ema(src_fast, len_fast)
plot(fastMA, title="Slow EMA", color=color.orange)
len_slow = input(15, minval=1, title="SLOW EMA")
src_slow = input(close, title="Source for Slow")
slowMA = ema(src_slow, len_slow)
plot(slowMA, title="Fast EMA", color=color.blue)
len_fast_exit = input(3, minval=1, title="FAST EMA Exit")
src_fast_exit = input(close, title="Source for Fast Exit")
fastMAE = ema(src_fast_exit, len_fast_exit)
plot(fastMAE, title="Fast EMA Ex", color=color.red)
src_slow_enter_short = input(low, title="Source for Short Entry")
slowMASEn = ema(src_slow_enter_short, len_slow)
src_slow_enter_long = input(high, title="Source for Long Entry")
slowMALEn = ema(src_slow_enter_long, len_slow)
src_slow_exit_short = input(high, title="Source for Short Exit")
slowMASEx = ema(src_slow_exit_short, len_slow)
src_slow_exit_long = input(low, title="Source for Long Exit")
slowMALEx = ema(src_slow_exit_long, len_slow)
enter_long = crossover(fastMA, slowMALEn)
enter_short = crossunder(fastMA, slowMASEn)
exit_long = crossunder(fastMAE, slowMALEx)
exit_short = crossover(fastMAE, slowMASEx)
out_enter = iff(enter_long == true, 1, iff(enter_short == true, -1, 0))
plotarrow(out_enter, "Plot Enter Points", colorup=color.green, colordown=color.red, maxheight = 30)
bull = fastMA > slowMALEn
bear = fastMA < slowMASEn
c = bull ? color.green : bear ? color.red : color.white
bgcolor(c)
exit_tuner = input(0.005, title="Exit Tuner to touch slowEMA")
bull_exit = (low>(fastMAE*(1+exit_tuner))) or exit_long
bear_exit = ((fastMAE*(1-exit_tuner))>high) or exit_short
bull_r = (bull and ((bull_exit[1]) or (bull_exit[2] and bull_exit[1])) and (low<=fastMAE))
bear_r = (bear and ((bear_exit[1]) or (bull_exit[2] and bull_exit[1])) and (fastMAE<=high))
bull_re = (bull and (low<slowMALEn)) and not(enter_long)
bear_re = (bear and (high>slowMASEn)) and not(enter_short)
bull_ree = (bull and ((low<slowMALEn) and not(bull_re[1] or enter_long[1])))
bear_ree = (bear and ((high>slowMASEn) and not(bear_re[1] or enter_short[1])))
bull_reenter = (bull_r or bull_ree) and not(enter_long)
bear_reenter = (bear_r or bear_ree) and not(enter_short)
plotshape(bull_exit, "Plot Bull Exit", style = shape.arrowdown, color=color.green, size=size.small, text="ExL", location=location.abovebar)
plotshape(bear_exit, "Plot Bear Exit", style = shape.arrowup, color=color.red, size=size.small, text="ExS", location=location.belowbar)
plotshape(bull_reenter, "Plot Bull ReEnter", style = shape.arrowup, color=color.green, size=size.small, text="ReL", location=location.belowbar)
plotshape(bear_reenter, "Plot Bear ReEnter", style = shape.arrowdown, color=color.red, size=size.small, text="ReS", location=location.abovebar)
run_strategy = input(false, title="Run Strategy")
// === INPUT BACKTEST RANGE ===
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 = 2000)
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 = 2100, title = "Thru Year", type = input.integer, minval = 2000)
// === INPUT SHOW PLOT ===
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
// === FUNCTION EXAMPLE ===
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"
var long_position_open = false
var short_position_open = false
if (enter_long and not(bull_exit) and not(long_position_open))
long_position_open := true
if (bull_reenter and not(long_position_open))
long_position_open := true
if (bull_exit and long_position_open)
long_position_open := false
if (enter_short and not(bear_exit) and not(short_position_open))
short_position_open := true
if (bear_reenter and not(short_position_open))
short_position_open := true
if (bear_exit and short_position_open)
short_position_open := false
if(run_strategy)
strategy.entry("LO", strategy.long, when=(window() and enter_long and not(bull_exit)), qty=4)
strategy.entry("LO", strategy.long, when=(window() and bull_reenter), qty=1)
strategy.close("LO", when=(window() and bull_exit))
strategy.entry("SO", strategy.short, when=(window() and enter_short and not(bear_exit)), qty=4)
strategy.entry("SO", strategy.short, when=(window() and bear_reenter), qty=1)
strategy.close("SO", when=(window() and bear_exit))
|
Ichimoku Cloud Strategy v2.0 | https://www.tradingview.com/script/2Co5NKpi-Ichimoku-Cloud-Strategy-v2-0/ | iamskrv | https://www.tradingview.com/u/iamskrv/ | 112 | 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/
// © iamskrv
//@version=4
strategy("Ichimoku Cloud Strategy v2.0", overlay=true)
//@version=4
// study(title="Ichimoku Cloud", shorttitle="Ichimoku", overlay=true)
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)
// Strategy
longCondition = crossover(conversionLine,baseLine)
if (longCondition)
strategy.entry("Buy", strategy.long)
shortCondition = crossover(baseLine, conversionLine)
if (shortCondition)
strategy.entry("Short", strategy.short) |
RSI5_50 with Divergence | https://www.tradingview.com/script/16yhUQN3-RSI5-50-with-Divergence/ | mohanee | https://www.tradingview.com/u/mohanee/ | 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/
// © mohanee
//@version=4
//GOOGL setting 5 ,50 close, 3 , 1 profitLevel at 75 and No stop Loss shows win rate 99.03 % profit factor 5830.152
strategy(title="RSI5_50 with Divergence", overlay=false,pyramiding=2, default_qty_type=strategy.fixed, default_qty_value=3, initial_capital=10000, currency=currency.USD)
len = input(title="RSI Period", minval=1, defval=5)
longRSILen = input(title="Long RSI Period", minval=10, defval=50)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=3)
lbL = input(title="Pivot Lookback Left", defval=1)
takeProfitRSILevel = input(title="Take Profit at RSI Level", minval=50, defval=75)
stopLoss = input(title="Stop Loss%(if checked 8% rule applied)", defval=false)
shortTermRSI = rsi(close,len)
longTermRSI = rsi(close,longRSILen)
rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false)
bearColor = color.purple
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
plot(shortTermRSI, title="RSI", linewidth=2, color=#8D1699)
plot(longTermRSI, title="longTermRSI", linewidth=2, color=color.orange)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevel = hline(70, title="Overbought", linestyle=hline.style_dotted)
osLevel = hline(30, title="Oversold", linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=longTermRSI >=50 ? color.green:color.purple, transp=65) // longTermRSI >=50
plFound = na(pivotlow(shortTermRSI, lbL, lbR)) ? false : true
phFound = na(pivothigh(shortTermRSI, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// shortTermRSI: Higher Low
oscHL = shortTermRSI[lbR] > valuewhen(plFound, shortTermRSI[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
plFound ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor),
transp=0
)
plotshape(
bullCond ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bullish
// shortTermRSI: Lower Low
oscLL = shortTermRSI[lbR] < valuewhen(plFound, shortTermRSI[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
plFound ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
transp=0
)
plotshape(
hiddenBullCond ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
longCondition= longTermRSI >=50 and ( (bullCond or hiddenBullCond ) ) or (strategy.position_size>0 and crossover(shortTermRSI,20) )
//last condition above is to leg in if you are already in the Long trade,
strategy.entry(id="RSIDivLE", long=true, when=longCondition)
//------------------------------------------------------------------------------
// Regular Bearish
// shortTermRSI: Lower High
oscLH = shortTermRSI[lbR] < valuewhen(phFound, shortTermRSI[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
phFound ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor),
transp=0
)
plotshape(
bearCond ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bearish
// shortTermRSI: Higher High
oscHH = shortTermRSI[lbR] > valuewhen(phFound, shortTermRSI[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
phFound ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
transp=0
)
plotshape(
hiddenBearCond ? shortTermRSI[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
//calculate stop Loss
stopLossVal = stopLoss==true ? ( strategy.position_avg_price - (strategy.position_avg_price*0.08) ) : 0
//partial profit
strategy.close(id="RSIDivLE", comment="TP1", qty=strategy.position_size*3/4, when=strategy.position_size>0 and (longTermRSI>=takeProfitRSILevel or crossover(longTermRSI,90)))
strategy.close(id="RSIDivLE",comment="TP2", qty=strategy.position_size*3/4 , when=crossover(longTermRSI,70))
strategy.close(id="RSIDivLE",comment="TP3", qty=strategy.position_size/2, when=crossover(longTermRSI,65))
strategy.close(id="RSIDivLE",comment="TP4", qty=strategy.position_size/2 , when=crossover(longTermRSI,60))
//close the whole position when stoploss hits or longTermRSI goes below 30
strategy.close(id="RSIDivLE",comment="Exit", when=crossunder(longTermRSI,30) or close<stopLossVal)
|
EMA Slope Trend Follower Strategy | https://www.tradingview.com/script/TKg40Ska/ | lukescream | https://www.tradingview.com/u/lukescream/ | 2,113 | 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/
// © lukescream
//@version=4
strategy("EMA Slope Trend Follower", initial_capital=10000, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.06, slippage = 2, default_qty_value=30, overlay=false)
//definizione input
average = input (title="Source MA Type", type=input.string, defval="EMA",options=["EMA","SMA"])
len = input(130, minval=1, title="Source MA Length")
slopeFlen = input (9,title="Fast Slope MA Length")
slopeSlen= input (21,title="Slow Slope MA Length")
trendfilter=input(true,title="Trend Filter")
trendfilterperiod=input(200,title="Trend Filter MA Period")
trendfiltertype=input (title="Trend Filter MA Type", type=input.string, defval="EMA",options=["EMA","SMA"])
volatilityfilter=input(false,title="Volatility Filter")
volatilitystdevlength=input(20,title="Vol Filter STDev Length")
volatilitystdevmalength=input(30,title="Vol Filter STDev MA Length")
//variabili
out = if average == "EMA"
ema(close,len)
else
sma(close,len)
slp = change(out)/out
emaslopeF = ema(slp,slopeFlen)
emaslopeS = ema(slp,slopeSlen)
//variabili accessorie e condizioni
TrendConditionL=if trendfiltertype =="EMA"
close>ema(close,trendfilterperiod)
else
close>sma(close,trendfilterperiod)
TrendConditionS=if trendfiltertype =="EMA"
close<ema(close,trendfilterperiod)
else
close<sma(close,trendfilterperiod)
VolatilityCondition=stdev(close,volatilitystdevlength)>sma(stdev(close,volatilitystdevlength),volatilitystdevmalength)
ConditionEntryL= if trendfilter == true
if volatilityfilter == true
emaslopeF>emaslopeS and TrendConditionL and VolatilityCondition
else
emaslopeF>emaslopeS and TrendConditionL
else
if volatilityfilter == true
emaslopeF>emaslopeS and VolatilityCondition
else
emaslopeF>emaslopeS
ConditionEntryS= if trendfilter == true
if volatilityfilter == true
emaslopeF<emaslopeS and TrendConditionS and VolatilityCondition
else
emaslopeF<emaslopeS and TrendConditionS
else
if volatilityfilter == true
emaslopeF<emaslopeS and VolatilityCondition
else
emaslopeF<emaslopeS
ConditionExitL=crossunder(emaslopeF,emaslopeS)
ConditionExitS=crossover(emaslopeF,emaslopeS)
//plot
plot (slp, color=color.white)
plot (emaslopeF,color=color.yellow)
plot (emaslopeS,color=color.red)
//ingressi e uscite
if ConditionExitS
if strategy.position_size < 0
strategy.close("SLPShort")
if ConditionExitL
if strategy.position_size > 0
strategy.close("SLPLong")
if ConditionEntryL
strategy.entry("SLPLong",long=true)
if ConditionEntryS
strategy.entry("SLPShort",long=false) |
MACD Trend Following Strategy | https://www.tradingview.com/script/WhhrjwC5-MACD-Trend-Following-Strategy/ | DeMindSET | https://www.tradingview.com/u/DeMindSET/ | 67 | 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/
// © DeMindSET
//@version=4
strategy("MACD Trend Follow Strategy", overlay=false)
// Getting inputs
LSB = input(title="Long/Short", defval="Long only", options=["Long only", "Short only" , "Both"])
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=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
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)
//
Bull= macd > signal
Bear= macd < signal
ConBull=macd>0
ConBear=macd<0
//
Green= Bull and ConBull
Red= Bear and ConBear
Yellow= Bull and ConBear
Blue= Bear and ConBull
//
bcolor = Green ? color.green : Red ? color.red : Yellow ? color.yellow : Blue ? color.blue : na
barcolor(color=bcolor)
// === INPUT BACKTEST RANGE ===
FromYear = input(defval = 2010, title = "From Year", minval = 1920)
FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 2009)
ToMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
// === FUNCTION EXAMPLE ===
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"
if LSB == "Long only" and Green and window()
strategy.entry("L",true)
if LSB == "Long only" and Red and window()
strategy.close("L",qty_percent=100,comment="TP Long")
if LSB == "Both" and Green and window()
strategy.entry("L",true)
if LSB == "Both" and Red and window()
strategy.entry("S",false)
if LSB == "Short only" and Red and window()
strategy.entry("S",false)
if LSB == "Short only" and Green and window()
strategy.close("S",qty_percent=100,comment="TP Short")
|
STRATEGY:RETRACEMENT | https://www.tradingview.com/script/1x7Dutbk-STRATEGY-RETRACEMENT/ | ponml | https://www.tradingview.com/u/ponml/ | 283 | 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/
// © ponml
//@version=4
strategy(title = "STRATEGY:RETRACEMENT", format = format.price, max_bars_back = 5000, precision = 2, overlay = true, pyramiding = 0, calc_on_order_fills = false, calc_on_every_tick = false, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 100, currency = "BTC", slippage = 0, commission_type = strategy.commission.percent, commission_value = 0.075)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Functions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Line Drawing Function
drawLine(_y1, _y2, _period, _width, _text)=>
int _x1 = nz(bar_index[_period], 0)
int _x2 = bar_index
var line _line = na
var label _label = na
if bar_index != nz(bar_index[1], 0)
line.delete(_line)
_line := line.new(x1 = _x1, y1 = _y1, x2 = _x2, y2 = _y2, xloc = xloc.bar_index, extend = extend.none, color = color.black, style = line.style_solid, width = _width)
label.delete(_label)
_label := label.new(bar_index - 3, _y2, _text, style = label.style_none)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Inputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Lookback Periods
high_lookback_period = input(defval = 200, type = input.integer, title = "High Lookback Period", minval = 1, step = 1)
low_lookback_period = input(defval = 200, type = input.integer, title = "Low Lookback Period", minval = 1, step = 1)
//Backtest Range
from_month = input(defval = 1, type = input.integer, title = "From Month", minval = 1, maxval = 12)
from_day = input(defval = 1, type = input.integer, title = "From Day", minval = 1, maxval = 31)
from_year = input(defval = 2019, type = input.integer, title = "From Year", minval = 1970)
thru_month = input(defval = 1, type = input.integer, title = "Thru Month", minval = 1, maxval = 12)
thru_day = input(defval = 1, type = input.integer, title = "Thru Day", minval = 1, maxval = 31)
thru_year = input(defval = 2021, type = input.integer, title = "Thru Year", minval = 1970)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Backtest Window
start = timestamp(from_year, from_month, from_day, 00, 00)
finish = timestamp(thru_year, thru_month, thru_day, 23, 59)
window()=> time >= start and time <= finish ? true : false
last_high = 0.0
last_high := na(last_high[1]) ? 0.0 : last_high[1]
//Highest High for Lookback Period
highest = highest(high, high_lookback_period)
//Lowest Low for Lookback Period
lowest = lowest(low, low_lookback_period)
//Period for Lines
period = max(-highestbars(high, high_lookback_period), -lowestbars(low, low_lookback_period))
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Plots
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Plot Highest
if (window())
drawLine(highest, highest, period, 2, "1.000")
//Plot Lowest
if (window())
drawLine(lowest, lowest, period, 2, "0.000")
//Plot Fib
if (window())
drawLine((highest - lowest) * 0.236 + lowest, (highest - lowest) * 0.236 + lowest, period, 1, "0.236")
drawLine((highest - lowest) * 0.382 + lowest, (highest - lowest) * 0.382 + lowest, period, 1, "0.382")
drawLine((highest - lowest) * 0.618 + lowest, (highest - lowest) * 0.618 + lowest, period, 1, "0.618")
drawLine((highest - lowest) * 0.786 + lowest, (highest - lowest) * 0.786 + lowest, period, 1, "0.786")
|
RSI Divergence X Ichimoku Cloud X 200EMA | https://www.tradingview.com/script/IDBU7W3o-RSI-Divergence-X-Ichimoku-Cloud-X-200EMA/ | tradethrills | https://www.tradingview.com/u/tradethrills/ | 601 | 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/
// © tradethrills
//@version=4
strategy("RSI Divergence X Ichimoku Cloud X 200EMA", overlay=true)
//RSI Indicator
len = input(defval=14, minval=1)
src = input(defval=close)
lbR = input(defval=5)
lbL = input(defval=5)
takeProfitLevellong = input(minval = 70, defval = 75)
takeProfitLevelshort = input(minval = 30, defval = 25)
rangeUpper = input(defval=60)
rangeLower = input(defval=5)
//200 EMA
ema200 = ema(close, 200)
//Ichimoku Cloud Indicator
conversionPeriods = input(9, minval=1)
basePeriods = input(26, minval=1)
laggingSpan2Periods = input(52, minval=1)
displacement = input(26, minval=1)
donchian(len) => avg(lowest(len), highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
abovecloud = max(leadLine1, leadLine2)
belowcloud = min(leadLine1, leadLine2)
//RSI Divergence Strategy
osc = rsi(src, len)
_inrange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
pricelowfound = na(pivotlow(osc, lbL, lbR)) ? false : true
pricehighfound = na(pivothigh(osc, lbL, lbR)) ? false : true
//Regular Bullish
osc_higherlow = osc[lbR] > valuewhen(pricelowfound, osc[lbR], 1) and _inrange(pricelowfound[1])
price_lowerlow = low[lbR] < valuewhen(pricelowfound, low[lbR], 1)
bullCond = price_lowerlow and osc_higherlow and pricelowfound
//Hidden Bullish
osc_lowerlow = osc[lbR] < valuewhen(pricelowfound, osc[lbR], 1) and _inrange(pricelowfound[1])
price_higherlow = low[lbR] > valuewhen(pricelowfound, low[lbR], 1)
hiddenbullCond = price_higherlow and osc_lowerlow and pricelowfound
//Regular Bearish
osc_lowerhigh = osc[lbR] < valuewhen(pricehighfound, osc[lbR], 1) and _inrange(pricehighfound[1])
price_higherhigh = high[lbR] > valuewhen(pricehighfound, high[lbR], 1)
bearCond = price_higherhigh and osc_lowerhigh and pricehighfound
//Hidden Bearish
osc_higherhigh = osc[lbR] > valuewhen(pricehighfound, osc[lbR], 1) and _inrange(pricehighfound[1])
price_lowerhigh = high[lbR] < valuewhen(pricehighfound, high[lbR], 1)
hiddenbearCond = price_lowerhigh and osc_higherhigh and pricehighfound
//Entry and Exit
longCondition = (bullCond or hiddenbullCond) and (abovecloud > ema200)
closelongCondition = crossover(osc, takeProfitLevellong)
shortCondition = (bearCond or hiddenbearCond) and (ema200 > belowcloud)
closeshortCondition = crossover(osc, takeProfitLevelshort)
strategy.entry("Long", strategy.long, 10000.0, when=longCondition)
strategy.close("Long", when=closelongCondition)
strategy.entry("Short", strategy.short, 10000.0, when=shortCondition)
strategy.close("Short", when=closeshortCondition)
|
McGinley Dynamic Indicator | https://www.tradingview.com/script/WHMsbRLs/ | LucasZancheta | https://www.tradingview.com/u/LucasZancheta/ | 257 | 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/
// © LucasZancheta
//@version=4
strategy(shorttitle="Maguila", title="McGinley Dynamic Indicator", overlay=true)
//Médias móveis
MA1Period=input(21, title="MA1")
MA2Period=input(42, title="MA2")
MA1 = ema(close, MA1Period)
MA2 = ema(close, MA2Period)
aboveAverage = MA1 >= MA2
hunderAverage = MA2 >= MA1
//Período do backtest
startDate = input(title="Start Date", type=input.integer, defval=28, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer, defval=5, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer, defval=2019, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer, defval=28, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer, defval=5, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer, defval=2020, minval=1800, maxval=2100)
//Verifica se o candle está dentro do período do backtest
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
//Número de periodos da média móvel
period = input(title="Períodos", type=input.integer, defval=20)
//Constante K (0.6)
k = input(title="Constante K", type=input.float, defval=0.6)
//Preço de fechamento
closePrice = input(title="Preço", type=input.source, defval=close)
mdi = 0.0
//Fórmula de McGinley
mdi := na(mdi[1]) ? closePrice : mdi[1] + (closePrice - mdi[1]) / max((k * period * pow(closePrice / mdi[1], 4)), 1)
//Regra de coloração
mdiColor = closePrice > mdi ? color.green : closePrice < mdi ? color.red : color.black
//Inserindo as informações no gráfico
plot(MA1, color=color.blue, linewidth=2)
plot(MA2, color=color.purple, linewidth=2)
barcolor(mdiColor)
//Estratégia
buySignal = aboveAverage and closePrice > mdi and crossunder(low, MA1) and close > MA1
buyLoss = closePrice < mdi and close < MA1 and close < MA2
if (inDateRange)
strategy.entry("Compra", strategy.long, qty=1, when= buySignal)
strategy.exit("Gain da compra", "Compra", qty=1, profit=20)
strategy.close("Compra", qty=1, when= buyLoss, comment="Loss na operação")
sellSignal = hunderAverage and closePrice < mdi and crossover(high, MA1) and close < MA1
sellLoss = closePrice > mdi and close > MA1 and close > MA2
if (inDateRange)
strategy.entry("Venda", strategy.short, qty=1, when= sellSignal)
strategy.exit("Gain da venda", "Venda", qty=1, profit=20)
strategy.close("Venda", qty=1, when= sellLoss, comment="Loss na operação")
if (not inDateRange)
strategy.close_all()
|
MacD 200 Day Moving Average Signal Crossover Strategy | https://www.tradingview.com/script/3zO6NXsn-MacD-200-Day-Moving-Average-Signal-Crossover-Strategy/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 320 | 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/
// © x11joe
//@version=4
//This strategy is based on a youtube strategy that suggested I do this...so I did!
strategy(title="MacD 200 Day Moving Average Signal Crossover Strategy", overlay=false, precision=2,commission_value=0.26, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// 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=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
moving_avg_length = input(title="Moving Average Length", type=input.integer, defval=200)
moving_avg = sma(close,moving_avg_length)
moving_avg_normalized = close - moving_avg
plot(moving_avg_normalized, title="Moving Average Normalized", style=plot.style_line, color=color.orange,linewidth=3)
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)
if(macd>signal and macd<0 and close>moving_avg)
strategy.entry("buy",strategy.long)
if(close<moving_avg and macd<signal and macd>0)
strategy.entry("sell",strategy.short) |
Strategy Timeframe | https://www.tradingview.com/script/CgQqmkXM-Strategy-Timeframe/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 70 | 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("Strategy Timeframe", overlay=true)
// === 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, 14), sma(close, 28))
if (window() and longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (window() and shortCondition)
strategy.entry("My Short Entry Id", strategy.short) |
Strategy Tester EMA-SMA-RSI-MACD | https://www.tradingview.com/script/akcty6VI-Strategy-Tester-EMA-SMA-RSI-MACD/ | fikira | https://www.tradingview.com/u/fikira/ | 544 | 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/
// © fikira
//@version=4
strategy("Strategy Tester EMA-SMA-RSI-MACD", shorttitle="Strat-test", overlay=true, max_bars_back=5000,
default_qty_type= strategy.percent_of_equity, calc_on_order_fills=false, calc_on_every_tick=false,
pyramiding=0, default_qty_value=100, initial_capital=100)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// "&" issue when added to _L_ :
//L_S = "Long & Short" , _L_ = "Long & Only" , _S_ = "Short Only"
// no issue (initial correct working version) :
L_S = "Long & Short" , _L_ = "Long Only" , _S_ = "Short Only"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Tiny = "Tiny"
Small = "Small"
Normal = "Normal"
Large = "Large"
cl = "close" , op = "open" , hi = "high" , lo = "low"
c4 = "ohlc4" , c3 = "hlc3" , hl = "hl2"
co = "xMA 1 > xMA 2"
cu = "xMA 3 < xMA 4"
co_HTF = "xMA 1 (HTF) > xMA 2 (HTF)"
cu_HTF = "xMA 3 (HTF) < xMA 4 (HTF)"
cla = "Close above xMA 1"
clu = "Close under xMA 3"
cla_HTF = "Close above xMA 1 (HTF)"
clu_HTF = "Close under xMA 3 (HTF)"
rsi = "RSI strategy"
notBuy = "BUY = false" , none = "NONE"
mch = "macd > signal" , mcl = "macd < signal"
mch0 = "macd > 0" , mcl0 = "macd < 0"
sgh0 = "signal > 0" , sgl0 = "signal < 0"
hisbl = "hist > hist[1]" , hisbr = "hist < hist[1]"
mch_HTF = "macd (HTF) > signal (HTF)" , mcl_HTF = "macd (HTF) < signal (HTF)"
mch0HTF = "macd (HTF) > 0" , mcl0HTF = "macd (HTF) < 0"
sgh0HTF = "signal (HTF) > 0" , sgl0HTF = "signal (HTF) < 0"
//s = input(cl, "Source" , options=[cl, op, hi, lo, c4, c3, hl])
src = input(title="Source", type=input.source, defval=close)
//src =
// s == cl ? close :
// s == op ? open :
// s == hi ? high :
// s == lo ? low :
// s == c4 ? ohlc4 :
// s == c3 ? hlc3 :
// s == hl ? hl2 :
// source
__1_ = input(false, ">=< >=< [STRATEGIES] >=< >=<")
Type = input(_L_, "Type Strategy", options=[L_S, _L_, _S_])
_1a_ = input(false, ">=< >=< [BUY/LONG] >=< >=<")
ENT = input(co, "Pick your poison:", options=[co, cla, rsi, mch, mch0, sgh0])
EH = input(0, " if RSI >")
EL = input(100, " if RSI <")
EH_HTF = input(0, " if RSI (HTF) >")
EL_HTF = input(100, " if RSI (HTF) <")
EX = input(none, " Extra argument", options=[none, mch, mch0, sgh0, hisbl])
EX2 = input(none, " Second argument", options=[none, mch_HTF, mch0HTF, sgh0HTF, co_HTF, cla_HTF])
_1b_ = input(false, ">=< [xMA settings (Buy/Long)] >=<")
ma1 = input(defval="SMA", title=" xMA 1" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len1 = input(50, " Length" )
ma2 = input(defval="SMA", title=" xMA 2" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len2 = input(100, " Length" )
ma1HTF = input(defval="SMA", title=" xMA 1 - HTF" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len1HTF = input(50, " Length" )
ma2HTF = input(defval="SMA", title=" xMA 2 - HTF" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len2HTF = input(100, " Length" )
_2a_ = input(false, ">=< >=< [SELL/SHORT] >=< >=<")
CLO = input(cu, "Pick your poison:", options=[notBuy, cu, clu, rsi, mcl, mcl0, sgl0])
CH = input(0, " if RSI >")
CL = input(100, " if RSI <")
CH_HTF = input(0, " if RSI (HTF) >")
CL_HTF = input(100, " if RSI (HTF) <")
CX = input(none, " Extra argument", options=[none, mcl, mcl0, sgl0, hisbr])
CX2 = input(none, " Second argument", options=[none, mcl_HTF, mcl0HTF, sgl0HTF, cu_HTF, clu_HTF])
_2b_ = input(false, ">=< [xMA settings (Sell/Short)] >=<")
ma3 = input(defval="SMA", title=" xMA 3" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len3 = input(50, " Length" )
ma4 = input(defval="SMA", title=" xMA 4" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len4 = input(100, " Length" )
ma3HTF = input(defval="SMA", title=" xMA 3 - HTF" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len3HTF = input(50, " Length" )
ma4HTF = input(defval="SMA", title=" xMA 4 - HTF" , options=["SMA", "EMA", "WMA", "HullMA", "VWMA", "RMA", "TEMA"])
len4HTF = input(100, " Length" )
__3_ = input(false, ">=< >=< [RSI] >=< >=< >=<")
ler = input(20 , " RSI Length")
__4_ = input(false, ">=< >=< [MACD] >=< >=< >=<")
fst = input(12, " Fast Length")
slw = input(26, " Slow Length")
sgn = input(9 , " Signal Smoothing")
sma_source = input(false, "Simple MA(Oscillator)")
sma_signal = input(false, "Simple MA(Signal Line)")
__5_ = input(false, ">=< >=< [HTF settings] >=< >=<")
MA_HTF = input("D", " xMA HTF" , type = input.resolution)
RSI_HTF = input("D", " RSI HTF" , type = input.resolution)
MACD_HTF= input("D", " MACD HTF" , type = input.resolution)
__6_ = input(false, ">=< >=< [SL/TP] >=< >=< >=<")
SL = input(10.0, title=" Stop Loss %" ) / 100
TP = input(20.0, title=" Take Profit %") / 100
SL_B = strategy.position_avg_price * (1 - SL)
TP_B = strategy.position_avg_price * (1 + TP)
SL_S = strategy.position_avg_price * (1 + SL)
TP_S = strategy.position_avg_price * (1 - TP)
// Limitation in time
// (= inspired from a script of "Che_Trader")
xox = input(false, ">=< >=< [TIME] >=< >=< >=<")
ystr1 = input(2010, " Since Year" )
ystp1 = input(2099, " Till Year" )
mstr1 = input(1 , " Since Month")
mstp1 = input(12 , " Till Month" )
dstr1 = input(1 , " Since Day" )
dstp1 = input(31 , " Till Day" )
_Str1 = timestamp(ystr1, mstr1, dstr1, 1, 1)
Stp1_ = timestamp(ystp1, mstp1, dstp1, 23, 59)
TIME = time >= _Str1 and time <= Stp1_ ? true : false
////////////////////////////////////////////////////////////////////////////////////////////
f_xma(type, len) =>
type == "SMA" ? sma(src,len) :
type == "EMA" ? ema(src,len) :
type == "WMA" ? wma(src,len) :
type == "VWMA" ? vwma(src,len) :
type == "RMA" ? rma(src,len) :
type == "HullMA" ? wma(2*wma(src, len/2)-wma(src, len), round(sqrt(len))) :
3 * (ema(src, len) - ema(ema(src, len), len)) + ema(ema(ema(src, len), len), len)
_1 = f_xma(ma1 , len1 )
_2 = f_xma(ma2 , len2 )
_3 = f_xma(ma3 , len3 )
_4 = f_xma(ma4 , len4 )
_1b = f_xma(ma1HTF, len1HTF)
_2b = f_xma(ma2HTF, len2HTF)
_3b = f_xma(ma3HTF, len3HTF)
_4b = f_xma(ma4HTF, len4HTF)
_1_HTF = security(syminfo.tickerid, MA_HTF, _1b , lookahead = barmerge.lookahead_on)
_2_HTF = security(syminfo.tickerid, MA_HTF, _2b , lookahead = barmerge.lookahead_on)
_3_HTF = security(syminfo.tickerid, MA_HTF, _3b , lookahead = barmerge.lookahead_on)
_4_HTF = security(syminfo.tickerid, MA_HTF, _4b , lookahead = barmerge.lookahead_on)
cl_HTF = security(syminfo.tickerid, MA_HTF, close, lookahead = barmerge.lookahead_on)
////////////////////////////////////////////////////////////////////////////////////////////
plot(ENT == co or ENT == cla ? _1 : na , "xMA 1" , color.lime )
plot(ENT == co ? _2 : na , "xMA 2" , color.red )
plot(CLO == cu or CLO == clu ? _3 : na , "xMA 3" , _3 == _1 ? color.lime : color.yellow )
plot(CLO == cu ? _4 : na , "xMA 4" , _4 == _2 ? color.red : color.blue , 2, plot.style_line )
plot(EX2 == co_HTF or EX2 == cla_HTF ? _1_HTF : na, "xMA 1 HTF", color.lime , 2, plot.style_line, false, 50)
plot(EX2 == co_HTF ? _2_HTF : na, "xMA 2 HTF", color.red , 2, plot.style_line, false, 50)
plot(CX2 == cu_HTF or CX2 == clu_HTF ? _3_HTF : na, "xMA 3 HTF", _3_HTF == _1_HTF ? color.lime : color.yellow, 2, plot.style_line, false, 50)
plot(CX2 == cu_HTF or CX2 == clu_HTF ? _3_HTF : na, "xMA 3 HTF", _3_HTF == _1_HTF ? color.lime : color.yellow, 2, plot.style_line, false, 50)
plot(CX2 == cu_HTF ? _4_HTF : na, "xMA 4 HTF", _4_HTF == _2_HTF ? color.red : color.blue , 2, plot.style_line, false, 50)
//plot(series, title, color, linewidth, style, trackprice, transp, histbase, offset, join, editable, show_last, display) → plot
////////////////////////////////////////////////////////////////////////////////////////////
// RSI
rsi_ = rsi(src, ler)
rsi_HTF = security(syminfo.tickerid, RSI_HTF , rsi_ , lookahead = barmerge.lookahead_on)
////////////////////////////////////////////////////////////////////////////////////////////
// MACD
fast_ma = sma_source ? sma(src, fst) : ema(src , fst)
slow_ma = sma_source ? sma(src, slw) : ema(src , slw)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, sgn) : ema(macd, sgn)
hist = macd - signal
macd_HTF = security(syminfo.tickerid, MACD_HTF, macd , lookahead = barmerge.lookahead_on)
signal_HTF = security(syminfo.tickerid, MACD_HTF, signal, lookahead = barmerge.lookahead_on)
////////////////////////////////////////////////////////////////////////////////////////////
extra =
EX == none ? true :
EX == mch ? macd > signal :
EX == mch0 ? macd > 0 :
EX == sgh0 ? signal > 0 :
EX == hisbl ? hist[1] < 0
and hist > hist[1] :
false
cxtra =
CX == none ? true :
CX == mcl ? macd <= signal :
CX == mcl0 ? macd <= 0 :
CX == sgl0 ? signal <= 0 :
CX == hisbr ? hist[1] > 0
and hist < hist[1] :
false
EXTRA =
EX2 == none ? true :
EX2 == mch_HTF ? macd_HTF > signal_HTF :
EX2 == mch0HTF ? macd_HTF > 0 :
EX2 == sgh0HTF ? signal_HTF > 0 :
EX2 == co_HTF ? _1_HTF > _2_HTF :
EX2 == cla_HTF ? cl_HTF > _1_HTF :
false
CXTRA =
CX2 == none ? true :
CX2 == mcl_HTF ? macd_HTF <= signal_HTF :
CX2 == mcl0HTF ? macd_HTF <= 0 :
CX2 == sgl0HTF ? signal_HTF <= 0 :
CX2 == cu_HTF ? _3_HTF <= _4_HTF :
CX2 == clu_HTF ? cl_HTF <= _3_HTF :
false
RSI = rsi_ > EH and rsi_ <= EL and rsi_HTF > EH_HTF and rsi_HTF <= EL_HTF
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BUY =
ENT == co and TIME and extra and EXTRA and RSI ? _1 > _2 :
ENT == cla and TIME and extra and EXTRA and RSI ? src > _1 :
ENT == rsi and TIME and extra and EXTRA ? RSI :
ENT == mch and TIME and extra and EXTRA and RSI ? macd > signal :
ENT == mch0 and TIME and extra and EXTRA and RSI ? macd > 0 :
ENT == sgh0 and TIME and extra and EXTRA and RSI ? signal > 0 :
na
SELL =
CLO == notBuy ? not BUY :
CLO == cu and TIME and cxtra and CXTRA and RSI ? _3 <= _4 :
CLO == clu and TIME and cxtra and CXTRA and RSI ? src <= _3 :
CLO == rsi and TIME and cxtra and CXTRA ? RSI :
CLO == mcl and TIME and cxtra and CXTRA and RSI ? macd <= signal :
CLO == mcl0 and TIME and cxtra and CXTRA and RSI ? macd <= 0 :
CLO == sgl0 and TIME and cxtra and CXTRA and RSI ? signal <= 0 :
na
if BUY
if (Type == _S_)
strategy.close("[S]")
else
strategy.entry("[B]", strategy.long)
if SELL
if (Type == _L_)
strategy.close("[B]")
else
strategy.entry("[S]", strategy.short)
if SL_B
strategy.exit("[SL/TP]" , "[B]", stop= SL_B, limit= TP_B)
if SL_S
strategy.exit("[SL/TP]" , "[S]", stop= SL_S, limit= TP_S)
SLTP_long = Type != _S_ and BUY [1] and (low <= SL_B [1] or high >= TP_B[1])
SLTP_short = Type != _L_ and SELL[1] and (high >= SL_S [1] or low <= TP_S[1])
TP_long = Type != _S_ and BUY [1] and high >= TP_B [1]
TP_short = Type != _L_ and SELL[1] and low <= TP_S [1]
close_long = not SLTP_long and Type == _L_ and SELL and BUY [1]
close_short = not SLTP_short and Type == _S_ and BUY and SELL[1]
SLTP = SLTP_long[1] or SLTP_short[1]
Long = Type != _S_ and ((BUY and not BUY[1] ) or (BUY and SLTP)) and not close_short
Short = Type != _L_ and ((SELL and not SELL[1]) or (SELL and SLTP)) and not close_long
plotshape(series=Short , title="Short" , style=shape.triangledown, location=location.abovebar, color=color.orange, size=size.tiny )
plotshape(series=Long , title="Long" , style=shape.triangleup , location=location.belowbar, color=color.lime , size=size.tiny )
plotshape(series=SLTP_long , title="SL/TP Long" , style=shape.xcross , location=location.abovebar, color=color.lime , size=size.tiny )
plotshape(series=SLTP_short , title="SL/TP Short", style=shape.xcross , location=location.belowbar, color=color.red , size=size.tiny )
plotshape(series=close_long , title="Close Long" , style=shape.square , location=location.abovebar, color=color.lime , size=size.tiny )
plotshape(series=close_short , title="Close Short", style=shape.square , location=location.belowbar, color=color.red , size=size.tiny )
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Debugging //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//plot = Type == _S_ and BUY ? 1 : Type != _S_ and BUY ? 2 : Type == _L_ and SELL ? -1 : Type != _L_ and SELL ? -2 :na
//plot(plot)
//plotchar(BUY, "", color=na)
//plotchar(SL_B, "", color=na)
//plotchar(SELL, "", color=na)
//plotchar(SL_S, "", color=na) |
Ranged Volume Strategy - evo | https://www.tradingview.com/script/YbzbEyDY-Ranged-Volume-Strategy-evo/ | EvoCrypto | https://www.tradingview.com/u/EvoCrypto/ | 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/
// © EvoCrypto
//@version=4
strategy("Ranged Volume Strategy - evo", shorttitle="Ranged Volume", format=format.volume)
// INPUTS {
Range_Length = input(5, title="Range Length", minval=1)
Heikin_Ashi = input(true, title="Heikin Ashi Colors")
Display_Bars = input(true, title="Show Bar Colors")
Display_Break = input(true, title="Show Break-Out")
Display_Range = input(true, title="Show Range")
// }
// SETTINGS {
Close = Heikin_Ashi ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close
Open = Heikin_Ashi ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open
Positive = volume
Negative = -volume
Highest = highest(volume, Range_Length)
Lowest = lowest(-volume, Range_Length)
Up = Highest > Highest[1] and Close > Open
Dn = Highest > Highest[1] and Close < Open
Volume_Color =
Display_Break and Up ? color.new(#ffeb3b, 0) :
Display_Break and Dn ? color.new(#f44336, 0) :
Close > Open ? color.new(#00c0ff, 60) :
Close < Open ? color.new(#000000, 60) : na
// }
//PLOTS {
plot(Positive, title="Positive Volume", color=Volume_Color, style=plot.style_histogram, linewidth=4)
plot(Negative, title="Negative Volume", color=Volume_Color, style=plot.style_histogram, linewidth=4)
plot(Display_Range ? Highest : na, title="Highest", color=color.new(#000000, 0), style=plot.style_line, linewidth=2)
plot(Display_Range ? Lowest : na, title="Lowest", color=color.new(#000000, 0), style=plot.style_line, linewidth=2)
barcolor(Display_Bars ? Volume_Color : na)
// }
if (Up)
strategy.entry("Long Entry", strategy.long)
if (Dn)
strategy.entry("Short Entry", strategy.short) |
Monthly MA Close | https://www.tradingview.com/script/jdxANexH-Monthly-MA-Close/ | universique | https://www.tradingview.com/u/universique/ | 108 | 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/
// © universique
//@version=4
strategy("Monthly MA Close ", shorttitle="MMAC", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
//MAY 6 2020 18:00
// No repaint function
// Function to securely and simply call `security()` so that it never repaints and never looks ahead.
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
//sec10 = f_secureSecurity(syminfo.tickerid, higherTf, data)
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
// ————— Returns the float minutes value of the string _res.
f_tfResInMinutes(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
// Dependency: f_resInMinutes().
security(syminfo.tickerid, _res, f_resInMinutes())
// —————————— Determine if current timeframe is smaller that higher timeframe selected in Inputs.
// Get higher timeframe in minutes.
//higherTfInMinutes = f_tfResInMinutes(higherTf)
// Get current timeframe in minutes.
currentTfInMinutes = f_resInMinutes()
// Compare current TF to higher TF to make sure it is smaller, otherwise our plots don't make sense.
//chartOnLowerTf = currentTfInMinutes < higherTfInMinutes
// Input
switch1=input(true, title="Show MA")
exponential = input(true, title="Exponential MA")
ticker = input(false, title="Other ticker MA")
tic_ma = input(title="Ticker MA", type=input.symbol, defval="SPY")
res_ma = input(title="Time MA (W, D, [min])", type=input.string, defval="M")
len_ma = input(8, minval=1, title="Period MA")
ma_cus = exponential?f_secureSecurity(tic_ma, res_ma, ema(close,len_ma)) : f_secureSecurity(tic_ma, res_ma, sma(close,len_ma))
ma_long = exponential?f_secureSecurity(syminfo.tickerid, res_ma, ema(close,len_ma)) : f_secureSecurity(syminfo.tickerid, res_ma, sma(close,len_ma))
cl1 = f_secureSecurity(syminfo.tickerid, 'M', close)
cl2 = f_secureSecurity(tic_ma, 'M', close)
// Input Backtest Range
showDate = input(defval = false, title = "Show Date Range", type = input.bool)
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 = 1995, title = "From Year", type = input.integer, minval = 1850)
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 = 1850)
// Funcion Example
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"
// Calculation
bullish_cross = ticker?cl2>ma_cus : cl1>ma_long
bearish_cross = ticker?cl2<ma_cus : cl1<ma_long
MAColor = bullish_cross ? color.green : bearish_cross ? color.red : color.orange
// Strategy
strategy.entry("long", strategy.long, when = window() and bullish_cross)
strategy.close("long", when = window() and bearish_cross)
// Output
plot(switch1?ma_long:na,color = MAColor,linewidth=4)
// Alerts
alertcondition(bullish_cross, title='Bullish', message='Bullish')
alertcondition(bearish_cross, title='Bearish', message='Bearish') |
Noro's Trend Ribbon Strategy | https://www.tradingview.com/script/ZsKsLiUU-noro-s-trend-ribbon-strategy/ | ROBO_Trading | https://www.tradingview.com/u/ROBO_Trading/ | 1,903 | 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/
// © noro
//@version=4
strategy(title = "Noro's Trend Ribbon Strategy", shorttitle = "Trend Ribbon str", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.1)
//Settings
needlong = input(true, defval = true, title = "Long")
needshort = input(true, defval = true, title = "Short")
type = input(defval = "SMA", options = ["SMA", "EMA", "VWMA", "RMA"], title = "MA Type")
len = input(20, minval = 5, title = "MA Length (min. 5)")
src1 = input(ohlc4, title = "MA Source")
src2 = input(ohlc4, title = "Signal Source")
showrib = input(true, title = "Show ribbon")
showbg = input(true, title = "Show color")
fromyear = input(1900, defval = 1900, minval = 1900, maxval = 2100, title = "From Year")
toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
frommonth = input(01, defval = 01, 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")
//MA
ma = type == "SMA" ? sma(src1, len) : type == "EMA" ? ema(src1, len) : type == "VWMA" ? vwma(src1, len) : rma(src1, len)
colorma = showrib ? color.black : na
pm = plot(ma, color = colorma, title = "MA")
//Price Channel
h = highest(ma, len)
l = lowest(ma, len)
colorpc = showrib ? color.blue : na
ph = plot(h, color = colorpc, title = "Upper line")
pl = plot(l, color = colorpc, title = "Lower Line")
//Trend
trend = 0
trend := src2 > h[1] ? 1 : src2 < l[1] ? -1 : trend[1]
//BG
colorbg1 = showbg ? color.red : na
colorbg2 = showbg ? color.blue : na
fill(ph, pm, color = colorbg1, transp = 50)
fill(pl, pm, color = colorbg2, transp = 50)
//Trading
truetime = time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)
if trend == 1 and needlong
strategy.entry("Long", strategy.long, when = truetime)
if trend == -1 and needshort
strategy.entry("Short", strategy.short, when = truetime)
if trend == 1 and needlong == false
strategy.close_all()
if trend == -1 and needshort == false
strategy.close_all()
if time > timestamp(toyear, tomonth, today, 23, 59)
strategy.close_all() |
Noro's Channel Close Strategy | https://www.tradingview.com/script/12DtNLFY-noro-s-channel-close-strategy/ | ROBO_Trading | https://www.tradingview.com/u/ROBO_Trading/ | 206 | 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/
// © noro
//@version=4
strategy(title = "noro's Channel Close Strategy", shorttitle = "Channel Close str", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.1)
len = input(10)
h = highest(high, len)
l = lowest(low, len)
plot(h)
plot(l)
if close > h[1]
strategy.entry("Long", strategy.long)
if close < l[1]
strategy.entry("Short", strategy.short) |
Multiple %% profit exits example | https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ | adolgov | https://www.tradingview.com/u/adolgov/ | 531 | 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("Multiple %% profit 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)
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
lossPnt = percentAsPoints(2)
strategy.exit("x1", qty_percent = 25, profit = percentAsPoints(1), loss = lossPnt)
strategy.exit("x2", qty_percent = 25, profit = percentAsPoints(2), loss = lossPnt)
strategy.exit("x3", qty_percent = 25, profit = percentAsPoints(3), loss = lossPnt)
strategy.exit("x4", profit = percentAsPoints(4), loss = lossPnt)
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) |
Double MA Cross | https://www.tradingview.com/script/kIYRF7KS-Double-MA-Cross/ | RafaelPiccolo | https://www.tradingview.com/u/RafaelPiccolo/ | 101 | 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/
// © RafaelPiccolo
//@version=4
strategy("Double MA Cross", overlay=true, initial_capital=1)
type1 = input("EMA", "MA Type 1", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA", "TEMA"])
len1 = input(10, minval=1, title="Length 1")
src1 = input(close, "Source 1", type=input.source)
type2 = input("EMA", "MA Type 2", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA", "TEMA"])
len2 = input(20, minval=2, title="Length 2")
src2 = input(close, "Source 2", type=input.source)
yearStart = input(2000, 'Year start')
monthStart = input(1, 'Month start', minval=1, maxval=12)
tema(src, len)=>
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
return = 3 * (ema1 - ema2) + ema3
getPoint(type, len, src)=>
return = type == "SMA" ? sma(src, len) : type == "EMA" ? ema(src, len) : type == "WMA" ? wma(src, len) : type == "HMA" ? hma(src, len) : type == "VWMA" ? vwma(src, len) : type == "RMA" ? rma(src, len) : tema(src, len)
p1 = getPoint(type1, len1, src1)
p2 = getPoint(type2, len2, src2)
timeFilter = (year >= yearStart) and (year > yearStart or (month >= monthStart))
shortCondition = crossunder(p1, p2) and timeFilter
longCondition = crossover(p1, p2) and timeFilter
if (shortCondition)
strategy.entry("Short", strategy.short)
if (longCondition)
strategy.entry("Long", strategy.long)
plot(p1, "MA 1", p1 < p2 ? color.red : color.green)
plot(p2, "MA 2", color.blue)
|
Price X MA Cross | https://www.tradingview.com/script/UvI5z2DC-Price-X-MA-Cross/ | RafaelPiccolo | https://www.tradingview.com/u/RafaelPiccolo/ | 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/
// © RafaelPiccolo
//@version=4
strategy("Price X MA Cross", overlay=true, initial_capital=1)
typ = input("HMA", "MA Type", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA", "TEMA"])
len = input(100, minval=1, title="Length")
src = input(close, "Source", type=input.source)
tol = input(0, minval=0, title="Tolerance (%)", type=input.float)
startYear = input(2000, 'Start Year')
startMonth = input(1, 'Start Month', minval=1, maxval=12)
tema(src, len)=>
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
return = 3 * (ema1 - ema2) + ema3
getMAPoint(type, len, src)=>
return = type == "SMA" ? sma(src, len) : type == "EMA" ? ema(src, len) : type == "WMA" ? wma(src, len) : type == "HMA" ? hma(src, len) : type == "VWMA" ? vwma(src, len) : type == "RMA" ? rma(src, len) : tema(src, len)
ma = getMAPoint(typ, len, src)
upperTol = ma * (1 + tol/100)
lowerTol = ma * (1 - tol/100)
timeFilter = (year >= startYear) and (year > startYear or (month >= startMonth))
longCondition = crossover(close, upperTol) and timeFilter
shortCondition = crossunder(close, lowerTol) and timeFilter
if (shortCondition)
strategy.entry("Short", strategy.short)
if (longCondition)
strategy.entry("Long", strategy.long)
plot(ma, "Moving Average", close > ma ? color.green : color.red, linewidth = 2)
t1 = plot(tol > 0 ? upperTol : na, transp = 70)
t2 = plot(tol > 0 ? lowerTol : na, transp = 70)
fill(t1, t2, color = tol > 0 ? color.blue : na)
|
Super Z strategy - Thanks to Rafael Zioni | https://www.tradingview.com/script/NIGCEUME-Super-Z-strategy-Thanks-to-Rafael-Zioni/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 1,882 | 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/
//Original script
//https://www.tradingview.com/script/wYknDlLx-super-Z/
//@version=4
strategy("Super Z strategy - Thanks to Rafael Zioni", shorttitle="Super Z strategy",overlay=true,precision=6, initial_capital=10000,calc_on_every_tick=true, pyramiding=10, default_qty_type=strategy.fixed, default_qty_value=10000, currency=currency.EUR)
src5 = input(close)
tf = input(1440)
len5 = timeframe.isintraday and timeframe.multiplier >= 1 ?
tf / timeframe.multiplier * 7 :
timeframe.isintraday and timeframe.multiplier < 60 ?
60 / timeframe.multiplier * 24 * 7 : 7
ma = ema(src5*volume, len5) / ema(volume, len5)
//script taken from https://www.tradingview.com/script/kChCRRZI-Hull-Moving-Average/
src1 = ma
p(src1, len5) =>
n = 0.0
s = 0.0
for i = 0 to len5 - 1
w = (len5 - i) * len5
n := n + w
s := s + src5[i] * w
s / n
hm = 2.0 * p(src1, floor(len5 / 2)) - p(src1, len5)
vhma = p(hm, floor(sqrt(len5)))
lineColor = vhma > vhma[1] ? color.lime : color.red
plot(vhma, title="VHMA", color=lineColor ,linewidth=3)
hColor = true,vis = true
hu = hColor ? (vhma > vhma[2] ? #00ff00 : #ff0000) : #ff9800
vl = vhma[0]
ll = vhma[1]
m1 = plot(vl, color=hu, linewidth=1, transp=60)
m2 = plot(vis ? ll : na, color=hu, linewidth=2, transp=80)
fill(m1, m2, color=hu, transp=70)
//
b = timeframe.isintraday and timeframe.multiplier >= 1 ?
60 / timeframe.multiplier * 7 :
timeframe.isintraday and timeframe.multiplier < 60 ?
60 / timeframe.multiplier * 24 * 7 : 7
//
res5 = input("D", type=input.resolution)
o = security(syminfo.tickerid, res5, open, barmerge.gaps_off, barmerge.lookahead_on)
c = security(syminfo.tickerid, res5, close, barmerge.gaps_off, barmerge.lookahead_on)
hz = security(syminfo.tickerid, res5, high, barmerge.gaps_off, barmerge.lookahead_on)
l = security(syminfo.tickerid, res5, low, barmerge.gaps_off, barmerge.lookahead_on)
col = c >= o ? color.lime : color.red
ppo = plot(b ? o >= c ? hz : l : o, color=col, title="Open", style=plot.style_stepline, transp=100)
ppc = plot(b ? o <= c ? hz : l : c, color=col, title="Close", style=plot.style_stepline, transp=100)
plot(b and hz > c ? hz : na, color=col, title="High", style=plot.style_circles, linewidth=2,transp=60)
plot(b and l < c ? l : na, color=col, title="Low", style=plot.style_circles,linewidth=2, transp=60)
fill(ppo, ppc, col)
//
// INPUTS //
st_mult = input(1, title = 'SuperTrend Multiplier', minval = 0, maxval = 100, step = 0.01)
st_period = input(50, title = 'SuperTrend Period', minval = 1)
// CALCULATIONS //
up_lev =l - (st_mult * atr(st_period))
dn_lev = hz + (st_mult * atr(st_period))
up_trend = 0.0
up_trend := c[1] > up_trend[1] ? max(up_lev, up_trend[1]) : up_lev
down_trend = 0.0
down_trend := c[1] < down_trend[1] ? min(dn_lev, down_trend[1]) : dn_lev
// Calculate trend var
trend = 0
trend := c > down_trend[1] ? 1: c < up_trend[1] ? -1 : nz(trend[1], 1)
// Calculate SuperTrend Line
st_line = trend ==1 ? up_trend : down_trend
// Plotting
//plot(st_line[1], color = trend == 1 ? color.green : color.red , style = plot.style_cross, linewidth = 2, title = "SuperTrend")
buy=crossover( c, st_line)
sell=crossunder(c, st_line)
signal=input(false)
/////////////// Plotting ///////////////
plotshape(signal and buy, style=shape.triangleup, size=size.normal, location=location.belowbar, color=color.lime)
plotshape(signal and sell, style=shape.triangledown, size=size.normal, location=location.abovebar, color=color.red)
if (buy)
strategy.entry("My Long Entry Id", strategy.long)
if (sell)
strategy.entry("My Short Entry Id", strategy.short) |
Noro's TrendMA Strategy | https://www.tradingview.com/script/BRDFaufy-noro-s-trendma-strategy/ | ROBO_Trading | https://www.tradingview.com/u/ROBO_Trading/ | 727 | 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/
// © noro
// 2020
//@version=4
strategy(title = "Noro's TrendMA Strategy", shorttitle = "TrendMA str", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.1)
//Settings
needlong = input(true, title = "Long")
needshort = input(true, title = "Short")
fast = input(10, minval = 1, title = "MA Fast (red)")
slow = input(30, minval = 2, title = "MA Slow (blue)")
type = input(defval = "SMA", options = ["SMA", "EMA"], title = "MA Type")
src = input(ohlc4, title = "MA Source")
showma = input(true, title = "Show MAs")
showbg = input(false, title = "Show Background")
//MAs
fastma = type == "EMA" ? ema(src, fast) : sma(src, fast)
slowma = type == "EMA" ? ema(src, slow) : sma(src, slow)
//Lines
colorfast = showma ? color.red : na
colorslow = showma ? color.blue : na
plot(fastma, color = colorfast, title = "MA Fast")
plot(slowma, color = colorslow, title = "MA Slow")
//Trend
trend1 = fastma > fastma[1] ? 1 : -1
trend2 = slowma > slowma[1] ? 1 : -1
trend = 0
trend := trend1 == 1 and trend2 == 1 ? 1 : trend1 == -1 and trend2 == -1 ? -1 : trend[1]
//Backgrouns
colbg = showbg == false ? na : trend == 1 ? color.lime : trend == -1 ? color.red : na
bgcolor(colbg, transp = 80)
//Trading
if trend == 1
if needlong
strategy.entry("Long", strategy.long)
if needlong == false
strategy.close_all()
if trend == -1
if needshort
strategy.entry("Short", strategy.short)
if needshort == false
strategy.close_all()
|
FTSMA - Trend is your frend | https://www.tradingview.com/script/wffJotUo-FTSMA-Trend-is-your-frend/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 2,454 | 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/
// © 03.freeman
//@version=4
strategy("FTSMA", overlay=true, precision=6, initial_capital=10000,calc_on_every_tick=true, pyramiding=10, default_qty_type=strategy.fixed, default_qty_value=10000, currency=currency.EUR)
src=input(close,"Source")
slowMA=input(200,"Slow MA period")
mediumMA=input(20,"Mid MA period")
fastMA=input(5,"Fast MA period")
plotSMA=input(true,"Use MA")
sin1=input(1,"First sinusoid",minval=1)
sin2=input(2,"Second sinusoid",minval=1)
sin3=input(3,"Third sinusoid",minval=1)
smoothinput = input('EMA', title = "MA Type", options =['EMA', 'SMA', 'ALMA','FRAMA','RMA', 'SWMA', 'VWMA','WMA','LinearRegression'])
linearReg=input(false, "Use linear regression?")
linregLenght=input(13, "Linear regression lenght")
linregOffset=input(0, "Linear regression offset")
//------FRAMA ma---------
ma(src, len) =>
float result = 0
int len1 = len/2
frama_SC=200
frama_FC=1
e = 2.7182818284590452353602874713527
w = log(2/(frama_SC+1)) / log(e) // Natural logarithm (ln(2/(SC+1))) workaround
H1 = highest(high,len1)
L1 = lowest(low,len1)
N1 = (H1-L1)/len1
H2_ = highest(high,len1)
H2 = H2_[len1]
L2_ = lowest(low,len1)
L2 = L2_[len1]
N2 = (H2-L2)/len1
H3 = highest(high,len)
L3 = lowest(low,len)
N3 = (H3-L3)/len
dimen1 = (log(N1+N2)-log(N3))/log(2)
dimen = iff(N1>0 and N2>0 and N3>0,dimen1,nz(dimen1[1]))
alpha1 = exp(w*(dimen-1))
oldalpha = alpha1>1?1:(alpha1<0.01?0.01:alpha1)
oldN = (2-oldalpha)/oldalpha
N = (((frama_SC-frama_FC)*(oldN-1))/(frama_SC-1))+frama_FC
alpha_ = 2/(N+1)
alpha = alpha_<2/(frama_SC+1)?2/(frama_SC+1):(alpha_>1?1:alpha_)
frama = 0.0
frama :=(1-alpha)*nz(frama[1]) + alpha*src
result := frama
result
// ----------MA calculation - ChartArt and modified by 03.freeman-------------
calc_ma(src,l) =>
_ma = smoothinput=='SMA'?sma(src, l):smoothinput=='EMA'?ema(src, l):smoothinput=='WMA'?wma(src, l):smoothinput=='LinearRegression'?linreg(src, l,0):smoothinput=='VWMA'?vwma(src,l):smoothinput=='RMA'?rma(src, l):smoothinput=='ALMA'?alma(src,l,0.85,6):smoothinput=='SWMA'?swma(src):smoothinput=='FRAMA'?ma(sma(src,1),l):na
//----------------------------------------------
//pi = acos(-1)
// Approximation of Pi in _n terms --- thanks to e2e4mfck
f_pi(_n) =>
_a = 1. / (4. * _n + 2)
_b = 1. / (6. * _n + 3)
_pi = 0.
for _i = _n - 1 to 0
_a := 1 / (4. * _i + 2) - _a / 4.
_b := 1 / (6. * _i + 3) - _b / 9.
_pi := (4. * _a) + (4. * _b) - _pi
pi=f_pi(20)
//---Thanks to xyse----https://www.tradingview.com/script/UTPOoabQ-Low-Frequency-Fourier-Transform/
//Declaration of user-defined variables
N = input(defval=64, title="Lookback Period", type=input.integer, minval=2, maxval=600, confirm=false, step=1, options=[2,4,8,16,32,64,128,256,512,1024,2048,4096])
//Real part of the Frequency Domain Representation
ReX(k) =>
sum = 0.0
for i=0 to N-1
sum := sum + src[i]*cos(2*pi*k*i/N)
return = sum
//Imaginary part of the Frequency Domain Representation
ImX(k) =>
sum = 0.0
for i=0 to N-1
sum := sum + src[i]*sin(2*pi*k*i/N)
return = -sum
//Get sinusoidal amplitude from frequency domain
ReX_(k) =>
case = 0.0
if(k!=0 and k!=N/2)
case := 2*ReX(k)/N
if(k==0)
case := ReX(k)/N
if(k==N/2)
case := ReX(k)/N
return = case
//Get sinusoidal amplitude from frequency domain
ImX_(k) =>
return = -2*ImX(k)/N
//Get full Fourier Transform
x(i, N) =>
sum1 = 0.0
sum2 = 0.0
for k=0 to N/2
sum1 := sum1 + ReX_(k)*cos(2*pi*k*i/N)
for k=0 to N/2
sum2 := sum2 + ImX_(k)*sin(2*pi*k*i/N)
return = sum1+sum2
//Get single constituent sinusoid
sx(i, k) =>
sum1 = ReX_(k)*cos(2*pi*k*i/N)
sum2 = ImX_(k)*sin(2*pi*k*i/N)
return = sum1+sum2
//Calculations for strategy
SLOWMA = plotSMA?calc_ma(close+sx(0,sin1),slowMA):close+sx(0,sin1)
MEDMA = plotSMA?calc_ma(close+sx(0,sin2),mediumMA):close+sx(0,sin2)
FASTMA = plotSMA?calc_ma(close+sx(0,sin3),fastMA):close+sx(0,sin3)
SLOWMA := linearReg?linreg(SLOWMA,linregLenght,linregOffset):SLOWMA
MEDMA := linearReg?linreg(MEDMA,linregLenght,linregOffset):MEDMA
FASTMA := linearReg?linreg(FASTMA,linregLenght,linregOffset):FASTMA
//Plot 3 Low-Freq Sinusoids
plot(SLOWMA, color=color.green)
plot(MEDMA, color=color.red)
plot(FASTMA, color=color.blue)
// Strategy: (Thanks to JayRogers)
// === STRATEGY RELATED INPUTS ===
// the risk management inputs
inpTakeProfit = input(defval = 0, title = "Take Profit Points", minval = 0)
inpStopLoss = input(defval = 0, title = "Stop Loss Points", minval = 0)
inpTrailStop = input(defval = 0, title = "Trailing Stop Loss Points", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset Points", minval = 0)
// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
longCondition = FASTMA>MEDMA and close > SLOWMA //crossover(FASTMA, MEDMA) and close > SLOWMA
if (longCondition)
strategy.entry("Long Entry", strategy.long)
shortCondition = FASTMA<MEDMA and close < SLOWMA //crossunder(FASTMA, MEDMA) and close < SLOWMA
if (shortCondition)
strategy.entry("Short Entry", strategy.short)
// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Buy", from_entry = "Long Entry", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Sell", from_entry = "Short Entry", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset) |
Starbux | https://www.tradingview.com/script/A9hMX1ft-Starbux/ | FenixCapital | https://www.tradingview.com/u/FenixCapital/ | 101 | 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/
// © FenixCapital
//@version=4
strategy("Starbux", overlay=true)
//VARIABLES
//Candlestick Variables
body=close-open
range=high-low
middle=(open+close)/2
abody=abs(body)
arange=abs(range)
ratio=abody/range
longcandle= (ratio>0.6)
bodytop=max(open, close)
bodybottom=min(open, close)
shadowtop=high-bodytop
shadowbottom=bodybottom-low
//Closing Variables
macd=macd(close,12,26,9)
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
//plot(macdLine, color=color.blue)
//plot(signalLine, color=color.orange)
//plot(histLine, color=color.red, style=plot.style_histogram)
rsi=rsi(close,14)
sma50= sma(close,50)
sma200= sma(close,200)
exitrsi=rsi > 76
exitmacd=macdLine >0 and signalLine>0
//exitmacd=crossunder(macdLine,signalLine)
stopprice= crossunder(sma50,sma200)
//Candlestick Plotting
blh = (arange*0.33>=abody and close>open and shadowbottom>=abody*2 and shadowtop<=arange*0.1)
plotshape(blh, title= "Bullish Hammer", location=location.belowbar, color=color.lime, style=shape.arrowup, text="Bull\nHammer")
//beh = (arange*0.25>=abody and close<open and shadowtop>=abody*2 and shadowbottom<=arange*0.05)
//plotshape(beh, title= "Bearish Hammer", color=color.orange, style=shape.arrowdown, text="Bear\nHammer")
//bpu = (open>close and close>low and shadowbottom>2*abody)
//plotshape(bpu, title= "Black Paper Umbrella", color=color.red, style=shape.arrowdown, text="Black\nPaper\nUmbrella")
//Trend Signal
bull5= sma50 > sma200
bullmacd=macdLine>=0 and signalLine>=0
bearmacd=macdLine<= 0 and signalLine<=0
//Trading Algorithm
longCondition = blh and bearmacd and volume>volume[1]
if (longCondition)
strategy.order("Buy", true, 1, when=longCondition)
strategy.risk.max_position_size(10)
//strategy.risk.max_drawdown(25,strategy.percent_of_equity)
exitlong = exitmacd
if (exitlong)
strategy.close_all()
|
Gap Filling Strategy | https://www.tradingview.com/script/ghocsiv7-Gap-Filling-Strategy/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 888 | 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/
// © alexgrover
//@version=4
strategy("Gap Filling Strategy",overlay=true)
invert = input(false),clw = input("New Session","Close When:",
options=["New Session","New Gap","Reverse Position"])
//----
ses = change(time("D"))
o = open,c = close
//----
upgap = o > high[1] and min(c,o) > max(c[1],o[1])
dngap = o < low[1] and min(c[1],o[1]) > max(c,o)
//----
val = upgap ? max(c[1],o[1]) : min(c[1],o[1])
lim = valuewhen(ses and (upgap or dngap),val,0)
//----
strategy.close_all(clw == "New Session" ? ses :
clw == "New Gap" ? ses and (upgap or dngap) : false)
if invert
strategy.entry("Buy", strategy.long, when=ses and upgap)
strategy.entry("Sell", strategy.short, when=ses and dngap)
else
strategy.entry("Buy", strategy.long, when=ses and dngap)
strategy.entry("Sell", strategy.short, when=ses and upgap)
if invert
strategy.exit("ExitBuy","Buy",stop=lim)
strategy.exit("ExitSell","Sell",stop=lim)
else
strategy.exit("ExitBuy","Buy",limit=lim)
strategy.exit("ExitSell","Sell",limit=lim)
//----
plot(lim,"Limit/Stop",#ff1100,2) |
Vortex with TSI strategy | https://www.tradingview.com/script/LWVlHnqk-vortex-with-tsi-strategy/ | hydrelev | https://www.tradingview.com/u/hydrelev/ | 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/
// © hydrelev
//@version=4
strategy("Vortex TSI strategy", overlay=false)
///////////////////INDICATOR TSI
long = input(title="Long Length", type=input.integer, defval=25)
short = input(title="Short Length", type=input.integer, defval=13)
signal = input(title="Signal Length", type=input.integer, defval=13)
price = close
double_smooth(src, long, short) =>
fist_smooth = ema(src, long)
ema(fist_smooth, short)
pc = change(price)
double_smoothed_pc = double_smooth(pc, long, short)
double_smoothed_abs_pc = double_smooth(abs(pc), long, short)
tsi_blue = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
tsi_red = ema(tsi_blue, signal)
// plot(tsi_blue, color=#3BB3E4)
// plot(tsi_red, color=#FF006E)
// hline(0, title="Zero")
/////////////////INDICATOR VI
period_ = input(14, title="Period", minval=2)
VMP = sum( abs( high - low[1]), period_ )
VMM = sum( abs( low - high[1]), period_ )
STR = sum( atr(1), period_ )
VIP_blue = VMP / STR
VIM_red = VMM / STR
// plot(VIP_blue, title="VI +", color=#3BB3E4)
// plot(VIM_red, title="VI -", color=#FF006E)
////////////////////STRATEGY
bar=input(1, title="Close after x bar", minval=1, maxval=50)
tsi_long = crossover(tsi_blue, tsi_red)
tsi_short = crossunder(tsi_blue, tsi_red)
vi_long = crossover(VIP_blue, VIM_red)
vi_short = crossunder(VIP_blue, VIM_red)
LongConditionOpen = tsi_long and vi_long ? true : false
LongConditionClose = tsi_long[bar] and vi_long[bar] ? true : false
ShortConditionOpen = tsi_short and vi_short ? true : false
ShortConditionClose = tsi_short[bar] and vi_short[bar] ? true : false
if (LongConditionOpen)
strategy.entry("Long Entry", strategy.long)
if (LongConditionClose)
strategy.close("Long Entry")
if (ShortConditionOpen)
strategy.entry("Short Entry", strategy.short)
if (ShortConditionClose)
strategy.close("Short Entry") |
MA-EMA Crossover LT | https://www.tradingview.com/script/NhCP9iBs-MA-EMA-Crossover-LT/ | Masa_1234 | https://www.tradingview.com/u/Masa_1234/ | 172 | 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/
// This is a Trend Following strategy. Strategy Logic as follows -
// Very simple MA and EMA crossover for Entry (Short or Long)
// Re-entry is on EMA crossover
// Dynamic Zones are used for Stop Loss exit - Dynamic Zone is simply a % of "X" period price range. I use 128 periods for checking range.
// Dynamic Zones script is taken from @allanster https://tradingview.com/script/AoChfBer-How-To-Use-Dynamic-Zones. It's beautiful, neat script.
// I have found that it gives good results (at least on-paper results) on 3 hours timeframe or Daily timeframes.
// I have kept certain default parameters like quantity, trade type long/short, etc since they were convinient for the kind of stocks I was checking.
// One can change many of these parameters to optimise the results.
// There are still some changes to be done to script as follows - //12Apr20
// 1. If on Long Entry, the entry point is below the dynamic zone line, then the stop loss is calculated above the entry point. I will fix it one of these days.
// 2. Additional re-entry logic or take-profit logic in case the stock runs much ahead
// 3. I need to write a Alerts script that would have 10s of stocks built into one script.
// 4. Any other feedback
// Please note I am not a programmer by profession. I am just trying to code a few simple trading ideas for my personal use.
// So, any suggestions / help in changing / optimizing code is most welcome.
//@version=4
strategy("MA-EMA Crossover LT", shorttitle="MA-EMA XO", max_bars_back = 200, overlay=true, precision=9, default_qty_type=strategy.fixed,default_qty_value=100)
//==================== STRATEGY CODE ======================
tradeType = input("BOTH", title="Trade Type ", options=["LONG", "SHORT", "BOTH"])
// === BACKTEST RANGE ===
FromMonth = 01//input(defval=01, title="From Month", minval=1)
FromDay = 01//input(defval=01, title="From Day", minval=1)
FromYear = input(defval=2017, title="From Year", minval=2000)
ToMonth = 12//input(defval=12, title="To Month", minval=1)
ToDay = 31//input(defval=31, title="To Day", minval=1)
ToYear = input(defval=9999, title="To Year", minval=2000)
testPeriod() =>
time > timestamp(FromYear, FromMonth, FromDay, 00, 00) and
time < timestamp(ToYear, ToMonth, ToDay, 23, 59)
stopLossPercent = input(1.00, "Stop Loss Percent")
profitPercent_long = input(3.50, "Profit Percent LONG")
profitPercent_short = input(3.0, "Profit Percent SHORT")
atr_multi_PT = input(1.50, "ATR Multiple for PT")
atr_multi_SL = input(1.50, "ATR Multiple for SL")
//////////////////////////////
isLongOpen = false
isShortOpen = false
//Order open on previous ticker?
isLongOpen := nz(isLongOpen[1])
isShortOpen := nz(isShortOpen[1])
/////////////////////
//Trailing and Profit variables
trigger = 0.0
trigger := na
profitTrigger = 0.0
profitTrigger := na
//obtain values from last ticker
entryPrice = 0.0
entryPrice := nz(entryPrice[1])
stopLossLevel = 0.0
stopLossLevel := nz(stopLossLevel[1])
profitPriceLevel = 0.0
profitPriceLevel := nz(profitPriceLevel[1])
//If in active trade, lets load with current value
if isLongOpen
profitTrigger := profitPriceLevel ? high : na
trigger := stopLossLevel ? ohlc4 : na
trigger
if isShortOpen
profitTrigger := profitPriceLevel ? low : na
trigger := stopLossLevel ? ohlc4 : na
trigger
isStopLoss = isLongOpen ? trigger < stopLossLevel :
isShortOpen ? trigger > stopLossLevel : na
isProfitCatch = isLongOpen ? profitTrigger > profitPriceLevel :
isShortOpen ? profitTrigger < profitPriceLevel : na
//=================== Optional Entry Condition ============
src = close
len = input(defval = 128, title = "DZ Length", type = input.integer, minval = 1)
// use_dz = input(false, title="Use Dynamic Zone")
pcntAbove = input(defval = 40, title = "Hi is Above X% of Sample", type = input.float, minval = 0, maxval = 100, step = 1.0)
pcntBelow = input(defval = 60, title = "Lo is Below X% of Sample", type = input.float, minval = 0, maxval = 100, step = 1.0)
smplAbove = percentile_nearest_rank(src, len, pcntAbove)
smplBelow = percentile_nearest_rank(src, len, 100 - pcntBelow)
above = plot(src > smplAbove ? src : smplAbove, title = "Above Line", color = na)
probOB = plot(smplAbove, title = "OB", color = color.green)
probOS = plot(smplBelow, title = "OS", color = color.red)
below = plot(src < smplBelow ? src : smplBelow, title = "Below Line", color = na)
fill(above, probOB, color = #00FF00, transp = 80)
fill(below, probOS, color = #FF0000, transp = 80)
// long_dz = close > smplAbove
// short_dz = close < smplBelow
//============== Entry Conditions =====================
timeframe = input("5D", title="MA16 Resolution", type=input.resolution)
_ma = sma(hlc3, 16)
ma=security(syminfo.tickerid, timeframe, _ma, barmerge.gaps_off, barmerge.lookahead_on)
_ema=ema(hlc3,7)
ema=security(syminfo.tickerid, timeframe, _ema, barmerge.gaps_off, barmerge.lookahead_on)
long = ma[1] > ema[1] ? crossover(ema, ma) : abs(ma - ema)/ma > 0.025 ? crossover(close, ema) : false
short = ma[1] < ema[1] ? crossunder(ema,ma) : abs(ma - ema)/ma > 0.025 ? crossunder(close, ema): false //:crossunder(close, ema)
longEntry = (tradeType == "LONG" or tradeType == "BOTH") and long
shortEntry = (tradeType == "SHORT" or tradeType == "BOTH") and short
//Upon Entry, do this.
if longEntry or shortEntry
entryPrice := ohlc4
entryPrice
//set price points for new orders
use_dz_sl = input(true, title="Use DZ SL")
if isLongOpen
stopLossLevel := use_dz_sl? max(smplAbove, ma) : ema - 0.25*atr_multi_PT* atr(32) //ma
profitTrail = ma + atr_multi_PT* atr(32)
profitPriceLevel := max( (1 + 0.01 * profitPercent_long) * entryPrice, profitTrail)
profitPriceLevel
if isShortOpen
stopLossLevel := use_dz_sl? min(smplBelow, ma) : ema + 0.25*atr_multi_PT* atr(32) //ma
profitTrail = ma - atr_multi_PT* atr(32)
profitPriceLevel := min( (1 - 0.01 * profitPercent_short) * entryPrice, profitTrail)
profitPriceLevel
shortExit = isShortOpen[1] and (isStopLoss or isProfitCatch or longEntry)
longExit = isLongOpen[1] and (isStopLoss or isProfitCatch or shortEntry)
if (longExit or shortExit) and not(longEntry or shortEntry)
trigger := na
profitTrigger := na
entryPrice := na
stopLossLevel := na
profitPriceLevel := na
// highest := na
// lowest := na
// lowest
if testPeriod() and (tradeType == "LONG" or tradeType == "BOTH")
strategy.entry("long", strategy.long, when=longEntry)
strategy.close("long", when=longExit)
if testPeriod() and (tradeType == "SHORT" or tradeType == "BOTH")
strategy.entry("short", strategy.short, when=shortEntry)
strategy.close("short", when=shortExit)
//If the value changed to invoke a buy, lets set it before we leave
isLongOpen := longEntry ? true : longExit == true ? false : isLongOpen
isShortOpen := shortEntry ? true : shortExit == true ? false : isShortOpen
plotshape(isShortOpen, title="Short Open", color=color.red, style=shape.triangledown, location=location.bottom)
plotshape(isLongOpen, title="Long Open", color=color.green, style=shape.triangleup, location=location.bottom)
plotshape(entryPrice ? entryPrice : na, title="Entry Level", color=color.black, style=shape.cross, location=location.absolute)
plotshape(stopLossLevel ? stopLossLevel : na, title="Stop Loss Level", color=color.orange, style=shape.xcross, location=location.absolute)
plotshape(profitPriceLevel ? profitPriceLevel : na, title="Profit Level", color=color.blue, style=shape.xcross, location=location.absolute)
plotshape(profitTrigger[1] ? isProfitCatch : na, title="Profit Exit Triggered", style=shape.diamond, location=location.abovebar, color=color.blue, size=size.small)
plotshape(trigger[1] ? isStopLoss : na, title="Stop Loss Triggered", style=shape.diamond, location=location.belowbar, color=color.orange, size=size.small)
plot(ma, title="MA 16", color=color.yellow)
plot(ema, title="EMA 7", color=color.blue) |
Chaloke System Strategy | https://www.tradingview.com/script/9ID5apv1/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 371 | 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/
// © ceyhun
//@version=4
strategy("Chaloke System Strategy",overlay=true)
P1=input(9,title="ShortTerm Period")
P2=input(15,title="MidTerm Period")
P3=input(24,title="LongTerm Period")
P4=input(5,title="Invesment Term")
P5=input(5,title="ATR Period")
Barcolor=input(true,title="Barcolor")
Sm=2*P5/10
ATRX=Sm*atr(P4)
S=ema(close,P1)-ATRX
M=ema(close,P2)-ATRX
Lg=ema(close,P3)-ATRX
Sht=iff(close==highest(close,3),S,ema(close[1],P1)-ATRX)
Mid=iff(close==highest(close,3),M,ema(close[1],P2)-ATRX)
Lng=iff(close==highest(close,3),Lg,ema(close[1],P3)-ATRX)
colors=iff(Sht>Mid and close > Sht ,color.green,iff(close < Lng or Sht<Lng,color.red,color.black))
plot(Sht,"Short",color=color.green,linewidth=2)
plot(Mid,"Middle",color=color.black,linewidth=2)
plot(Lng,"Long",color=color.red,linewidth=2)
barcolor(Barcolor ? colors :na)
long = crossover(Sht,Mid) and close > Sht
short = crossunder(Sht,Lng) or close < Lng
if long
strategy.entry("Long", strategy.long, comment="Long")
if short
strategy.entry("Short", strategy.short, comment="Short")
|
GMS: Mean Reversion Strategy | https://www.tradingview.com/script/JinDGmg4-GMS-Mean-Reversion-Strategy/ | GlobalMarketSignals | https://www.tradingview.com/u/GlobalMarketSignals/ | 219 | 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/
// © GlobalMarketSignals
//@version=4
strategy("GMS: Mean Reversion Strategy", overlay=true)
LongShort = input(title="Long Only or Short Only or Both?", type=input.string, defval="Both", options=["Both", "Long Only", "Short Only"])
Lookback = input(title="Length", type=input.integer, defval=10, minval=0)
LThr1 = input(title="Upper threshold", type=input.float, defval=1, minval=0)
LThr = input(title="Lower threshold", type=input.float, defval=-1, maxval=0)
src = input(title="Source", type=input.source, defval=close)
LongShort2 = input(title="Linear Regression Exit or Moving Average Exit?", type=input.string, defval="MA", options=["LR", "MA"])
SMAlenL = input(title="MA/LR Exit Length", type = input.integer ,defval=10)
SMALen2 = input(title="Trend SMA Length", type = input.integer ,defval=200)
AboveBelow = input(title="Above or Below Trend SMA?", type=input.string, defval="Above", options=["Above", "Below", "Don't Include"])
PTbutton = input(title="Profit Target On/Off", type=input.bool, defval=true)
ProfitTarget = input(title="Profit Target %", type=input.float, defval=1, step=0.1, minval=0)
SLbutton = input(title="Stop Loss On/Off", type=input.bool, defval=true)
StopLoss = input(title="Stop Loss %", type=input.float, defval=-1, step=0.1, maxval=0)
x = (src-linreg(src,Lookback,0))/(stdev(src,Lookback))
plot(linreg(src,Lookback,0))
//PROFIT TARGET & STOPLOSS
if PTbutton == true and SLbutton == true
strategy.exit("EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick), loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
if PTbutton == true and SLbutton == false
strategy.exit("PT EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick))
else
if PTbutton == false and SLbutton == true
strategy.exit("SL EXIT", loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
strategy.cancel("PT EXIT")
////////////////////////
//MOVING AVERAGE EXIT//
//////////////////////
if LongShort=="Long Only" and AboveBelow=="Above" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) and close>sma(close,SMALen2))
strategy.close("LONG", when = close>sma(close,SMAlenL))
if LongShort=="Long Only" and AboveBelow=="Below" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) and close<sma(close,SMALen2))
strategy.close("LONG", when = close>sma(close,SMAlenL))
if LongShort=="Long Only" and AboveBelow=="Don't Include" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) )
strategy.close("LONG", when = close>sma(close,SMAlenL))
///////
if LongShort=="Short Only" and AboveBelow=="Above" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) and close>sma(close,SMALen2))
strategy.close("SHORT", when = close<sma(close,SMAlenL))
if LongShort=="Short Only" and AboveBelow=="Below" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) and close<sma(close,SMALen2))
strategy.close("SHORT", when = close<sma(close,SMAlenL))
if LongShort=="Short Only" and AboveBelow=="Don't Include" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) )
strategy.close("SHORT", when = close<sma(close,SMAlenL))
//////
if LongShort=="Both" and AboveBelow=="Above" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) and close>sma(close,SMALen2))
strategy.close("LONG", when = close>sma(close,SMAlenL))
if LongShort=="Both" and AboveBelow=="Below" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) and close<sma(close,SMALen2))
strategy.close("LONG", when = close>sma(close,SMAlenL))
if LongShort=="Both" and AboveBelow=="Don't Include" and LongShort2 =="MA"
strategy.entry("LONG", true, when = x<LThr and close<sma(close,SMAlenL) )
strategy.close("LONG", when = close>sma(close,SMAlenL))
///////
if LongShort=="Both" and AboveBelow=="Above" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) and close>sma(close,SMALen2))
strategy.close("SHORT", when = close<sma(close,SMAlenL))
if LongShort=="Both" and AboveBelow=="Below" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) and close<sma(close,SMALen2))
strategy.close("SHORT", when = close<sma(close,SMAlenL))
if LongShort=="Both" and AboveBelow=="Don't Include" and LongShort2 =="MA"
strategy.entry("SHORT", false, when = x>LThr1 and close>sma(close,SMAlenL) )
strategy.close("SHORT", when = close<sma(close,SMAlenL))
/////////////////
//LIN REG EXIT//
///////////////
if LongShort=="Long Only" and AboveBelow=="Above" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) and close>sma(close,SMALen2))
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
if LongShort=="Long Only" and AboveBelow=="Below" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) and close<sma(close,SMALen2))
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
if LongShort=="Long Only" and AboveBelow=="Don't Include" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) )
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
///////
if LongShort=="Short Only" and AboveBelow=="Above" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) and close>sma(close,SMALen2))
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
if LongShort=="Short Only" and AboveBelow=="Below" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) and close<sma(close,SMALen2))
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
if LongShort=="Short Only" and AboveBelow=="Don't Include" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) )
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
//////
if LongShort=="Both" and AboveBelow=="Above" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) and close>sma(close,SMALen2))
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
if LongShort=="Both" and AboveBelow=="Below" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) and close<sma(close,SMALen2))
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
if LongShort=="Both" and AboveBelow=="Don't Include" and LongShort2 =="LR"
strategy.entry("LONG", true, when = x<LThr and close<linreg(close,SMAlenL,0) )
strategy.close("LONG", when = close>linreg(close,SMAlenL,0))
///////
if LongShort=="Both" and AboveBelow=="Above" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) and close>sma(close,SMALen2))
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
if LongShort=="Both" and AboveBelow=="Below" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) and close<sma(close,SMALen2))
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
if LongShort=="Both" and AboveBelow=="Don't Include" and LongShort2 =="LR"
strategy.entry("SHORT", false, when = x>LThr1 and close>linreg(close,SMAlenL,0) )
strategy.close("SHORT", when = close<linreg(close,SMAlenL,0))
|
Distance Oscillator Strategy- evo | https://www.tradingview.com/script/w391Z7WS-Distance-Oscillator-Strategy-evo/ | EvoCrypto | https://www.tradingview.com/u/EvoCrypto/ | 311 | 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/
// © EvoCrypto
//@version=4
strategy("Distance Oscillator Strategy- evo", shorttitle="Distance Oscillator Strategy")
// INPUTS {
na_1 = input(false, title="────────────{ Oscillator }──────────────")
// Osc_Src = input(close, title="Oscillator Source ")
Example_Length = input(20, title="Example Length", minval=1)
Osc_Src = (highest(Example_Length) + lowest(Example_Length)) / 2
// Strategy can not let you choose a Moving Average to connect with like the study version, so I use the MA above as example
Osc_Format = input("Percent",title="Oscillator Format", options=["Percent", "Currency"])
na_2 = input(false, title="─────────────{ Average }──────────────")
Average_Type = input("Hull", title="Average Type", options=["Hull", "Sma", "Ema", "Wma"])
Length = input(50, title="Average Length", minval=1)
Lagg = input(12, title="Average Lagg", minval=1)
Display_MA = input(true, title="Display Average")
// }
// SETTINGS {
Osc_Sum =
Osc_Format == "Percent" ? (close - Osc_Src) / close * 100 :
Osc_Format == "Currency" ? (close - Osc_Src) : na
Osc_MA = Display_MA == false ? na:
Average_Type == "Hull"? hma(Osc_Sum, Length) :
Average_Type == "Sma" ? sma(Osc_Sum, Length) :
Average_Type == "Ema" ? ema(Osc_Sum, Length) :
Average_Type == "Wma" ? wma(Osc_Sum, Length) : na
Osc_MA_1 = Osc_MA[Lagg]
Cross_Up = crossover( Osc_MA, Osc_MA_1)
Cross_Down = crossunder(Osc_MA, Osc_MA_1)
Osc_Color = Osc_Sum > 0 ? color.new(#bbdefb, 70) : Osc_Sum < 0 ? color.new(#000000, 70) : na
Average_Color = Osc_MA > Osc_MA_1 ? color.new(#311b92, 100) : Osc_MA < Osc_MA_1 ? color.new(#b71c1c, 100) : na
// }
// PLOT {
plot(Osc_Sum, title="Oscillator", color=Osc_Color, style=plot.style_histogram, linewidth=2)
Plot_0 = plot(Osc_MA, title="Osc Average",color=#b71c1c, linewidth=2)
Plot_1 = plot(Osc_MA_1, title="Osc Average",color=#311b92, linewidth=2)
fill(Plot_0, Plot_1, title="Average", color=Average_Color)
plotshape(Cross_Up ? Osc_MA_1 : na, title="Cross Up", color=#bbdefb, location=location.absolute, size=size.tiny, style=shape.circle)
plotshape(Cross_Down ? Osc_MA_1 : na, title="Cross Down", color=#000000, location=location.absolute, size=size.tiny, style=shape.circle)
// }
// STRATEGY {
if (Cross_Up)
strategy.entry("Long", strategy.long)
if (Cross_Down)
strategy.entry("Short", strategy.short)
// } |
volume high standard deviation stystem | https://www.tradingview.com/script/SipKWYGZ/ | dongyun | https://www.tradingview.com/u/dongyun/ | 39 | 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/
// © dongyun
//@version=4
strategy("高交易量交易系统", overlay=true)
rule = input(3,'')
length = input(40,'')
factor = input(1.0,'')
vavg = 0.0
vsd = 0.0
uplimit = 0.0
mavg = 0.0
aror = 0.0
adjvol = 0.0
savevol = 0.0
//Find average volume, replacing bad values
adjvol := volume
if (volume != 0)
savevol := volume
else
savevol := savevol[1]
adjvol := savevol
// Replace high volume days because they distort standard deviation
if (adjvol > vavg + 2 * factor * vsd)
adjvol := savevol
else
adjvol := adjvol[1]
vavg := sma(adjvol,length)
vsd := stdev(adjvol,length)
// Extreme volume limit
uplimit := vavg + 2*factor*vsd
// System rules based on moving average trend
mavg := sma(close,length/2)
// Only enter on new trend signals without high volume
if (rule == 0 or rule == 2)
if (mavg > mavg[1] and strategy.position_size != 1)
strategy.entry("Long", strategy.long)
if (mavg < mavg[1] and strategy.position_size != -1)
strategy.entry("Short", strategy.short)
// Don't reenter after high volume exit
if ( rule == 1 or rule == 3)
if (mavg > mavg[1] and volume < uplimit and strategy.position_size != 1)
strategy.entry("Long", strategy.long)
if (mavg < mavg[1] and volume < uplimit and strategy.position_size != -1)
strategy.entry("Short", strategy.short)
// Exit on profitable high volume
if (rule == 0 or rule == 1)
if (mavg < mavg[1])
strategy.close("Long")
if (mavg > mavg[1])
strategy.close("Short")
if (rule == 2 or rule == 3)
if (mavg < mavg[1] or (close > close[1] and volume > uplimit))
strategy.close("Long")
if (mavg>mavg[1] or (close<close[1] and volume>uplimit))
strategy.close("Short")
|
DEMA Strategy with MACD | https://www.tradingview.com/script/xeqJN1KH-DEMA-Strategy-with-MACD/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 818 | 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/
// © melihtuna
//@version=1
strategy("DEMA Strategy with MACD", overlay=true)
// === Trend Trader Strategy ===
DemaLength = input(21, minval=1)
MacdControl = input(false, title="Control 'MACD Histogram is positive?' when Buy condition")
e1 = ema(close, DemaLength)
e2 = ema(e1, DemaLength)
dema1 = 2 * e1 - e2
pos = close > dema1 ? 1 : 0
barcolor(pos == 0 ? red: pos == 1 ? green : blue )
plot(dema1, color= blue , title="DEMA Strategy with MACD")
// === 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) // 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"
// === MACD ===
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
macdCond= MacdControl ? histLine[0] > 0 ? true : false : true
strategy.entry("BUY", strategy.long, when = window() and pos == 1 and macdCond)
strategy.entry("SELL", strategy.short, when = window() and pos == 0)
|
volume low standard deviation stystem | https://www.tradingview.com/script/eLzxKzjE/ | dongyun | https://www.tradingview.com/u/dongyun/ | 104 | 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/
// © dongyun
//@version=4
strategy("交易量底部标准差系统", overlay=true)
options = input(1,'')
length = input(40,'')
nlow = input(5,'')
factor = input(1.0,'')
vavg = 0.0
vavgn = 0.0
vsd = 0.0
lowlimit = 0.0
uplimit = 0.0
mavg = 0.0
aror = 0.0
adjvol = 0.0
savevol = 0.0
//Find average volume, replacing bad values
adjvol := volume
if (volume != 0)
savevol := volume
else
savevol := savevol[1]
adjvol := savevol
// Replace high volume days because they distort standard deviation
if (adjvol > 2 * factor * nz(vsd[1]))
adjvol := savevol
else
adjvol := adjvol[1]
vavg := sma(adjvol,length)
vsd := stdev(adjvol,length)
vavgn := sma(adjvol,nlow)
// Extreme volume limits
lowlimit := vavg - factor * vsd
uplimit := vavg + 2 * factor * vsd
// System rules based on moving average trend
mavg := sma(close,length/2)
// Only enter on new trend signals
if (options == 2)
if (mavg > mavg[1] and mavg[1] <= mavg[2])
strategy.entry("Long", strategy.long)
if (mavg<mavg[1] and mavg[1]>=mavg[2])
strategy.entry("Short", strategy.short)
else
if (mavg > mavg[1] and vavgn > lowlimit)
strategy.entry("Long", strategy.long)
if (mavg < mavg[1] and vavgn > lowlimit)
strategy.entry("Short", strategy.short)
// Exit on low volume
if (options != 1)
if (mavg<mavg[1] or (strategy.position_size > 0 and vavgn<= lowlimit))
strategy.close("Long")
if (mavg>mavg[1] or (strategy.position_size > 0 and vavgn<= lowlimit))
strategy.close("Short")
else
if (mavg < mavg[1])
strategy.close("Long")
if (mavg > mavg[1])
strategy.close("Short") |
MAMA (Ehlers) MESA Adaptive Moving Average | https://www.tradingview.com/script/qF12FAVo/ | dongyun | https://www.tradingview.com/u/dongyun/ | 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/
// © dongyun
//@version=4
strategy("自适应移动平均的MESA系统", overlay=true)
fastlimit = input(0.5,'')
slowlimit = input(0.05,'')
smooth = 0.0
detrender = 0.0
I1 = 0.0
Q1 = 0.0
JI = 0.0
JQ = 0.0
I2 = 0.0
Q2 = 0.0
Re = 0.0
Im = 0.0
period = 0.0
smoothperiod = 0.0
phase = 0.0
deltaphase = 0.0
alpha = 0.0
MAMA = 0.0
FAMA = 0.0
price = 0.0
price := (high + low)/2
PI = 2 * asin(1)
if (bar_index > 5)
smooth := (4*price + 3*price[1] + 2*price[2] + price[3])/10
detrender := (.0962*smooth + .5769*nz(smooth[2]) - .5769*nz(smooth[4]) - .0962*nz(smooth[6]))*(.075*nz(period[1]) + .54)
// compute InPhase and Quadrature components
Q1 := (.0962*detrender + .5769*nz(detrender[2]) - .5769*nz(detrender[4]) - .0962*nz(detrender[6]))*(.075*nz(period[1]) + .54)
I1 := nz(detrender[3])
// advance the pulse of i1 and q1 by 90 degrees
JI := (.0962*I1 + .5769*nz(I1[2]) - .5769*nz(I1[4]) - .0962*nz(I1[6]))*(.075*nz(period[1]) + .54)
JQ := (.0962*Q1 + .5769*nz(Q1[2]) - .5769*nz(Q1[4]) - .0962*nz(Q1[6]))*(.075*nz(period[1]) + .54)
//phase addition for 3-bar averaging
I2 := I1 - JQ
Q2 := Q1 + JI
//smooth the i and q components before applying
I2 := .2*I2 + .8*nz(I2[1])
Q2 := .2*Q2 + .8*nz(Q2[1])
// hymodyne discriminator
Re := I2*I2[1] + Q2*nz(Q2[1])
Im := I2*Q2[1] + Q2*nz(I2[1])
Re := .2*Re + .8*nz(Re[1])
Im := .2*Im + .8*nz(Im[1])
if (Im != 0 and Re != 0)
period := 2 * PI/atan(Im/Re)
if (period > 1.5 * nz(period[1]))
period := 1.5*nz(period[1])
if (period < .67*nz(period[1]))
period := .67*nz(period[1])
if (period < 6)
period := 6
if (period > 50)
period := 50
period := .2*period + .8*nz(period[1])
smoothperiod := .33*period + .67*nz(smoothperiod[1])
if (I1 != 0)
phase := (180/PI) * atan(Q1/I1)
deltaphase := nz(phase[1]) - phase
if (deltaphase < 1)
deltaphase := 1
alpha := fastlimit/deltaphase
if(alpha < slowlimit)
alpha := slowlimit
MAMA := alpha*price + (1 - alpha)*nz(MAMA[1])
FAMA := .5*alpha*MAMA + (1 - .5*alpha)*nz(FAMA[1])
if (FAMA < MAMA)
strategy.entry("Long", strategy.long)
else
if (FAMA > MAMA)
strategy.entry("Short", strategy.short)
|
Moving Average profit targets with var size | https://www.tradingview.com/script/RtkfiSLH/ | dongyun | https://www.tradingview.com/u/dongyun/ | 44 | 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/
// © dongyun
//@version=4
strategy("利润目标止损的移动平均线", overlay=true)
period = input(80,'')
ptper = input(252,'')
ptfactor = input(12,'')
sizeper = input(20, '')
trend = 0.0
signal = 0
size = 1.0
investment = 100000
atrange = 0.0
ptrange = 0.0
stoph = 0.0
stopl = 0.0
if sizeper != 0
atrange := atr(sizeper)
if atrange == 0 or sizeper == 0
size := 1
else
size := investment/atrange * 0.1
trend := sma(close,period)
if signal != 1 and nz(trend[1]) < nz(trend[2]) and trend > nz(trend[1])
strategy.entry('long',strategy.long, comment='open_long')
signal := 1
else
signal := nz(signal[1])
if signal != -1 and nz(trend[1]) > nz(trend[2]) and trend < nz(trend[1])
strategy.entry('short',strategy.short, comment='open_short')
signal := -1
else
if signal == 0
signal := nz(signal[1])
ptrange := atr(ptper)
if strategy.position_size > 0
strategy.exit("exit_long", "long", qty = strategy.position_size, limit = close + ptfactor*ptrange , comment='trail_long')
else
if strategy.position_size < 0
strategy.exit("exit_short", "short", qty = abs(strategy.position_size), limit = close - ptfactor*ptrange, comment='trail_short')
|
Full Candle Outside BB [Bishnu103] | https://www.tradingview.com/script/cdsymDFl-Full-Candle-Outside-BB-Bishnu103/ | Bishnu103 | https://www.tradingview.com/u/Bishnu103/ | 174 | 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/
// © Bishnu103
//@version=4
strategy(title="Full Candle Outside BB [Bishnu103]",shorttitle="OUTSIDE BB",overlay=true,calc_on_every_tick=true,backtest_fill_limits_assumption=2)
// ***********************************************************************************************************************
// input variables
buy_session = input(title="Trade Session", type=input.session, defval="0915-1430")
exit_inraday = input(title="Exit Intraday?", type=input.bool, defval=true)
entry_distance = input(title="Entry distance from alert", minval=1, maxval=10, defval=3)
show_bb_switch = input(title="Show BB", type=input.bool, defval=true)
risk_limit = input(title="Risk Limit (%)", type=input.float, defval=1.5, minval=0.5, maxval=5.0, step=0.5)
target_option = input(title="Target Options", options=["BB","Profit %"], defval="Profit %")
target_pct = input(title="Profit (%)", type=input.float, defval=3.0, minval=0.5, maxval=10.0, step=0.5)
//
bbLength = input(title="BB Length", minval=1, defval=20)
bbStdDev = input(title="BB StdDev", minval=1, defval=2)
// ***********************************************************************************************************************
// global variables
long_entry = false
short_entry = false
long_exit = false
short_exit = false
// variable values available across candles
var entry_price = 0.0
var sl_price = 0.0
var exit_price_1 = 0.0
var exit_price_2 = 0.0
var candle_count = 0
var qty_hold = 0.0
// ***********************************************************************************************************************
// function to return bollinger band values based on candle poition passed
getBB(pos) => [mBB, uBB, lBB] = bb(close[pos], bbLength, bbStdDev)
// function returns true if current time is within intraday byuing session set in input
BarInSession(sess) => time(timeframe.period, sess) != 0
// ***********************************************************************************************************************
// strategy
//
// get current bb value
[mBB_0,uBB_0,lBB_0] = getBB(0)
// check if full candle outside upper BB
outside_uBB = low > uBB_0 and close <= open and (high > open or low < close)
outside_lBB = high < lBB_0 and close >= open and (high > close or low < open)
// check if SL greater than the risk limit % defined by user
risk_in_limit = outside_uBB ? (high - low) < (low * (risk_limit/100)) : (outside_lBB ? (high - low) < (high * (risk_limit/100)) : false)
// ***********************************************************************************************************************
// entry conditions
long_entry := outside_lBB and risk_in_limit
short_entry := outside_uBB and risk_in_limit
// keep candle count since the alert generated so that order can be cancelled after N number of candle calling it out as invalid alert
candle_count := candle_count + 1
if long_entry or short_entry
candle_count := 0
// ***********************************************************************************************************************
// risk management
//
// decide entry and sl price
if long_entry
entry_price := high
if short_entry
entry_price := low
if long_entry
sl_price := low
if short_entry
sl_price := high
// first exit is when price hits middle BB, gets updated for each candle based on it's middle BB value. second exit at upper/ lower band
exit_price_1 := mBB_0
//
if strategy.position_size > 0
exit_price_2 := uBB_0
if strategy.position_size < 0
exit_price_2 := lBB_0
// ***********************************************************************************************************************
// position sizing
price = if close[0] > 25000
25000
else
price = close[0]
qty = round(25000/price)
// ***********************************************************************************************************************
// entry
if long_entry and strategy.position_size == 0
strategy.order("BUY", strategy.long, qty, stop=entry_price, comment="BUY @ "+ tostring(entry_price))
qty_hold := qty
if short_entry and strategy.position_size == 0
strategy.order("SELL", strategy.short, qty, stop=entry_price, comment="SELL @ "+ tostring(entry_price))
qty_hold := qty
// cancel an order if N number of candles are completed after alert candle
strategy.cancel_all(candle_count > (entry_distance-1))
// if current time is outside byuing session then do not enter intraday trade
strategy.cancel_all(timeframe.isintraday and not BarInSession(buy_session))
// ***********************************************************************************************************************
// exit
if strategy.position_size > 0 and target_option == "BB"
mBB_qty = round(abs(strategy.position_size)/2)
strategy.cancel("EXIT at MBB", true)
strategy.cancel("EXIT at UBB", true)
strategy.cancel("EXIT at SL", true)
if qty_hold == abs(strategy.position_size)
strategy.order("EXIT at MBB", strategy.short, mBB_qty, limit=exit_price_1, comment="EXIT TG1 @ "+ tostring(exit_price_1))
if qty_hold != abs(strategy.position_size)
strategy.order("EXIT at UBB", strategy.short, abs(strategy.position_size), limit=exit_price_2, comment="EXIT TG2 @ "+ tostring(exit_price_2))
strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size), stop=sl_price, comment="EXIT SL @ "+ tostring(sl_price))
if strategy.position_size < 0 and target_option == "BB"
mBB_qty = round(abs(strategy.position_size)/2)
strategy.cancel("EXIT at MBB", true)
strategy.cancel("EXIT at LBB", true)
strategy.cancel("EXIT at SL", true)
if qty_hold == abs(strategy.position_size)
strategy.order("EXIT at MBB", strategy.long, mBB_qty, limit=exit_price_1, comment="EXIT TG1 @ "+ tostring(exit_price_1))
if qty_hold != abs(strategy.position_size)
strategy.order("EXIT at LBB", strategy.long, abs(strategy.position_size), limit=exit_price_2, comment="EXIT TG2 @ "+ tostring(exit_price_1))
strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop=sl_price, comment="EXIT SL @ "+ tostring(sl_price))
if strategy.position_size > 0 and target_option == "Profit %"
exit_price_1 := entry_price + (entry_price * (target_pct/100))
strategy.order("EXIT at Target %", strategy.short, abs(strategy.position_size), limit=exit_price_1, comment="EXIT TG% @ "+ tostring(exit_price_1))
strategy.order("EXIT at SL", strategy.short, abs(strategy.position_size), stop=sl_price, comment="EXIT SL @ "+ tostring(sl_price))
if strategy.position_size < 0 and target_option == "Profit %"
exit_price_1 := entry_price - (entry_price * (target_pct/100))
strategy.order("EXIT at Target %", strategy.long, abs(strategy.position_size), limit=exit_price_1, comment="EXIT TG% @ "+ tostring(exit_price_1))
strategy.order("EXIT at SL", strategy.long, abs(strategy.position_size), stop=sl_price, comment="EXIT SL @ "+ tostring(sl_price))
//plot(qty_hold)
// if intraday trade, close the trade at open of 15:15 candle
exit_intraday_time = timestamp(syminfo.timezone,year,month,dayofmonth,15,14,0)
if timeframe.isintraday and exit_inraday and time_close >= exit_intraday_time
strategy.cancel_all(true)
strategy.close("BUY", when=strategy.position_size > 0, qty=strategy.position_size, comment="EXIT TM @ "+ tostring(close))
strategy.close("SELL", when=strategy.position_size < 0, qty=strategy.position_size, comment="EXIT TM @ "+ tostring(close))
// ***********************************************************************************************************************
// plots
//
// plot BB
[mBBp,uBBp,lBBp] = getBB(0)
p_mBB = plot(show_bb_switch ? mBBp : na, color=color.teal)
p_uBB = plot(show_bb_switch ? uBBp : na, color=color.teal)
p_lBB = plot(show_bb_switch ? lBBp : na, color=color.teal)
fill(p_uBB,p_lBB,color=color.teal,transp=95) |
OBV Trend | https://www.tradingview.com/script/dG2enMXm/ | dongyun | https://www.tradingview.com/u/dongyun/ | 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/
// © dongyun
//@version=4
strategy("均衡交易量指标系统", overlay=true)
//strategy.risk.allow_entry_in(strategy.direction.long)
period = input(60,'')
OBVlocal = 0.0
if close > close[1]
OBVlocal := nz(OBVlocal[1]) + volume
else
if close < close[1]
OBVlocal := nz(OBVlocal[1]) - volume
else
OBVlocal := nz(OBVlocal[1])
MAOBV = sma(OBVlocal,period)
if MAOBV > MAOBV[1]
strategy.entry("Long", strategy.long, when=strategy.position_size <= 0)
else
if MAOBV < MAOBV[1]
strategy.entry("Short", strategy.short, when=strategy.position_size > 0) |
Modified 3MA cross : Modified 3 moving average crossover | https://www.tradingview.com/script/FgksfsTm/ | dongyun | https://www.tradingview.com/u/dongyun/ | 77 | 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/
// © dongyun
//@version=4
strategy("三重交叉修正模式系统", overlay=true)
//strategy.risk.allow_entry_in(strategy.direction.long)
length1 = input(18,'长线')
length2 = input(9,'中线')
length3 = input(4,'短线')
ma1 =0.0
ma2 = 0.0
ma3 = 0.0
ma1 := sma(close,length1)
ma2 := sma(close,length2)
ma3 := sma(close,length3)
plot(ma1)
plot(ma2)
plot(ma3)
if ma2 > ma1 and ma3 > ma3[1]
strategy.entry("Long", strategy.long, when=strategy.position_size <= 0)
if ma2 < ma1 and ma3 < ma3[1]
strategy.entry("Short", strategy.short, when=strategy.position_size > 0) |
Rsi, Ema , Ma and Bollinger Bands for 1 min Btcusdt | https://www.tradingview.com/script/az3Tnoj1-Rsi-Ema-Ma-and-Bollinger-Bands-for-1-min-Btcusdt/ | lepstick | https://www.tradingview.com/u/lepstick/ | 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/
// © lepstick-TC
//@version=4
strategy("1", overlay=true)
length = input(5, minval=1)
src = input(close, title="Source")
mult = input(1.5, minval=0.001, maxval=50)
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
plot(basis, color=color.red)
p1 = plot(upper, color=color.blue)
p2 = plot(lower, color=color.blue)
fill(p1, p2)
rsicok=input(75,minval=0,title="Rsi yüksek")
rsiaz=input(25,maxval=50,title="Rsi düşük")
rsizaman=input(7,minval=0,title="Rsi zaman")
smadeger=input(10,minval=0,title="Ma üst")
smadeger2=input(5,minval=0,title="Ma alt")
emadeger=input(30,minval=0,title="Ema üst")
emadeger2=input(20,minval=0,title="Ema alt")
myrsi=rsi(close,rsizaman)
myrsi2=rsi(close,rsiaz)
myrsi3=rsi(close,rsicok)
myma=sma(close,smadeger)
myma2=sma(close,smadeger2)
myema=ema(close,emadeger)
myema2=ema(close,emadeger2)
mycond =myrsi >rsicok and close> myma and close>myema
mycond2=myrsi<rsiaz and close<myma2 and close<myema2
barcolor(mycond? #2196F3: na)
barcolor(mycond2? #FF9800: na)
plot(myma,title="Ma yüksek",color=color.black,linewidth=0)
plot(myma2,title="Ma düşük",color=color.blue,linewidth=0)
plot(myema,title="Ema yüksek",color=color.yellow,linewidth=0)
plot(myema2,title="Ema düşük",color=color.gray,linewidth=0)
idunno =close< sma(close,smadeger2) and close < sma(close,smadeger) and close<ema(close,emadeger)and close<ema(close,emadeger2)and crossunder(close,lower)and crossunder(myrsi,myrsi2)and crossunder(close,basis)
plotchar(idunno,char="A",color=#808000 ,location=location.belowbar)
idunno2 =close> sma(close,smadeger2) and close> sma(close,smadeger) and close>ema(close,emadeger)and close>ema(close,emadeger2)and crossover(close,upper)and crossover(myrsi,myrsi3)and crossover(close,basis)
plotchar(idunno2,char="S",color=#787B86 ,location=location.abovebar)
strategy.entry("Al",true,when =idunno)
strategy.entry("Sat",false,when = idunno2)
strategy.close("Al",when=ema(close,emadeger)and crossover(open,upper))
strategy.close("Sat",when=sma(close,smadeger2)and crossunder(open,lower))
//strategy.exit("Al çıkış","Al",limit=upper)
//strategy.exit("Sat çıkış","Sat",limit=lower)
//strategy.exit("Al çıkış","Al",trail_points=close*0.1/syminfo.mintick,trail_offset=close*0.005/syminfo.mintick)
//strategy.exit("Sat çıkış","Sat",trail_points=close*0.1/syminfo.mintick,trail_offset=close*0.005/syminfo.mintick)
|
Uhl MA System - Strategy Analysis | https://www.tradingview.com/script/4S9Yz3DB-Uhl-MA-System-Strategy-Analysis/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 903 | 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/
// © alexgrover
//@version=4
strategy("Uhl MA System - Strategy Analysis")
length = input(100),mult = input(1.),src = input(close)
//----
out = 0., cma = 0., cts = 0.
Var = variance(src,length) ,sma = sma(src,length)
secma = pow(nz(sma - cma[1]),2) ,sects = pow(nz(src - cts[1]),2)
ka = Var < secma ? 1 - Var/secma : 0 ,kb = Var < sects ? 1 - Var/sects : 0
cma := ka*sma+(1-ka)*nz(cma[1],src) ,cts := kb*src+(1-kb)*nz(cts[1],src)
//----
if crossover(cts,cma)
strategy.entry("Buy", strategy.long)
if crossunder(cts,cma)
strategy.entry("Sell", strategy.short)
//----
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) |
GMS: RSI & ROC Strategy | https://www.tradingview.com/script/shKG0EbF-GMS-RSI-ROC-Strategy/ | GlobalMarketSignals | https://www.tradingview.com/u/GlobalMarketSignals/ | 216 | 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/
// © GlobalMarketSignals
//@version=4
strategy("GMS: RSI & ROC Strategy", overlay=true)
LongShort = input(title="Long Only or Short Only or Both?", type=input.string, defval="Both", options=["Both", "Long Only", "Short Only"])
RSIroc = input(title="RSI Only, ROC Only, Both?", type=input.string, defval="Both", options=["Both", "RSI Only", "ROC Only"])
RSILength = input(title="RSI Length", type = input.integer ,defval=14)
RSIUpper = input(title="RSI Upper Threshold", type = input.float ,defval=70)
RSILower = input(title="RSI Lower Threshold", type = input.float ,defval=30)
ROCLength = input(title="ROC Length", type = input.integer ,defval=14)
ROCUpper = input(title="ROC Upper Threshold", type = input.float ,defval=1)
ROCLower = input(title="ROC Lower Threshold", type = input.float ,defval=-1)
LongExit = input(title="Long Exit SMA Length", type = input.integer ,defval=5)
ShortExit = input(title="Short Exit SMA Length", type = input.integer ,defval=5)
AboveBelow = input(title="Trend SMA Filter?", type=input.string, defval="Above", options=["Above", "Below", "Don't Include"])
TrendLength = input(title="Trend SMA Length", type = input.integer ,defval=200)
PTbutton = input(title="Profit Target On/Off", type=input.bool, defval=true)
ProfitTarget = input(title="Profit Target %", type=input.float, defval=1, step=0.01, minval=0)
SLbutton = input(title="Stop Loss On/Off", type=input.bool, defval=true)
StopLoss = input(title="Stop Loss %", type=input.float, defval=-1, step=0.01, maxval=0)
//PROFIT TARGET & STOPLOSS
if PTbutton == true and SLbutton == true
strategy.exit("EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick), loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
if PTbutton == true and SLbutton == false
strategy.exit("PT EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick))
else
if PTbutton == false and SLbutton == true
strategy.exit("SL EXIT", loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
strategy.cancel("PT EXIT")
//RSI ONLY
//Long Side
if LongShort =="Long Only" and AboveBelow == "Above" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Below" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "RSI Only"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
//RSI ONLY
//SHORT SIDE
if LongShort =="Short Only" and AboveBelow == "Above" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Below" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "RSI Only"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
///////-----------------/////////////
///////-----------------/////////////
///////-----------------/////////////
//ROC ONLY
//Long Side
if LongShort =="Long Only" and AboveBelow == "Above" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Below" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = roc(close,ROCLength)<ROCLower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "ROC Only"
strategy.entry("LONG", true, when = rsi(close,ROCLength)<ROCLower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
//ROC ONLY
//SHORT SIDE
if LongShort =="Short Only" and AboveBelow == "Above" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Below" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "ROC Only"
strategy.entry("SHORT", false, when = roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
///////-----------------/////////////
///////-----------------/////////////
///////-----------------/////////////
//BOTH
//Long Side
if LongShort =="Long Only" and AboveBelow == "Above" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Below" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close>sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit) and close<sma(close,TrendLength))
strategy.close("LONG", when = close>sma(close,LongExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "Both"
strategy.entry("LONG", true, when = rsi(close,RSILength)<RSILower and roc(close,ROCLength)<ROCLower and close< sma(close,LongExit))
strategy.close("LONG", when = close>sma(close,LongExit))
//BOTH
//SHORT SIDE
if LongShort =="Short Only" and AboveBelow == "Above" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Below" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Above" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close>sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Below" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit) and close<sma(close,TrendLength))
strategy.close("SHORT", when = close<sma(close,ShortExit))
if LongShort =="Both" and AboveBelow == "Don't Include" and RSIroc == "Both"
strategy.entry("SHORT", false, when = rsi(close,RSILength)>RSIUpper and roc(close,ROCLength)>ROCUpper and close> sma(close,ShortExit))
strategy.close("SHORT", when = close<sma(close,ShortExit))
|
Pivot Point Breakout | https://www.tradingview.com/script/PuGrfn7G/ | dongyun | https://www.tradingview.com/u/dongyun/ | 95 | 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/
// © dongyun
//@version=4
strategy("枢轴点突破策略", overlay=true)
//strategy.risk.allow_entry_in(strategy.direction.long)
// btcusdt 最好参数为4
period = input(3,'观察数')
startday = 2*period + 1
lasthigh = 0.0
lastlow = 0.0
if high[period + 1] >= highest(high,startday)
lasthigh := high[period+1]
else
lasthigh := lasthigh[1]
if low[period+1] <= lowest(low,startday)
lastlow := low[period+1]
else
lastlow := lastlow[1]
if high > lasthigh
strategy.entry("Long", strategy.long, when=strategy.position_size <= 0)
else
if low < lastlow
strategy.entry("Short", strategy.short, when=strategy.position_size > 0) |
ChannelsBreakout | https://www.tradingview.com/script/nNt11l6M-ChannelsBreakout/ | Giovanni_Trombetta | https://www.tradingview.com/u/Giovanni_Trombetta/ | 241 | 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/
// © Giovanni_Trombetta
// Strategy to capture price channel breakouts
//@version=4
strategy("ChannelsBreakout", max_bars_back=50, overlay=true)
instrument = input(1, title = "Select 1: Stock/Forex, 2: Future")
money = input(10000, title = "Money for each trade")
backtest_start = input(2000, "Insert first year to backtest")
period = input(50, title = "Period in bars of Donchian Channel")
monetary_stoploss = input(1000, title = "Monetary Stop Loss")
quantity = if instrument != 1
1
else
int(money / close)
upBarrier = highest(high,period)
downBarrier = lowest(low,period)
up = highest(high,period / 4)
down = lowest(low,period / 4)
plot(upBarrier, color=color.green, linewidth=2)
plot(downBarrier, color=color.red, linewidth=2)
plot(up, color=color.lime, linewidth=1)
plot(down, color=color.orange, linewidth=2)
longCondition = crossover(close, upBarrier[1]) and year >= backtest_start
if (longCondition)
strategy.entry("Long", strategy.long, quantity, when = strategy.position_size == 0)
closeCondition = crossunder(close, down[1]) or down < down[1]
if (closeCondition)
strategy.close("Long", comment = "Trailing")
stop_level = strategy.position_avg_price - monetary_stoploss / strategy.position_size
strategy.exit("StopLoss", from_entry = "Long", stop = stop_level)
plot(stop_level, color=color.yellow, linewidth=2)
l = label.new(bar_index, na,
text="PineScript Code", color= color.lime, textcolor = color.white,
style=label.style_labelup, yloc=yloc.belowbar, size=size.normal)
label.delete(l[1]) |
WMA + MACD strategy with trailing stop | https://www.tradingview.com/script/0sS5Urzv/ | heniu_1 | https://www.tradingview.com/u/heniu_1/ | 88 | 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/
// © heniu_1
//@version=4
strategy("WMA + MACD strategy", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=20, commission_type=strategy.commission.percent, commission_value=0.39)
[_, _, histogram] = macd(close, 10, 20, 10)
ma = wma(close, 120)
a = close - (close * 0.03)
b = close[1] - (close[1] * 0.03)
sl = iff(a > b, a, b)
plot(sl, color=color.yellow, style=plot.style_stepline)
longCondition = close > ma and histogram > 0
closeCondition = close <= sl
if (longCondition)
strategy.entry("Kup", strategy.long)
if (closeCondition)
strategy.exit("Sprzedaj", stop = sl) |
Ichimoku Kinko Hyo Cloud + QQE | https://www.tradingview.com/script/0IY0ERtK-Ichimoku-Kinko-Hyo-Cloud-QQE/ | GreggJ | https://www.tradingview.com/u/GreggJ/ | 477 | 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/
// © KryptoNight
//@version=4
// comment/uncomment Study/Strategy to easily switch modes
// study("Ichimoku Kinko Hyo Cloud - no offset - no repaint - RSI filter - alerts", shorttitle="IchiCloud + RSI - alerts", overlay=true)
// ============================================================================== Strategy mode - uncomment to activate
strategy("Ichimoku Kinko Hyo Cloud - no offset - no repaint - RSI filter - strategy", shorttitle="IchiCloud + RSI - Strategy Tester Mode", overlay=true, pyramiding = 0,
currency = currency.EUR, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100,
calc_on_every_tick = true, calc_on_order_fills = true, commission_type = strategy.commission.percent, commission_value = 0.15)
// ==============================================================================
// ------------------------------------------------------------------------------
ichiCloud_offset = input(false, title="Standard Ichimoku Cloud") // with the visual offset
ichiCloud_noOffset = input(true, title="Ichimoku Cloud - no offset - no repaint") // without the visual offset
conversion_prd = input(9, minval=1, title="Conversion Line Period - Tenkan-Sen")
baseline_prd = input(27, minval=1, title="Base Line Period - Kijun-Sen")
baselineA_prd = input(52, minval=1, title="Base Line Period - Kijun-Sen (auxiliary)")
leadingSpan_2prd = input(52, minval=1, title="Lagging Span 2 Periods - Senkou Span B")
displacement = input(26, minval=0, title="Displacement: (-) Chikou Span; (+) Senkou Span A")
extra_bars = input(1, minval=0, title="Displacement: additional bars")
laggingSpan_src = input(close, title="Lagging Span price source - Chikou-Span")
donchian(len) => avg(lowest(len), highest(len))
displ = displacement-extra_bars
// ------------------------------------------------------------------------------
// OFFSET:
conversion = donchian(conversion_prd) // Conversion Line - Tenkan-Sen (9 Period)
baseline = donchian(baseline_prd) // Base Line - Kijun-Sen (26 Period)
baselineA = donchian(baselineA_prd) // Base Line Period - Kijun-Sen (auxiliary)
leadingSpanA = avg(conversion, baseline)
leadingSpanB = donchian(leadingSpan_2prd)
laggingSpan = laggingSpan_src
// Color - bullish, bearish
col_cloud = leadingSpanA>=leadingSpanB ? color.green : color.red
// Cloud Lines
spanA = plot(ichiCloud_offset? leadingSpanA : na, offset=displ, title="Offset: Lead Line 1 - Senkou Span A cloud", color=color.green)
spanB = plot(ichiCloud_offset? leadingSpanB : na, offset=displ, title="Offset: Lead Line 2 - Senkou Span B cloud", color=color.red)
fill(spanA, spanB, color=col_cloud, transp=80, title="Offset: Ichimoku Cloud - Leading Span 1 & 2 based coloring")
// Other Lines
conversion_p = plot(ichiCloud_offset? conversion : na, title="Offset: Conversion Line - Tenkan-Sen", color=#0496ff)
standard_p = plot(ichiCloud_offset? baseline : na, title="Offset: Base Line - Kijun-Sen", color=#991515)
standardA_p = plot(ichiCloud_offset? baselineA : na, title="Offset: Base Line - Kijun-Sen (auxiliary)", color=color.teal)
lagging_Span_p = plot(ichiCloud_offset? laggingSpan : na, offset=-displ, title="Offset: Chikou Span (Lagging Span)", color=#459915)
// ------------------------------------------------------------------------------
// NO OFFSET:
conversion_noOffset = conversion[displ] // Conversion Line - Tenkan-Sen (9 Period)
baseline_noOffset = baseline[displ] // Base Line - Kijun-Sen (26 Period)
baselineA_noOffset = baselineA[displ] // Base Line Period - Kijun-Sen (auxiliary)
leadingSpanA_noOffset = leadingSpanA[displ*2]
leadingSpanB_noOffset = leadingSpanB[displ*2]
laggingSpan_noOffset = laggingSpan[0]
// Color - bullish, bearish
col_cloud_noOffset = leadingSpanA_noOffset>=leadingSpanB_noOffset ? color.green : color.red
// Cloud Lines
spanA_noOffset = plot(ichiCloud_noOffset? leadingSpanA_noOffset : na, title="No offset: Lead Line 1 - Senkou Span A cloud", color=color.green, transp=0)
spanB_noOffset = plot(ichiCloud_noOffset? leadingSpanB_noOffset : na, title="No offset: Lead Line 2 - Senkou Span B cloud", color=color.red, transp=0)
fill(spanA_noOffset, spanB_noOffset, color=col_cloud_noOffset, transp=80, title="No offset: Ichimoku Cloud - Leading Span 1 & 2 based coloring")
// Other Lines
conversion_p_noOffset = plot(ichiCloud_noOffset? conversion_noOffset : na, title="No offset: Conversion Line - Tenkan-Sen", color=#0496ff, transp=0)
baseline_p_noOffset = plot(ichiCloud_noOffset? baseline_noOffset : na, title="No offset: Base Line - Kijun-Sen", color=#991515, transp=0)
baselineA_p_noOffset = plot(ichiCloud_noOffset? baselineA_noOffset : na, title="No offset: Base Line - Kijun-Sen (auxiliary)", color=color.teal, transp=0)
laggingSpan_p_noOffset = plot(ichiCloud_noOffset? laggingSpan_noOffset : na, title="No offset: Chikou Span (Lagging Span)", color=#459915, transp=0)
// ==============================================================================
// Conditions & Alerts (based on the lines without offset)
maxC = max(leadingSpanA_noOffset,leadingSpanB_noOffset)
minC = min(leadingSpanA_noOffset,leadingSpanB_noOffset)
// Trend start signals: crosses between Chikou Span (Lagging Span) and the Cloud (Senkou Span A, Senkou Span B)
uptrend_start = crossover(laggingSpan_noOffset,maxC)
downtrend_start = crossunder(laggingSpan_noOffset,minC)
// Trends
uptrend = laggingSpan_noOffset>maxC // Above Cloud
downtrend = laggingSpan_noOffset<minC // Below Cloud
// No trend: choppy trading - the price is in transition
notrend = maxC>=laggingSpan_noOffset and laggingSpan_noOffset>=minC
// Confirmations
uptrend_confirm = crossover(leadingSpanA_noOffset,leadingSpanB_noOffset)
downtrend_confirm = crossunder(leadingSpanA_noOffset,leadingSpanB_noOffset)
// Signals - crosses between Conversion Line (Tenkan-Sen) and Base Line (Kijun-Sen)
bullish_signal = crossover(conversion_noOffset,baseline_noOffset)
bearish_signal = crossunder(conversion_noOffset,baseline_noOffset)
// Various alerts
alertcondition(uptrend_start, title="Uptrend Started", message="Uptrend Started")
alertcondition(downtrend_start, title="Downtrend Started", message="Downtrend Started")
alertcondition(uptrend_confirm, title="Uptrend Confirmed", message="Uptrend Confirmed")
alertcondition(downtrend_confirm, title="Downtrend Confirmed", message="Downtrend Confirmed")
alertcondition(bullish_signal, title="Buy Signal", message="Buy Signal")
alertcondition(bearish_signal, title="Sell Signal", message="Sell Signal")
rsi_OBlevel = input(50, title="RSI Filter: Overbought level (0 = off)")
rsi_OSlevel = input(100,title="RSI Filter: Oversold level (100 = off)")
rsi_len = input(14,title="RSI Length")
rsi_src = input(close,title="RSI Price source")
rsi = rsi(rsi_src,rsi_len)
// Strategy -------------------------------
long_signal = bullish_signal and uptrend and rsi<=rsi_OSlevel // breakout filtered by the rsi
exit_long = bearish_signal and uptrend
short_signal = bearish_signal and downtrend and rsi>=rsi_OBlevel // breakout filtered by the rsi
exit_short = bullish_signal and downtrend
// Strategy alerts
alertcondition(long_signal, title="Long Signal - Uptrend", message="Long Signal - Uptrend")
alertcondition(exit_long, title="Long Exit Signal - Uptrend", message="Long Exit Signal - Uptrend")
alertcondition(short_signal, title="Long Signal - Downtrend", message="Long Signal - Downtrend")
alertcondition(exit_short, title="Short Exit Signal - Downtrend", message="Short Exit Signal - Downtrend")
// Plot areas for trend and transition
color_trend = uptrend? #00FF00 : downtrend? #FF0000 : notrend? color.new(#FFFFFF, 50) : na
fill(spanA_noOffset, spanB_noOffset, color=color_trend, transp=90, title="No offset: Ichimoku Cloud - Lagging Span & Cloud based coloring")
plotshape(ichiCloud_noOffset?uptrend_start:na, title="No offset: Uptrend Started", color=color.green, style=shape.circle, location=location.belowbar, size=size.tiny, text="Up")
plotshape(ichiCloud_noOffset?downtrend_start:na, title="No offset: Downtrend Started", color=color.red, style=shape.circle,location=location.abovebar, size=size.tiny, text="Down")
plotshape(ichiCloud_noOffset?uptrend_confirm:na, title="No offset: Uptrend Confirmed", color=color.green, style=shape.circle, location=location.belowbar, size=size.small, text="Confirm Up")
plotshape(ichiCloud_noOffset?downtrend_confirm:na, title="No offset: Downtrend Confirmed", color=color.red, style=shape.circle, location=location.abovebar, size=size.small, text="Confirm Down")
plotshape(ichiCloud_noOffset?long_signal:na, title="No offset: Long Signal", color=#00FF00, style=shape.triangleup, location=location.belowbar, size=size.small, text="Long")
plotshape(ichiCloud_noOffset?exit_long:na, title="No offset: Exit Long Signal", color=color.fuchsia, style=shape.triangledown, location=location.abovebar, size=size.small, text="Exit long")
plotshape(ichiCloud_noOffset?short_signal:na, title="No offset: Short Signal", color=#FF0000, style=shape.triangledown, location=location.abovebar, size=size.small, text="Short")
plotshape(ichiCloud_noOffset?exit_short:na, title="No offset: Exit Short Signal", color=color.fuchsia, style=shape.triangleup, location=location.belowbar, size=size.small, text="Exit short")
// ============================================================================== Strategy Component - uncomment to activate
if (long_signal)
strategy.entry("Long",strategy.long)
if (exit_long)
strategy.close("Long")
// if (short_signal)
// strategy.entry("Short",strategy.short)
// if (exit_short)
// strategy.close("Short")
// ==============================================================================
//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © colinmck
RSI_Period = input(10, title='RSI Length')
SF = input(5, title='RSI Smoothing')
QQE = input(2.438, title='Fast QQE Factor')
ThreshHold = input(10, title="Thresh-hold")
src = close
Wilders_Period = RSI_Period * 3 - 1
Rsi = rsi(src, RSI_Period)
RsiMa = ema(Rsi, SF)
AtrRsi = abs(RsiMa[1] - RsiMa)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
dar = ema(MaAtrRsi, Wilders_Period) * QQE
longband = 0.0
shortband = 0.0
trend = 0
DeltaFastAtrRsi = dar
RSIndex = RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
cross_1 = cross(longband[1], RSIndex)
trend := cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Find all the QQE Crosses
QQExlong = 0
QQExlong := nz(QQExlong[1])
QQExshort = 0
QQExshort := nz(QQExshort[1])
QQExlong := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
QQExshort := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0
//Conditions
qqeLong = QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na
qqeShort = QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na
// Plotting
plotshape(qqeLong, title="QQE long", text="Long", textcolor=color.white, style=shape.labelup, location=location.belowbar, color=color.green, transp=0, size=size.tiny)
plotshape(qqeShort, title="QQE short", text="Short", textcolor=color.white, style=shape.labeldown, location=location.abovebar, color=color.red, transp=0, size=size.tiny)
// Alerts
alertcondition(qqeLong, title="Long", message="Long")
alertcondition(qqeShort, title="Short", message="Short")
|
GMS: Moving Average Crossover Strategy | https://www.tradingview.com/script/FERReBsH-GMS-Moving-Average-Crossover-Strategy/ | GlobalMarketSignals | https://www.tradingview.com/u/GlobalMarketSignals/ | 371 | 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/
// © GlobalMarketSignals
//@version=4
strategy("GMS: Moving Average Cross Over", overlay=true)
LongShort = input(title="Long Only or Short Only or Both?", type=input.string, defval="Both", options=["Both", "Long Only", "Short Only"])
MAs1 = input(title="Which Moving Average? (1)", type=input.string, defval="SMA", options=["SMA", "EMA", "WMA", "VWMA"])
MAs2 = input(title="Which Moving Average? (2)", type=input.string, defval="SMA", options=["SMA", "EMA", "WMA", "VWMA"])
MA1 = input(title="Moving Average Length 1", type = input.integer ,defval=10)
MAL2 = input(title="Moving Average Length 2", type = input.integer ,defval=20)
AboveBelow = input(title="Trend SMA Filter?", type=input.string, defval="Above", options=["Above", "Below", "Don't Include"])
TLen = input(title="Trend SMA Length", type = input.integer ,defval=200)
PTbutton = input(title="Profit Target On/Off", type=input.bool, defval=true)
ProfitTarget = input(title="Profit Target %", type=input.float, defval=1, step=0.01, minval=0)
SLbutton = input(title="Stop Loss On/Off", type=input.bool, defval=true)
StopLoss = input(title="Stop Loss %", type=input.float, defval=-1, step=0.01, maxval=0)
//PROFIT TARGET & STOPLOSS
if PTbutton == true and SLbutton == true
strategy.exit("EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick), loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
if PTbutton == true and SLbutton == false
strategy.exit("PT EXIT", profit=((close*(ProfitTarget*0.01))/syminfo.mintick))
else
if PTbutton == false and SLbutton == true
strategy.exit("SL EXIT", loss=((close*(StopLoss*-0.01))/syminfo.mintick))
else
strategy.cancel("PT EXIT")
////////////////////////
///////LONG ONLY////////
////////////////////////
//ABOVE
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),vwma(close,MAL2)))
// BELOW
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("LONG", when = crossunder(wma(close,MA1),vwma(close,MAL2)))
// DONT INCLUDE
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) )
strategy.close("LONG", when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) )
strategy.close("LONG", when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) )
strategy.close("LONG", when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) )
strategy.close("LONG", when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) )
strategy.close("LONG", when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) )
strategy.close("LONG", when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) )
strategy.close("LONG", when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) )
strategy.close("LONG", when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) )
strategy.close("LONG", when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) )
strategy.close("LONG", when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) )
strategy.close("LONG", when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) )
strategy.close("LONG", when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) )
strategy.close("LONG", when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) )
strategy.close("LONG", when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) )
strategy.close("LONG", when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Long Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) )
strategy.close("LONG", when = crossunder(wma(close,MA1),vwma(close,MAL2)))
////////////////////////
///////SHORT ONLY///////
////////////////////////
//ABOVE
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),vwma(close,MAL2)))
// BELOW
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.close("SHORT", when = crossover(wma(close,MA1),vwma(close,MAL2)))
// DONT INCLUDE
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)) )
strategy.close("SHORT", when = crossover(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)) )
strategy.close("SHORT", when = crossover(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)) )
strategy.close("SHORT", when = crossover(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)) )
strategy.close("SHORT", when = crossover(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)) )
strategy.close("SHORT", when = crossover(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)) )
strategy.close("SHORT", when = crossover(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)) )
strategy.close("SHORT", when = crossover(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)) )
strategy.close("SHORT", when = crossover(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)) )
strategy.close("SHORT", when = crossover(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)) )
strategy.close("SHORT", when = crossover(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)) )
strategy.close("SHORT", when = crossover(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)) )
strategy.close("SHORT", when = crossover(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)) )
strategy.close("SHORT", when = crossover(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)) )
strategy.close("SHORT", when = crossover(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)) )
strategy.close("SHORT", when = crossover(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Short Only" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2)) )
strategy.close("SHORT", when = crossover(wma(close,MA1),vwma(close,MAL2)))
////////////////////////
/////// BOTH ///////////
////////////////////////
//ABOVE
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Above" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) and close>sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2)))
// BELOW
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Below" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) and close<sma(close,TLen))
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2)))
// DONT INCLUDE
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),sma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),ema(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),vwma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "SMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(sma(close,MA1),wma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(sma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),sma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),ema(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),vwma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "EMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(ema(close,MA1),wma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(ema(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),vwma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),vwma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),sma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),ema(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "VWMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(vwma(close,MA1),wma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(vwma(close,MA1),wma(close,MAL2)))
///--///
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "WMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),wma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),wma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "SMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),sma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),sma(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "EMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),ema(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),ema(close,MAL2)))
if LongShort =="Both" and AboveBelow == "Don't Include" and MAs1 == "WMA" and MAs2 == "VWMA"
strategy.entry("LONG", true, when = crossover(wma(close,MA1),vwma(close,MAL2)) )
strategy.entry("SHORT", false, when = crossunder(wma(close,MA1),vwma(close,MAL2))) |
Patient Trendfollower (7)(alpha) Backtesting Algorithm | https://www.tradingview.com/script/8Pm6VUL5-Patient-Trendfollower-7-alpha-Backtesting-Algorithm/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 429 | 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/
// © greenmask9
//@version=4
strategy("Patient Trendfollower (7) Strategy", overlay=true)
// 21 EMA
emalength = input(21, title="Short EMA")
emashort = ema(close, emalength)
plot(emashort, color = color.purple, linewidth=1)
// 55 EMA
emalength2 = input(55, title="Long EMA")
ema = ema(close, emalength2)
plot(ema, color = color.green, linewidth=1)
//CCI calculation and inputs
lengthcci = input(20, minval=1, title="Overbought/sold detector period")
src = input(close, title="Overbought/sold detector source")
ma = sma(src, lengthcci)
ccivalue = (src - ma) / (0.015 * dev(src, lengthcci))
//CCI plotting
ccioverbought = input(defval=100, title="Overbought level 1")
ccioverbought2 = input(defval=140, title="Overbought level 2")
ccioverbought3 = input(defval=180, title="Overbought level 3")
ccioversold = input(defval=-100, title="Oversold level 1")
ccioversold2 = input(defval=-140, title="Oversold level 2")
ccioversold3 = input(defval=-180, title="Oversold level 3")
cciOB = (ccivalue >= ccioverbought and ccivalue < ccioverbought2)
plotshape(cciOB, title= "Overbought", location=location.abovebar, color=color.lime, transp=0, style=shape.circle)
cciOS = (ccivalue <= ccioversold and ccivalue > ccioversold2)
plotshape(cciOS, title= "Oversold", location=location.belowbar, color=color.lime, transp=0, style=shape.circle)
cciOB2 = (ccivalue >= ccioverbought2 and ccivalue < ccioverbought3)
plotshape(cciOB2, title= "Overbought", location=location.abovebar, color=color.red, transp=0, style=shape.circle)
cciOS2 = (ccivalue <= ccioversold and ccivalue > ccioversold3)
plotshape(cciOS2, title= "Oversold", location=location.belowbar, color=color.red, transp=0, style=shape.circle)
cciOB3 = (ccivalue >= ccioverbought3)
plotshape(cciOB3, title= "Overbought", location=location.abovebar, color=color.black, transp=0, style=shape.circle)
cciOS3 = (ccivalue <= ccioversold3)
plotshape(cciOS3, title= "Oversold", location=location.belowbar, color=color.black, transp=0, style=shape.circle)
//Supertrend
length = input(title="ATR Period", type=input.integer, defval=55)
mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=5.0)
wicks = input(title="Take Wicks into Account ?", type=input.bool, defval=true)
illuminate = input(title="Illuminate Trend", type=input.bool, defval=true)
atr = mult * atr(length)
longStop = hl2 - atr
longStopPrev = nz(longStop[1], longStop)
longStop := (wicks ? low[1] : close[1]) > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = hl2 + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := (wicks ? high[1] : close[1]) < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and (wicks ? high : close) > shortStopPrev ? 1 : dir == 1 and (wicks ? low : close) < longStopPrev ? -1 : dir
longColor = color.new(color.green, 90)
shortColor = color.new(color.red, 90)
noneColor = color.new(color.white, 100)
longStopPlot = plot(dir == 1 ? longStop : na, title="Long Stop", style=plot.style_linebr, linewidth=2, color=longColor)
shortStopPlot = plot(dir == 1 ? na : shortStop, title="Short Stop", style=plot.style_linebr, linewidth=2, color=shortColor)
midPricePlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = illuminate ? (dir == 1 ? longColor : noneColor) : noneColor
shortFillColor = illuminate ? (dir == -1 ? shortColor : noneColor) : noneColor
fill(midPricePlot, longStopPlot, title="Long State Filling", color=longFillColor)
fill(midPricePlot, shortStopPlot, title="Short State Filling", color=shortFillColor)
//entries
uptrend = emashort>ema and dir == 1
upsignal = ccivalue<=ccioversold and ccivalue>ccioversold2
upsignal2 = ccivalue<=ccioversold2 and ccivalue>ccioversold3
upsignal3 = ccivalue<=ccioversold3
downtrend = emashort<ema and dir == -1
downsignal = ccivalue>=ccioverbought and ccivalue<ccioverbought2
downsignal2 = ccivalue>=ccioverbought2 and ccivalue<ccioverbought3
downsignal3 = ccivalue>=ccioverbought3
//adapts to the current bar, I need to save the bars number when the condition for buy was true, static number is spread
spread = input (0.00020, title="Spread")
upstoploss = longStop - spread
downstoploss = shortStop + spread
ordersize=floor(strategy.initial_capital/close)
testlong = input(title="Test longs", type=input.bool, defval=true)
testshort = input(title="Test shorts", type=input.bool, defval=true)
//new
degree = input(title="Test level 1 overbought/sold levels", type=input.bool, defval=true)
degree2 = input(title="Test level 2 overbought/sold levels", type=input.bool, defval=false)
degree3 = input(title="Test level 3 overbought/sold levels", type=input.bool, defval=false)
statictarget = input(title="Use static target", type=input.bool, defval=true)
statictargetvalue = input(title="Static target in pips", type=input.integer, defval=400)
//timetrade = input(title="Open trades only withing specified time", type=input.bool, defval=true)
//timtrade = input()
//přidat možnost TP podle ATR a sl podle ATR
buy1 = uptrend and upsignal and strategy.opentrades==0 and testlong and degree
x1 = barssince (buy1)
if (buy1)
//bodlo by zakázat atrtarget v tomto případě
if (statictarget)
strategy.entry("Long1", strategy.long, ordersize)
strategy.exit( "Exitlong", from_entry="Long1" , profit=statictargetvalue,stop=upstoploss[x1])
buy2 = uptrend and upsignal2 and strategy.opentrades==0 and testlong and degree2
x2 = barssince (buy2)
if (buy2)
//bodlo by zakázat atrtarget v tomto případě
if (statictarget)
strategy.entry("Long2", strategy.long, ordersize)
strategy.exit( "Exitlong", from_entry="Long2" , profit=statictargetvalue,stop=upstoploss[x2])
buy3 = uptrend and upsignal3 and strategy.opentrades==0 and testlong and degree3
x3 = barssince (buy3)
if (buy3)
//bodlo by zakázat atrtarget v tomto případě
if (statictarget)
strategy.entry("Long3", strategy.long, ordersize)
strategy.exit( "Exitlong", from_entry="Long3" , profit=statictargetvalue,stop=upstoploss[x3])
sell1 = downtrend and downsignal and strategy.opentrades==0 and testshort and degree
y1 = barssince (sell1)
if (sell1)
if (statictarget)
strategy.entry("Sell1", strategy.short, ordersize)
strategy.exit( "Exitshort", from_entry="Sell1" , profit=statictargetvalue,stop=downstoploss[y1])
sell2 = downtrend and downsignal2 and strategy.opentrades==0 and testshort and degree2
y2 = barssince (sell2)
if (sell2)
if (statictarget)
strategy.entry("Sell2", strategy.short, ordersize)
strategy.exit( "Exitshort", from_entry="Sell2" , profit=statictargetvalue,stop=downstoploss[y2])
sell3 = downtrend and downsignal3 and strategy.opentrades==0 and testshort and degree3
y3 = barssince (sell3)
if (sell3)
if (statictarget)
strategy.entry("Sell3", strategy.short, ordersize)
strategy.exit( "Exitshort", from_entry="Sell3" , profit=statictargetvalue,stop=downstoploss[y3])
|
FRAMA - Supertrend strategy | https://www.tradingview.com/script/y81orwSC-FRAMA-Supertrend-strategy/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 1,849 | 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/
// © 03.freeman
//@version=4
strategy("FRAMA strategy", overlay=true,precision=6, initial_capital=1000,calc_on_every_tick=true, pyramiding=0, default_qty_type=strategy.fixed, default_qty_value=10000, currency=currency.EUR)
ma_src = input(title="MA FRAMA Source", type=input.source, defval=close)
ma_frama_len = input(title="MA FRAMA Length", type=input.integer, defval=12)
res = input(title="Resolution", type=input.resolution, defval="1W")
frama_FC = input(defval=1,minval=1, title="* Fractal Adjusted (FRAMA) Only - FC")
frama_SC = input(defval=200,minval=1, title="* Fractal Adjusted (FRAMA) Only - SC")
High = security(syminfo.tickerid, res, high)
Low = security(syminfo.tickerid, res, low)
source = security(syminfo.tickerid, res, ma_src)
enterRule = input(false,title = "Use supertrend for enter")
exitRule = input(false,title = "Use supertrend for exit")
ma(src, len) =>
float result = 0
int len1 = len/2
e = 2.7182818284590452353602874713527
w = log(2/(frama_SC+1)) / log(e) // Natural logarithm (ln(2/(SC+1))) workaround
H1 = highest(High,len1)
L1 = lowest(Low,len1)
N1 = (H1-L1)/len1
H2_ = highest(High,len1)
H2 = H2_[len1]
L2_ = lowest(Low,len1)
L2 = L2_[len1]
N2 = (H2-L2)/len1
H3 = highest(High,len)
L3 = lowest(Low,len)
N3 = (H3-L3)/len
dimen1 = (log(N1+N2)-log(N3))/log(2)
dimen = iff(N1>0 and N2>0 and N3>0,dimen1,nz(dimen1[1]))
alpha1 = exp(w*(dimen-1))
oldalpha = alpha1>1?1:(alpha1<0.01?0.01:alpha1)
oldN = (2-oldalpha)/oldalpha
N = (((frama_SC-frama_FC)*(oldN-1))/(frama_SC-1))+frama_FC
alpha_ = 2/(N+1)
alpha = alpha_<2/(frama_SC+1)?2/(frama_SC+1):(alpha_>1?1:alpha_)
frama = 0.0
frama :=(1-alpha)*nz(frama[1]) + alpha*src
result := frama
result
frama = ma(sma(source,1),ma_frama_len)
signal = ma(frama,ma_frama_len)
plot(frama, color=color.red)
plot(signal, color=color.green)
longCondition = crossover(frama,signal)
shortCondition = crossunder(frama,signal)
Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp = 0.0
TrendDown = 0.0
Trend = 0.0
Tsl = 0.0
TrendUp :=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown :=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl := Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? color.green : color.red
//plot(Tsl, color = linecolor , style = plot.style_line , linewidth = 2,title = "SuperTrend")
plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar,color.green,0,0)
plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, color.red,0,0)
plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=color.lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=color.red, maxheight=60, minheight=50, transp=0)
// Strategy: (Thanks to JayRogers)
// === STRATEGY RELATED INPUTS ===
//tradeInvert = input(defval = false, title = "Invert Trade Direction?")
// the risk management inputs
inpTakeProfit = input(defval = 0, title = "Take Profit Points", minval = 0)
inpStopLoss = input(defval = 0, title = "Stop Loss Points", minval = 0)
inpTrailStop = input(defval = 0, title = "Trailing Stop Loss Points", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset Points", minval = 0)
// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// === STRATEGY - LONG POSITION EXECUTION ===
enterLong() => enterRule? (longCondition and Trend ==1):longCondition // functions can be used to wrap up and work out complex conditions
exitLong() => exitRule and Trend == -1
strategy.entry(id = "Buy", long = true, when = enterLong() ) // use function or simple condition to decide when to get in
strategy.close(id = "Buy", when = exitLong() ) // ...and when to get out
// === STRATEGY - SHORT POSITION EXECUTION ===
enterShort() => enterRule? (shortCondition and Trend ==-1):shortCondition
exitShort() => exitRule and Trend == 1
strategy.entry(id = "Sell", long = false, when = enterShort())
strategy.close(id = "Sell", when = exitShort() )
// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Buy", from_entry = "Buy", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Sell", from_entry = "Sell", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
// === Backtesting Dates === thanks to Trost
testPeriodSwitch = input(false, "Custom Backtesting Dates")
testStartYear = input(2020, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testStartHour = input(0, "Backtest Start Hour")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,testStartHour,0)
testStopYear = input(2020, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(31, "Backtest Stop Day")
testStopHour = input(23, "Backtest Stop Hour")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,testStopHour,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
isPeriod = testPeriodSwitch == true ? testPeriod() : true
// === /END
if not isPeriod
strategy.cancel_all()
strategy.close_all() |
RSI and Smoothed RSI Bull Div Strategy [BigBitsIO] | https://www.tradingview.com/script/NC603cui-RSI-and-Smoothed-RSI-Bull-Div-Strategy-BigBitsIO/ | BigBitsIO | https://www.tradingview.com/u/BigBitsIO/ | 999 | 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/
// © BigBitsIO
//@version=4
strategy(title="RSI and Smoothed RSI Bull Div Strategy [BigBitsIO]", shorttitle="RSI and Smoothed RSI Bull Div Strategy [BigBitsIO]", overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=.1, slippage=0)
TakeProfitPercent = input(3, title="Take Profit %", type=input.float, step=.25)
StopLossPercent = input(1.75, title="Stop Loss %", type=input.float, step=.25)
RSICurve = input(14, title="RSI Lookback Period", type=input.integer, step=1)
BuyBelowTargetPercent = input(0, title="Buy Below Lowest Low In RSI Divergence Lookback Target %", type=input.float, step=.05)
BuyBelowTargetSource = input(close, title="Source of Buy Below Target Price", type=input.source)
SRSICurve = input(10, title="Smoothed RSI Lookback Period", type=input.integer, step=1)
RSICurrentlyBelow = input(30, title="RSI Currently Below", type=input.integer, step=1)
RSIDivergenceLookback = input(25, title="RSI Divergence Lookback Period", type=input.integer, step=1)
RSILowestInDivergenceLookbackCurrentlyBelow = input(25, title="RSI Lowest In Divergence Lookback Currently Below", type=input.integer, step=1)
RSISellAbove = input(65, title="RSI Sell Above", type=input.integer, step=1)
MinimumSRSIDownTrend = input(3, title="Minimum SRSI Downtrend Length", type=input.integer, step=1)
SRSICurrentlyBelow = input(35, title="Smoothed RSI Currently Below", type=input.integer, step=1)
PlotTarget = input(false, title="Plot Target")
RSI = rsi(close, RSICurve)
SRSI = wma(2*wma(RSI, SRSICurve/2)-wma(RSI, SRSICurve), round(sqrt(SRSICurve))) // Hull moving average
SRSITrendDownLength = 0
if (SRSI < SRSI[1])
SRSITrendDownLength := SRSITrendDownLength[1] + 1
// Strategy Specific
ProfitTarget = (close * (TakeProfitPercent / 100)) / syminfo.mintick
LossTarget = (close * (StopLossPercent / 100)) / syminfo.mintick
BuyBelowTarget = BuyBelowTargetSource[(lowestbars(RSI, RSIDivergenceLookback)*-1)] - (BuyBelowTargetSource[(lowestbars(RSI, RSIDivergenceLookback)*-1)] * (BuyBelowTargetPercent / 100))
plot(PlotTarget ? BuyBelowTarget : na)
bool IsABuy = RSI < RSICurrentlyBelow and SRSI < SRSICurrentlyBelow and lowest(SRSI, RSIDivergenceLookback) < RSILowestInDivergenceLookbackCurrentlyBelow and BuyBelowTargetSource < BuyBelowTarget and SRSITrendDownLength >= MinimumSRSIDownTrend and RSI > lowest(RSI, RSIDivergenceLookback)
bool IsASell = RSI > RSISellAbove
if IsABuy
strategy.entry("Positive Trend", true) // buy by market
strategy.exit("Take Profit or Stop Loss", "Positive Trend", profit = ProfitTarget, loss = LossTarget)
if IsASell
strategy.close("Positive Trend")
|
Trend Balance Point System by Welles Wilder | https://www.tradingview.com/script/w12N5Pq3-Trend-Balance-Point-System-by-Welles-Wilder/ | xtradernet | https://www.tradingview.com/u/xtradernet/ | 137 | 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/
// © 2020 X-Trader.net
//@version=3
strategy("Trend Balance Point System by Welles Wilder", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 10000)
MomPer = input(2, "Momentum Period")
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
longTrigger = mom(close, MomPer)[1] > mom(close, MomPer)[2] and mom(close, MomPer)[1] > mom(close, MomPer)[3]
shortTrigger = mom(close, MomPer)[1] < mom(close, MomPer)[2] and mom(close, MomPer)[1] < mom(close, MomPer)[3]
longEntry = (not isLong) and longTrigger
shortEntry = (not isShort) and shortTrigger
longStop = valuewhen(longEntry, ((high[1]+low[1]+close[1])/3 - (high[1]-low[1])), 0)
longTP = valuewhen(longEntry, (2*(high[1]+low[1]+close[1])/3 - low[1]), 0)
shortStop = valuewhen(shortEntry, ((high[1]+low[1]+close[1])/3 + (high[1]-low[1])), 0)
shortTP = valuewhen(shortEntry, (2*(high[1]+low[1]+close[1])/3 - high[1]), 0)
strategy.entry(id = "Long", long = true, when = (longEntry and not isShort))
strategy.exit("Exit Long", "Long", profit = longTP, loss = longStop, when = isLong)
strategy.entry(id = "Short", long = false, when = (shortEntry and not isLong))
strategy.exit("Exit Short", "Short", profit = shortTP, loss = shortStop, when = isShort)
|
Trend Following Breakout | https://www.tradingview.com/script/vOfNuQ8n-Trend-Following-Breakout/ | TrendSurfersSignals | https://www.tradingview.com/u/TrendSurfersSignals/ | 685 | 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/
// © TrendSurfersSignals
//@version=4
strategy("Trend Surfers - Breakout + Alerts", calc_on_every_tick =false, overlay=true, initial_capital=2000,commission_value=.1,default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
/////////////// INPUT ENTRY EXIT
entry= input(100, "ENTRY H/L")
exit= input(50, "EXIT H/L")
/////////////// Backtest Input
FromYear = input(2015, "Backtest Start Year")
FromMonth = input(1, "Backtest Start Month")
FromDay = input(1, "Backtest Start Day")
ToYear = input(2999, "Backtest End Year")
ToMonth = input(1, "Backtest End Month")
ToDay = input(1, "Backtest End Day")
/////////////// Backtest Setting
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() => time >= start and time <= finish ? true : false
/////////////// BUY OPEN PLOT
highestpricelong = highest(high,entry)[1]
plot(highestpricelong, color=color.green, linewidth=2)
/////////////// BUY CLOSE PLOT
lowestpricelong = lowest(high,exit)[1]
plot(lowestpricelong, color=color.green, linewidth=2)
/////////////// SHORT OPEN PLOT
lowestpriceshort = lowest(low,entry)[1]
plot(lowestpriceshort, color=color.red, linewidth=2)
/////////////// SHORT CLOSE PLOT
highestpriceshort = highest(low,exit)[1]
plot(highestpriceshort, color=color.red, linewidth=2)
///////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// CONDITION LONG SHORT //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/////////////// SHORT
entryshort= crossunder(close, lowestpriceshort)
exitshort= crossover(close,highestpriceshort)
/////////////// LONG
exitlong= crossover(close, lowestpricelong)
entrylong= crossover(close,highestpricelong)
///////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// LONG and SHORT ORDER //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////// Alert Message
pair = syminfo.basecurrency + syminfo.currency
entry_long_message = '\nGo Long for ' + pair + 'NOW!' +
'\nClose any short position that are open!' +
'\n\nFind Trend Surfers on Google' +
'\nFor automated premium signals (FREE)'
entry_short_message ='\nGo Short for ' + pair + 'NOW!' +
'\nClose any long position that are open!' +
'\n\nFind Trend Surfers on Google' +
'\nFor automated premium signals (FREE)'
exit_long_message ='\nExit Long for ' + pair + 'NOW!' +
'\n\nFind Trend Surfers on Google' +
'\nFor automated premium signals (FREE)'
exit_short_message ='\nExit Short for ' + pair + 'NOW!' +
'\n\nFind Trend Surfers on Google' +
'\nFor automated premium signals (FREE)'
/////////////// LONG
if (entrylong)
strategy.entry("LongEntry", strategy.long, alert_message = entry_long_message, when = window())
if (exitlong or entryshort)
strategy.close("LongEntry", alert_message = exit_long_message, when=window())
/////////////// SHORT
if (entryshort)
strategy.entry("short", strategy.short, alert_message = entry_short_message, when = window())
if (exitshort or entrylong)
strategy.close("short", alert_message = exit_short_message, when=window())
|
Pair Trade crypto | https://www.tradingview.com/script/I5aIQVbP-Pair-Trade-crypto/ | danilogalisteu | https://www.tradingview.com/u/danilogalisteu/ | 101 | 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/
// © danilogalisteu
//@version=4
strategy("Pair Trade", default_qty_type=strategy.percent_of_equity, default_qty_value=100)
length = input(42, "SMA length", input.integer)
//
x = log(security((input("100*ltcusd")), timeframe.period, close))
y = log(security((input("xbtusd")), timeframe.period, close))
x_ = sma(x, length)
y_ = sma(y, length)
mx = stdev(x, length)
my = stdev(y, length)
c = correlation(x, y, length)
spread_entry = input(0.060, "Entry spread", input.float, step=0.005)
spread_exit = input(0.055, "Exit spread", input.float, step=0.005)
beta = c * (my / mx)
alpha = y_ - beta * x_
spread = y - (alpha + x * beta)
//plot(alpha, color=color.white, transp=0)
//plot(beta, color=color.blue, transp=0)
//plot(c, color=color.blue, transp=0)
plot(spread, color=color.red, transp=0)
strategy.entry("SE", strategy.short, when=spread>spread_entry)
strategy.close("SE", when=spread<spread_exit)
strategy.entry("LE", strategy.long, when=spread<-spread_entry)
strategy.close("LE", when=spread>-spread_exit)
|
Pair Trade | https://www.tradingview.com/script/UqPGgdR7-Pair-Trade/ | danilogalisteu | https://www.tradingview.com/u/danilogalisteu/ | 138 | 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/
// © danilogalisteu
//@version=4
strategy("Pair Trade", default_qty_type=strategy.percent_of_equity, default_qty_value=100)
length = input(37, "SMA length", input.integer)
//
x = log(security((input("BOVA11")), timeframe.period, close))
y = log(security((input("SMAL11")), timeframe.period, close))
x_ = sma(x, length)
y_ = sma(y, length)
mx = stdev(x, length)
my = stdev(y, length)
c = correlation(x, y, length)
spread_entry = input(0.035, "Entry spread", input.float, step=0.005)
spread_exit = input(-0.015, "Exit spread", input.float, step=0.005)
beta = c * (my / mx)
alpha = y_ - beta * x_
spread = y - (alpha + x * beta)
//plot(alpha, color=color.white, transp=0)
//plot(beta, color=color.blue, transp=0)
//plot(c, color=color.blue, transp=0)
plot(spread, color=color.red, transp=0)
strategy.entry("SE", strategy.short, when=spread>spread_entry)
strategy.close("SE", when=spread<spread_exit)
strategy.entry("LE", strategy.long, when=spread<-spread_entry)
strategy.close("LE", when=spread>-spread_exit)
|
Darvas Box Strategy | https://www.tradingview.com/script/JVVHPkZf/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 426 | 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/
// © ceyhun
//@version=4
strategy ("Darvas Box Strategy",overlay=true)
boxp=input(5, "BOX LENGTH")
D_High = security(syminfo.tickerid, 'D', high)
D_Low = security(syminfo.tickerid, 'D', low)
D_Close = security(syminfo.tickerid, 'D', close)
D_Open = security(syminfo.tickerid, 'D', open)
LL = lowest(D_Low,boxp)
k1 = highest(D_High,boxp)
k2 = highest(D_High,boxp-1)
k3 = highest(D_High,boxp-2)
NH = valuewhen(D_High>k1[1],D_High,0)
box1 = k3<k2
TopBox = valuewhen(barssince(D_High>k1[1])==boxp-2 and box1, NH, 0)
BottomBox = valuewhen(barssince(D_High>k1[1])==boxp-2 and box1, LL, 0)
plot(TopBox, linewidth=2, color=#00FF00, title="TopBox")
plot(BottomBox, linewidth=2, color=#FF0000, title="BottomBox")
if crossover(D_Close,TopBox)
strategy.entry("Long", strategy.long, comment="Long")
if crossunder(D_Close,BottomBox)
strategy.entry("Short", strategy.short, comment="Short")
|
EASYMOKU INDICATOR | https://www.tradingview.com/script/w61dAHV7/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 704 | 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
//#####©ÉÉÉɶN###############################################
//####*..´´´´´´,,,»ëN########################################
//###ë..´´´´´´,,,,,,''%©#####################################
//###'´´´´´´,,,,,,,'''''?¶###################################
//##o´´´´´´,,,,,,,''''''''*©#################################
//##'´´´´´,,,,,,,'''''''^^^~±################################
//#±´´´´´,,,,,,,''''''''^í/;~*©####æ%;í»~~~~;==I±N###########
//#»´´´´,,,,,,'''''''''^;////;»¶X/í~~/~~~;=~~~~~~~~*¶########
//#'´´´,,,,,,''''''''^^;////;%I^~/~~/~~~=~~~;=?;~~~~;?ë######
//©´´,,,,,,,''''''''^^~/////X~/~~/~~/~~»í~~=~~~~~~~~~~^;É####
//¶´,,,,,,,''''''''^^^;///;%;~/~~;í~~»~í?~?~~~?I/~~~~?*=íÑ###
//N,,,,,,,'''''''^^^^^///;;o/~~;;~~;£=»í»;IX/=~~~~~~^^^^'*æ##
//#í,,,,,''''''''^^^^^;;;;;o~»~~~~íX//~/»~;í?IíI»~~^/*?'''=N#
//#%,,,'''''''''^^^^^^í;;;;£;~~~//»I»/£X/X/»í*&~~~^^^^'^*~'É#
//#©,,''''''''^^^^^^^^~;;;;&/~/////*X;í;o*í»~=*?*===^'''''*£#
//##&''''''''^^^^^^^^^^~;;;;X=í~~~»;;;/~;í»~»±;^^^^^';=''''É#
//##N^''''''^^^^^^^^^^~~~;;;;/£;~~/»~~»~~///o~~^^^^''''?^',æ#
//###Ñ''''^^^^^^^^^^^~~~~~;;;;;í*X*í»;~~IX?~~^^^^/?'''''=,=##
//####X'''^^^^^^^^^^~~~~~~~~;;íííííí~~í*=~~~~Ií^'''=''''^»©##
//#####£^^^^^^^^^^^~~~~~~~~~~~íííííí~~~~~*~^^^;/''''='',,N###
//######æ~^^^^^^^^~~~~~~~~~~~~~~íííí~~~~~^*^^^'=''''?',,§####
//########&^^^^^^~~~~~~~~~~~~~~~~~~~~~~~^^=^^''=''''?,íN#####
//#########N?^^~~~~~~~~~~~~~~~~~~~~~~~~^^^=^''^?''';í@#######
//###########N*~~~~~~~~~~~~~~~~~~~~~~~^^^*'''^='''/É#########
//##############@;~~~~~~~~~~~~~~~~~~~^^~='''~?'';É###########
//#################É=~~~~~~~~~~~~~~^^^*~'''*~?§##############
//#####################N§£I/~~~~~~»*?~»o§æN##################
//@version=4
strategy("EASYMOKU INDICATOR", overlay = true, initial_capital = 10000, currency = "USD", commission_value = 0.04)
// Initial Ichimoku inputs
Act_IKH = input(true, "ICHIMOKU KYNKO HYO")
Multiplier = input(5.9, "MULTIPLIER", minval = 0.1, type = input.float, step = 0.1)
Settings_input = input("OCCIDENTAL 7-22-44-22", "SETTINGS", options = ["ORIENTAL 9-26-52-26", "OCCIDENTAL 7-22-44-22"])
Settings(_oriental,_occidental) => round(((Settings_input == "ORIENTAL 9-26-52-26") ? _oriental : _occidental)*Multiplier)
tenkanPeriods = Settings(9,7)
kijunPeriods = Settings(26,22)
sekouBPeriods = Settings(52,44)
displacement = Settings(26,22)
// Ichimoku Calculations
donchian(_len) => avg(lowest(_len), highest(_len))
tenkan = donchian(tenkanPeriods)
kijun = donchian(kijunPeriods)
senkouA = avg(tenkan, kijun)
senkouB = donchian(sekouBPeriods)
// KUMO Conditions
var bool KUMO_Cond = na
KUMO_Cond := (close > senkouA[displacement-1] and close > senkouB[displacement-1]) ? 1 : (close < senkouA[displacement-1] and close < senkouB[displacement-1]) ? 0 : na
// CHIKOU Conditions
var bool CHIKOU_Cond = na
CHIKOU_Cond := (close > senkouA[2*displacement] and close > senkouB[2*displacement]) ? 1 : (close < senkouA[2*displacement] and close < senkouB[2*displacement]) ? 0 : na
// TENKAN & KIJUN Crossings Conditions
var bool TENKAN_KIJUN = na
TENKAN_KIJUN := crossover(tenkan,kijun) ? 1 : crossunder(tenkan,kijun) ? -1 : nz(TENKAN_KIJUN[1])
// Plottings
t = plot(Act_IKH ? tenkan : na, color = color.lime, linewidth = 2, title = "TENKAN SEN")
k = plot(Act_IKH ? kijun : na, color = color.red, linewidth = 2, title = "KIJUN SEN")
c = plot(Act_IKH ? close : na, offset = -displacement+1, color = color.aqua, title = "CHIKOU SPAN")
sA = plot(Act_IKH ? senkouA : na, offset = displacement-1, color = color.green, title = "SENKOU A")
sB = plot(Act_IKH ? senkouB : na, offset = displacement-1, color = color.red, title = "SENKOU B")
fill(sA, sB, title = "KUMO", color = senkouA > senkouB ? color.green : color.red)
// Bar colors according to Ichimoku Conditions
barcolor(KUMO_Cond == 1 and CHIKOU_Cond == 1 ? color.lime : KUMO_Cond == 0 and CHIKOU_Cond == 0 ? color.red : color.orange)
// Strategy
if KUMO_Cond == 1 and CHIKOU_Cond == 1
strategy.entry("LONG", strategy.long, when = TENKAN_KIJUN == 1)
strategy.close("LONG", comment = "XLONG", when = TENKAN_KIJUN == -1)
if KUMO_Cond == 0 and CHIKOU_Cond == 0
strategy.entry("SHORT", strategy.short, when = TENKAN_KIJUN == -1)
strategy.close("SHORT", comment = "XSHORT", when = TENKAN_KIJUN == 1) |
Darvas Box Strategy V2 | https://www.tradingview.com/script/Uamkz8Ma/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 1,188 | 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/
// © ceyhun
//@version=4
strategy ("Darvas Box Strategy V2",overlay=true)
boxp=input(5, "BOX LENGTH")
LL = lowest(low,boxp)
k1 = highest(high,boxp)
k2 = highest(high,boxp-1)
k3 = highest(high,boxp-2)
NH = valuewhen(high>k1[1],high,0)
box1 = k3<k2
TopBox = valuewhen(barssince(high>k1[1])==boxp-2 and box1, NH, 0)
BottomBox = valuewhen(barssince(high>k1[1])==boxp-2 and box1, LL, 0)
plot(TopBox, linewidth=2, color=#00FF00, title="TopBox")
plot(BottomBox, linewidth=2, color=#FF0000, title="BottomBox")
if crossover(close,TopBox)
strategy.entry("Long", strategy.long, comment="Long")
if crossunder(close,BottomBox)
strategy.entry("Short", strategy.short, comment="Short")
|
PPO Divergence ST | https://www.tradingview.com/script/KooiAYDB-PPO-Divergence-ST/ | lukzard | https://www.tradingview.com/u/lukzard/ | 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/
// © luciancapdefier
//@version=4
strategy("PPO Divergence ST", overlay=true, initial_capital=30000, calc_on_order_fills=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// time
FromYear = input(2019, "Backtest Start Year")
FromMonth = input(1, "Backtest Start Month")
FromDay = input(1, "Backtest Start Day")
ToYear = input(2999, "Backtest End Year")
ToMonth = input(1, "Backtest End Month")
ToDay = input(1, "Backtest End Day")
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
source = close
topbots = input(true, title="Show PPO high/low triangles?")
long_term_div = input(true, title="Use long term divergences?")
div_lookback_period = input(55, minval=1, title="Lookback Period")
fastLength = input(12, minval=1, title="PPO Fast")
slowLength=input(26, minval=1, title="PPO Slow")
signalLength=input(9,minval=1, title="PPO Signal")
smoother = input(2,minval=1, title="PPO Smooth")
fastMA = ema(source, fastLength)
slowMA = ema(source, slowLength)
macd = fastMA - slowMA
macd2=(macd/slowMA)*100
d = sma(macd2, smoother) // smoothing PPO
bullishPrice = low
priceMins = bullishPrice > bullishPrice[1] and bullishPrice[1] < bullishPrice[2] or low[1] == low[2] and low[1] < low and low[1] < low[3] or low[1] == low[2] and low[1] == low[3] and low[1] < low and low[1] < low[4] or low[1] == low[2] and low[1] == low[3] and low[1] and low[1] == low[4] and low[1] < low and low[1] < low[5] // this line identifies bottoms and plateaus in the price
oscMins= d > d[1] and d[1] < d[2] // this line identifies bottoms in the PPO
BottomPointsInPPO = oscMins
bearishPrice = high
priceMax = bearishPrice < bearishPrice[1] and bearishPrice[1] > bearishPrice[2] or high[1] == high[2] and high[1] > high and high[1] > high[3] or high[1] == high[2] and high[1] == high[3] and high[1] > high and high[1] > high[4] or high[1] == high[2] and high[1] == high[3] and high[1] and high[1] == high[4] and high[1] > high and high[1] > high[5] // this line identifies tops in the price
oscMax = d < d[1] and d[1] > d[2] // this line identifies tops in the PPO
TopPointsInPPO = oscMax
currenttrough4=valuewhen (oscMins, d[1], 0) // identifies the value of PPO at the most recent BOTTOM in the PPO
lasttrough4=valuewhen (oscMins, d[1], 1) // NOT USED identifies the value of PPO at the second most recent BOTTOM in the PPO
currenttrough5=valuewhen (oscMax, d[1], 0) // identifies the value of PPO at the most recent TOP in the PPO
lasttrough5=valuewhen (oscMax, d[1], 1) // NOT USED identifies the value of PPO at the second most recent TOP in the PPO
currenttrough6=valuewhen (priceMins, low[1], 0) // this line identifies the low (price) at the most recent bottom in the Price
lasttrough6=valuewhen (priceMins, low[1], 1) // NOT USED this line identifies the low (price) at the second most recent bottom in the Price
currenttrough7=valuewhen (priceMax, high[1], 0) // this line identifies the high (price) at the most recent top in the Price
lasttrough7=valuewhen (priceMax, high[1], 1) // NOT USED this line identifies the high (price) at the second most recent top in the Price
delayedlow = priceMins and barssince(oscMins) < 3 ? low[1] : na
delayedhigh = priceMax and barssince(oscMax) < 3 ? high[1] : na
// only take tops/bottoms in price when tops/bottoms are less than 5 bars away
filter = barssince(priceMins) < 5 ? lowest(currenttrough6, 4) : na
filter2 = barssince(priceMax) < 5 ? highest(currenttrough7, 4) : na
//delayedbottom/top when oscillator bottom/top is earlier than price bottom/top
y11 = valuewhen(oscMins, delayedlow, 0)
y12 = valuewhen(oscMax, delayedhigh, 0)
// only take tops/bottoms in price when tops/bottoms are less than 5 bars away, since 2nd most recent top/bottom in osc
y2=valuewhen(oscMax, filter2, 1) // identifies the highest high in the tops of price with 5 bar lookback period SINCE the SECOND most recent top in PPO
y6=valuewhen(oscMins, filter, 1) // identifies the lowest low in the bottoms of price with 5 bar lookback period SINCE the SECOND most recent bottom in PPO
long_term_bull_filt = valuewhen(priceMins, lowest(div_lookback_period), 1)
long_term_bear_filt = valuewhen(priceMax, highest(div_lookback_period), 1)
y3=valuewhen(oscMax, currenttrough5, 0) // identifies the value of PPO in the most recent top of PPO
y4=valuewhen(oscMax, currenttrough5, 1) // identifies the value of PPO in the second most recent top of PPO
y7=valuewhen(oscMins, currenttrough4, 0) // identifies the value of PPO in the most recent bottom of PPO
y8=valuewhen(oscMins, currenttrough4, 1) // identifies the value of PPO in the SECOND most recent bottom of PPO
y9=valuewhen(oscMins, currenttrough6, 0)
y10=valuewhen(oscMax, currenttrough7, 0)
bulldiv= BottomPointsInPPO ? d[1] : na // plots dots at bottoms in the PPO
beardiv= TopPointsInPPO ? d[1]: na // plots dots at tops in the PPO
i = currenttrough5 < highest(d, div_lookback_period) // long term bearish oscilator divergence
i2 = y10 > long_term_bear_filt // long term bearish top divergence
i3 = delayedhigh > long_term_bear_filt // long term bearish delayedhigh divergence
i4 = currenttrough4 > lowest(d, div_lookback_period) // long term bullish osc divergence
i5 = y9 < long_term_bull_filt // long term bullish bottom div
i6 = delayedlow < long_term_bull_filt // long term bullish delayedbottom div
//plot(0, color=gray)
//plot(d, color=black)
//plot(bulldiv, title = "Bottoms", color=maroon, style=circles, linewidth=3, offset= -1)
//plot(beardiv, title = "Tops", color=green, style=circles, linewidth=3, offset= -1)
bearishdiv1 = (y10 > y2 and oscMax and y3 < y4) ? true : false
bearishdiv2 = (delayedhigh > y2 and y3 < y4) ? true : false
bearishdiv3 = (long_term_div and oscMax and i and i2) ? true : false
bearishdiv4 = (long_term_div and i and i3) ? true : false
bullishdiv1 = (y9 < y6 and oscMins and y7 > y8) ? true : false
bullishdiv2 = (delayedlow < y6 and y7 > y8) ? true : false
bullishdiv3 = (long_term_div and oscMins and i4 and i5) ? true : false
bullishdiv4 = (long_term_div and i4 and i6) ? true : false
bearish = bearishdiv1 or bearishdiv2 or bearishdiv3 or bearishdiv4
bullish = bullishdiv1 or bullishdiv2 or bullishdiv3 or bullishdiv4
greendot = beardiv != 0 ? true : false
reddot = bulldiv != 0 ? true : false
if (reddot[1] and window() and barssince(reddot[1])==0)
strategy.entry("Buy Id", strategy.long, comment="BUY")
if (greendot[1] and window() and barssince(greendot[1])==0)
strategy.entry("Sell Id", strategy.short, comment="SELL")
alertcondition( bearish, title="Bearish Signal (Orange)", message="Orange & Bearish: Short " )
alertcondition( bullish, title="Bullish Signal (Purple)", message="Purple & Bullish: Long " )
alertcondition( greendot, title="PPO High (Green)", message="Green High Point: Short " )
alertcondition( reddot, title="PPO Low (Red)", message="Red Low Point: Long " )
// plotshape(bearish ? d : na, text='▼\nP', style=shape.labeldown, location=location.abovebar, color=color(orange,0), textcolor=color(white,0), offset=0)
// plotshape(bullish ? d : na, text='P\n▲', style=shape.labelup, location=location.belowbar, color=color(#C752FF,0), textcolor=color(white,0), offset=0)
plotshape(topbots and greendot ? d : na, text='', style=shape.triangledown, location=location.abovebar, color=color.red, offset=0, size=size.tiny)
plotshape(topbots and reddot ? d : na, text='', style=shape.triangleup, location=location.belowbar, color=color.lime, offset=0, size=size.tiny)
//barcolor(bearishdiv1 or bearishdiv2 or bearishdiv3 or bearishdiv4 ? orange : na)
//barcolor(bullishdiv1 or bullishdiv2 or bullishdiv3 or bullishdiv4 ? fuchsia : na)
//barcolor(#dedcdc)
|
[fikira] Fibma/Fibema Strategy | https://www.tradingview.com/script/0I6kCcYq-fikira-Fibma-Fibema-Strategy/ | fikira | https://www.tradingview.com/u/fikira/ | 306 | 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/
// © fikira
//@version=4
strategy("[fikira] Fibma/Fibema Strategy", shorttitle="Fibma/Fibema Strategy", overlay=true)
SMA = input(true, title="SMA ?")
EMA = input(false, title="EMA ?")
MA500 = input(true, title="Barcolor X MA 500 ?")
EMA500 = input(true, title="Barcolor X EMA 500 ?")
str50 = input(true, title="Strategy X MA/EMA 50")
str100 = input(true, title="Strategy X MA/EMA 100")
str236 = input(true, title="Strategy X MA/EMA 236")
str764 = input(true, title="Strategy X MA/EMA 764")
str500 = input(true, title="Strategy X MA/EMA 500")
str1000 = input(true, title="Strategy X MA/EMA 1000")
_24 = input(24, title="MA 24")
_24_ = sma(close, _24)
_38 = input(38, title="MA 38")
_38_ = sma(close, _38)
_50 = input(50, title="MA 50")
_50_ = sma(close, _50)
_62 = input(62, title="MA 62")
_62_ = sma(close, _62)
_76 = input(76, title="MA 76")
_76_ = sma(close, _76)
_100 = input(100, title="MA 100")
_100_ = sma(close, _100)
_236 = input(236, title="MA 236")
_236_ = sma(close, _236)
_382 = input(382, title="MA 382")
_382_ = sma(close, _382)
_500 = input(500, title="MA 500")
_500_ = sma(close, _500)
_618 = input(618, title="MA 618")
_618_ = sma(close, _618)
_764 = input(764, title="MA 764")
_764_ = sma(close, _764)
_1000 = input(1000, title="MA 1000")
_1000_ = sma(close, _1000)
_e24 = input(24, title="EMA 24")
_e24_ = ema(close, _e24)
_e38 = input(38, title="EMA 38")
_e38_ = ema(close, _e38)
_e50 = input(50, title="EMA 50")
_e50_ = ema(close, _e50)
_e62 = input(62, title="EMA 62")
_e62_ = ema(close, _e62)
_e76 = input(76, title="EMA 76")
_e76_ = ema(close, _e76)
_e100 = input(100, title="EMA 100")
_e100_ = ema(close, _e100)
_e236 = input(236, title="EMA 236")
_e236_ = ema(close, _e236)
_e382 = input(382, title="EMA 382")
_e382_ = ema(close, _e382)
_e500 = input(500, title="EMA 500")
_e500_ = ema(close, _e500)
_e618 = input(618, title="EMA 618")
_e618_ = ema(close, _e618)
_e764 = input(764, title="EMA 764")
_e764_ = ema(close, _e764)
_e1000 = input(1000, title="EMA 1000")
_e1000_ = ema(close, _e1000)
p24 = plot(SMA?_24_:na, color=color.blue, linewidth=0, transp=0, title="MA 24")
p38 = plot(SMA?_38_:na, color=color.yellow, linewidth=0, transp=0, title="MA 38")
plot(SMA?_50_:na, color=color.lime, linewidth=0, transp=0, title="MA 50")
p62 = plot(SMA?_62_:na, color=color.orange, linewidth=0, transp=0, title="MA 62")
p76 = plot(SMA?_76_:na, color=#EE1749, linewidth=0, transp=0, title="MA 76")
plot(SMA?_100_:na, color=color.white, linewidth=0, transp=0, title="MA 100")
p236 = plot(SMA?_236_:na, color=color.blue, linewidth=2, transp=0, title="MA 236")
p382 = plot(SMA?_382_:na, color=color.yellow, linewidth=2, transp=30, title="MA 382")
plot(SMA?_500_:na, color=color.lime, linewidth=2, transp=30, title="MA 500")
p618 = plot(SMA?_618_:na, color=color.orange, linewidth=2, transp=30, title="MA 618")
p764 = plot(SMA?_764_:na, color=#EE1749, linewidth=2, transp=30, title="MA 764")
plot(SMA?_1000_:na, color=color.white, linewidth=2, transp=30, title="MA 1000")
pe24 = plot(EMA?_e24_:na, color=color.blue, linewidth=0, transp=0, title="EMA 24")
pe38 = plot(EMA?_e38_:na, color=color.yellow, linewidth=0, transp=0, title="EMA 38")
plot(EMA?_e50_:na, color=color.lime, linewidth=0, transp=0, title="EMA 50")
pe62 = plot(EMA?_e62_:na, color=color.orange, linewidth=0, transp=0, title="EMA 62")
pe76 = plot(EMA?_e76_:na, color=#EE1749, linewidth=0, transp=0, title="EMA 76")
plot(EMA?_e100_:na, color=color.white, linewidth=0, transp=0, title="EMA 100")
pe236 = plot(EMA?_e236_:na, color=color.blue, linewidth=2, transp=0, title="EMA 236")
pe382 = plot(EMA?_e382_:na, color=color.yellow, linewidth=2, transp=30, title="EMA 382")
plot(EMA?_e500_:na, color=color.lime, linewidth=2, transp=0, title="EMA 500")
pe618 = plot(EMA?_e618_:na, color=color.orange, linewidth=2, transp=30, title="EMA 618")
pe764 = plot(EMA?_e764_:na, color=#EE1749, linewidth=2, transp=30, title="EMA 764")
plot(EMA?_e1000_:na, color=color.white, linewidth=2, transp=30, title="EMA 1000")
fill(p38, p62, _62_ > _38_ ? color.red : color.lime, transp=95, title="X MA 38/62")
fill(p382, p618, _618_ > _382_ ? color.red : color.lime, transp=95, title="X MA 382/618")
fill(p24, p76, _76_ > _24_ ? color.red : color.lime, transp=95, title="X MA 24/76")
fill(p236, p764, _764_ > _236_ ? color.red : color.lime, transp=95, title="X MA 236/764")
fill(pe38, pe62, _e62_ > _e38_ ? color.red : color.lime, transp=95, title="X EMA 38/62")
fill(pe382, pe618, _e618_ > _e382_ ? color.red : color.lime, transp=95, title="X EMA 382/618")
fill(pe24, pe76, _e76_ > _e24_ ? color.red : color.lime, transp=95, title="X EMA 24/76")
fill(pe236, pe764, _e764_ > _e236_ ? color.red : color.lime, transp=95, title="X EMA 236/764")
_500bl = SMA and MA500 and close > _500_ ? true : false
_500br = SMA and MA500 and close < _500_ ? true : false
barcolor(
_500bl and not _500bl[1] ? color.yellow :
close > open and _500bl and _500bl[1] ? color.lime :
close < open and _500bl and _500bl[1] ? color.orange :
_500br and not _500br[1] ? color.purple : na, title="close crosses MA 500")
_e500bl = EMA and EMA500 and close > _e500_ ? true : false
_e500br = EMA and EMA500 and close < _e500_ ? true : false
barcolor(
_e500bl and not _e500bl[1] ? color.yellow :
close > open and _e500bl and _e500bl[1] ? color.lime :
close < open and _e500bl and _e500bl[1] ? color.orange :
_e500br and not _e500br[1] ? color.purple : na, title="close crosses EMA 500")
_50bl = SMA and close > _50_ ? true : false
_50br = SMA and close < _50_ ? true : false
_100bl = SMA and close > _100_ ? true : false
_100br = SMA and close < _100_ ? true : false
_236bl = SMA and close > _236_ ? true : false
_236br = SMA and close < _236_ ? true : false
_764bl = SMA and close > _764_ ? true : false
_764br = SMA and close < _764_ ? true : false
_1000bl = SMA and close > _1000_ ? true : false
_1000br = SMA and close < _1000_ ? true : false
_e50bl = EMA and close > _e50_ ? true : false
_e50br = EMA and close < _e50_ ? true : false
_e100bl = EMA and close > _e100_ ? true : false
_e100br = EMA and close < _e100_ ? true : false
_e236bl = EMA and close > _e236_ ? true : false
_e236br = EMA and close < _e236_ ? true : false
_e764bl = EMA and close > _e764_ ? true : false
_e764br = EMA and close < _e764_ ? true : false
_e1000bl = EMA and close > _e1000_ ? true : false
_e1000br = EMA and close < _e1000_ ? true : false
// STRATEGIES
// Profit Factor is simply defined as gross profits divided by gross losses, a Profit Factor above 2 is outstanding,
// a profit Factor of 3 means your net gains were 3 times greater than your net losses, anything above 3 is unheard of :-)
// Please check the profit factor in the D, 3D, W timeframe when for example "Strategy X MA/EMA 50" is enabled :-)
// You also can enable/disable each strategy to see what works best in what timeframe
if (str50 and _50bl and not _50bl[1])
strategy.entry("L50", strategy.long)
if (str50 and _50br and not _50br[1])
strategy.entry("S50", strategy.short)
if (str100 and _100bl and not _100bl[1])
strategy.entry("L100", strategy.long)
if (str100 and _100br and not _100br[1])
strategy.entry("S100", strategy.short)
if (str236 and _236bl and not _236bl[1])
strategy.entry("L236", strategy.long)
if (str236 and _236br and not _236br[1])
strategy.entry("S236", strategy.short)
if (str764 and _764bl and not _764bl[1])
strategy.entry("L764", strategy.long)
if (str764 and _764br and not _764br[1])
strategy.entry("S764", strategy.short)
if (str500 and _500bl and not _500bl[1])
strategy.entry("L500", strategy.long)
if (str500 and _500br and not _500br[1])
strategy.entry("S500", strategy.short)
if (str1000 and _1000bl and not _1000bl[1])
strategy.entry("L1000", strategy.long)
if (str1000 and _1000br and not _1000br[1])
strategy.entry("S1000", strategy.short)
if (str50 and _e50bl and not _e50bl[1])
strategy.entry("LE50", strategy.long)
if (str50 and _e50br and not _e50br[1])
strategy.entry("SE50", strategy.short)
if (str100 and _e100bl and not _e100bl[1])
strategy.entry("LE100", strategy.long)
if (str100 and _e100br and not _e100br[1])
strategy.entry("SE100", strategy.short)
if (str236 and _e236bl and not _e236bl[1])
strategy.entry("LE236", strategy.long)
if (str236 and _e236br and not _e236br[1])
strategy.entry("SE236", strategy.short)
if (str764 and _e764bl and not _e764bl[1])
strategy.entry("LE764", strategy.long)
if (str764 and _e764br and not _e764br[1])
strategy.entry("SE764", strategy.short)
if (str500 and _e500bl and not _e500bl[1])
strategy.entry("LE500", strategy.long)
if (str500 and _e500br and not _e500br[1])
strategy.entry("SE500", strategy.short)
if (str1000 and _e1000bl and not _e1000bl[1])
strategy.entry("LE1000", strategy.long)
if (str1000 and _e1000br and not _e1000br[1])
strategy.entry("SE1000", strategy.short)
|
MACD_RSI strategy | https://www.tradingview.com/script/pjNTFYox/ | fangdingjun | https://www.tradingview.com/u/fangdingjun/ | 692 | 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/
// © fangdingjun
//@version=4
strategy("MACD_RSI strategy", overlay=false)
_ema_len = input(20, title="EMA length")
_macd_fast = input(12, title="MACD Fast")
_macd_slow = input(26, title="MACD Slow")
_macd_signal_len = input(20, title="MACD Signal length")
_rsi_len = input(14, title="RSI length")
_rsi_signal_len = input(20, title="RSI signal length")
_ema = ema(close, _ema_len)
_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(_rsi, color=color.orange)
plot(_rsi_signal, color=color.purple)
longCondition = close > _ema and _macd > _macd_signal and _rsi > _rsi_signal
if (longCondition)
strategy.entry("Buy", strategy.long)
shortCondition = close < _ema and _macd < _macd_signal and _rsi < _rsi_signal
if (shortCondition)
strategy.entry("Sell", strategy.short) |
HA smoothed eliminator v2 | https://www.tradingview.com/script/7BtbYzxO-ha-smoothed-eliminator-v2/ | lsprofit | https://www.tradingview.com/u/lsprofit/ | 65 | 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/
// © russtic
//@version=2
strategy("HA smoothed eliminator v2 ",pyramiding=1, slippage=10, default_qty_type=strategy.percent_of_equity,
commission_type=strategy.commission.percent, commission_value=0.075, overlay=true,
default_qty_value=100, initial_capital=1000)
FromMonth1 = input(defval=1, title="From Month", minval=1, maxval=12)
FromDay1 = input(defval=1, title="From Day", minval=1, maxval=31)
FromYear1 = input(defval=2019, title="From Year", minval=2010)
ToMonth1 = input(defval=12, title="To Month", minval=1, maxval=12)
ToDay1 = input(defval=31, title="To Day", minval=1, maxval=31)
ToYear1 = input(defval=2020, title="To Year", minval=2010)
start1 = timestamp(FromYear1, FromMonth1, FromDay1, 00, 00)
finish1 = timestamp(ToYear1, ToMonth1, ToDay1, 23, 59)
window1() =>
time >= start1 and time <= finish1 ? true : false
t1 = time(period, "0300-1200")
t2 = time(period, "0930-1700")
London = na(t1) ? na : green
NY = na(t2) ? na : red
bgcolor(London, title="London")
bgcolor(NY, title="New York")
///////////////////////////
// HA smoothed
len=(1 )
o=ema(open,len)
c=ema(close,len)
h=ema(high,len)
l=ema(low,len)
haclose = (o+h+l+c)/4
haopen = na(haopen[1]) ? (o + c)/2 : (haopen[1] + haclose[1]) / 2
hahigh = max (h, max(haopen,haclose))
halow = min (l, min(haopen,haclose))
len2=(len)
o2=ema(haopen, len2)
c2=ema(haclose, len2)
h2=ema(hahigh, len2)
l2=ema(halow, len2)
buy= (o2<c2)
closebuy= (o2>c2)
sell= (o2>c2)
closesell= (o2<c2)
//
/// END NEW SCRIPT
//
//
// MERGE SCRIPTS
a1= o2<c2
b1=o2>c2
is_uptrend = (a1)// and (p> 0)
is_downtrend = (b1)// and (p <0)
barcolor(b1 ? red: a1 ? lime : blue)
//end
// =========================start PVT -GIVES EACH BAR A VALUE
facton = (true)//, title="arrow elimination (factor) on ")
Length1 = 2//input(2, title="PVT Length", minval=1)
xPrice = close//input(title="Source", type=source, defval=close)
xsma = wma(xPrice, Length1)
nRes = xPrice - xsma
pos = iff(nRes > 0, 1,
iff(nRes < 0, -1, nz(pos[1], 0)))
forex= input(true, title = 'strength toggle ')
forexyes = (forex == true)? 10000 : (forex == false)? 1: na
plot(nRes*forexyes , color=aqua, title="strength", transp=100)
// ========================= end pvt
//
//============================= start factor // ELIMINATES weak signals
// start trend
//
factor = input(600.00, title = "strength elimination")
factor1 = factor - (factor*2)//input(-100.00, title = "sell strength elimination ")
facton1 = (facton == true) and is_uptrend == 1 and nRes*forexyes>factor ? 1 : (facton == true) and is_downtrend == 1 and nRes*forexyes<factor1 ? -1 : (facton == false)
// ==================== =====
//
//=========================== end factor
nRestrend = (nRes*forexyes)
//=========================== plot arrows
plot1 = iff(is_uptrend[1] == 1, 0 , 1)
plot2 = iff(is_downtrend[1] == 1, 0 , 1)
uparrowcond = is_downtrend ? false : nz(uparrowcond[1], false) == true ? uparrowcond[1] : (facton1 and is_uptrend and nRes*forexyes>factor)
downarrowcond = is_uptrend ? false : nz(downarrowcond[1], false) == true ? downarrowcond[1] : (facton1 and is_downtrend and nRes*forexyes<factor1)
//prevarrowstate = uparrowcond ? 1 : downarrowcond ? -1 : nz(prevarrowstate[1], 0)
candledir = (open < close)? 1: (open>close)? -1 : na // ONLY OPENS ON SAME BAR DIRECTION AS SIGNAL
up=nz(uparrowcond[1], false) == false and ( is_uptrend and nRes*forexyes>factor) and candledir ? 1:na
dn=nz(downarrowcond[1], false) == false and ( is_downtrend and nRes*forexyes<factor1) and candledir? -1:na
sig=0
if up==1
sig:=1
else
if dn==-1
sig:=-1
else
sig:=sig[1]
plotarrow(sig[1]!=1 and sig==1?1:na, title="BUY ARROW", colorup=lime, maxheight=80, minheight=50, transp=0)// up arrow
plotarrow(sig[1]!=-1 and sig==-1?-1:na, title="SELL ARROW", colordown=red, maxheight=80, minheight=50, transp=0)// down arrow
//========================= alert condition
alertcondition(sig[1]!=1 and sig==1?1:na, title="BUY eliminator", message="BUY " )
alertcondition(sig[1]!=-1 and sig==-1?-1:na, title="SELL eliminator", message="SELL ")
strategy.entry("B", true, when=(sig[1]!=1 and sig==1?1:na) and window1())
strategy.entry("S", false,when=(sig[1]!=-1 and sig==-1?-1:na) and window1())
|
Hancock - Filtered Volume OBV OSC [Strategy] | https://www.tradingview.com/script/tWdLcYVH-Hancock-Filtered-Volume-OBV-OSC-Strategy/ | ahancock | https://www.tradingview.com/u/ahancock/ | 477 | 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/
// © ahancock
//@version=4
strategy(
title = "Hancock - Filtered Volume OBV OSC [Strategy]",
initial_capital = 1000,
overlay = false,
commission_type = strategy.commission.percent,
commission_value= 0.075)
sma_average = "SMA"
ema_average = "EMA"
wma_average = "WMA"
hma_average = "HMA"
vwma_average = "VWMA"
rma_average = "RMA"
alma_average = "ALMA"
// Inputs
source = input(close, title = "Source", type = input.source)
use_vol_filter = input(true, title = "Use Volume Filter", type = input.bool)
vol_filter_length = input(50, title = "Volume Filter - Length", type = input.integer, minval = 1)
vol_filter_multiplier = input(2.5, title = "Volume Filter - Multiplier", type = input.float, minval = 0.1, step = 0.1)
use_osc = input(true, title = "Use Oscillator", type = input.bool)
osc_length = input(50, title = "Oscillator - Signal Length", type = input.integer, minval = 1)
osc_type = input(wma_average, title = "Oscillator - Type", options = [sma_average, ema_average, wma_average, hma_average, vwma_average, rma_average, alma_average])
average_alma_offset = input(0.85, title = "Oscillator - ALMA - Offset", type = input.float, minval = 0.05, step = 0.05)
average_alma_sigma = input(10, title = "Oscillator - ALMA - Sigma", type = input.integer, minval = 1)
channel_length = input(125, title = "Channel - Slow Length", minval = 5, maxval = 200, step = 5)
channel_percent = input(35, title = "Channel - Fast Length Percent", minval = 5, maxval = 100, step = 5)
trade_both = "Both", trade_long = "Long", trade_short = "Short"
trade_direction = input("Both", title = "Trade - Direction", options = [trade_both, trade_long, trade_short])
trade_leverage = input(5, title = "Trade - Leverage", type = input.integer, minval = 1, maxval = 100)
trade_stop = input(10, title = "Trade - Stop Loss %", type = input.float, minval = 0.5, step = 0.5, maxval = 100)
trade_trail_threshold = input(10, title = "Trade - Trail Stop Threshold %", type = input.float, minval = 0.5, step = 0.5, maxval = 100)
trade_trail = input(20, title = "Trade - Trail Stop Minimum %", type = input.float, minval = 0.5, step = 0.5, maxval = 100)
trade_risk = input(100, title = "Trade - Risk %", type = input.integer, step = 1, minval = 1, maxval = 100)
use_test_range = input(false, "Use Test Range", type = input.bool)
test_year = input(2016, "Test - Year", type = input.integer, minval = 1970, maxval = 2222)
test_month = input(01, "Test - Month", type = input.integer, minval = 1, maxval = 12)
test_day = input(01, "Test - Day", type = input.integer, minval = 1, maxval = 31)
// Functions
get_round(value, precision) => round(value * (pow(10, precision))) / pow(10, precision)
get_average(values, length, type) =>
type == sma_average ? sma(values, length) :
type == ema_average ? ema(values, length) :
type == wma_average ? wma(values, length) :
type == hma_average ? wma(2 * wma(values, length / 2) - wma(values, length), round(sqrt(length))) :
type == vwma_average ? vwma(values, length) :
type == rma_average ? rma(values, length) :
type == alma_average ? alma(values, length, average_alma_offset, average_alma_sigma) : na
get_obv(values, filter_length, filter_multiplier, use_filter, osc_length, osc_type, use_osc) =>
threshold = abs(avg(volume, filter_length) - (stdev(volume, filter_length) * filter_multiplier))
obv = 0.0
if (use_filter and volume < threshold)
obv := nz(obv[1])
else
obv := nz(obv[1]) + sign(change(values)) * volume
use_osc ? (obv - get_average(obv, osc_length, osc_type)) : obv
get_dc(high_values, low_values, length) =>
top = highest(high_values, length)
bot = lowest(low_values, length)
mid = bot + ((top - bot) / 2)
[top, mid, bot]
get_dcs(high_values, low_values, length, length_percent) =>
slow_length = length
fast_length = slow_length * length_percent / 100
[slow_top, slow_mid, slow_bot] =
get_dc(high_values, low_values, slow_length)
[fast_top, fast_mid, fast_bot] =
get_dc(high_values, low_values, fast_length)
[slow_top, slow_mid, slow_bot, fast_top, fast_mid, fast_bot]
// Strategy
obv = get_obv(
source,
vol_filter_length,
vol_filter_multiplier,
use_vol_filter,
osc_length,
osc_type,
use_osc)
[slow_top_price, _, slow_bot_price, fast_top_price, _, fast_bot_price] =
get_dcs(high, low, channel_length, channel_percent)
[slow_top_obv, _, slow_bot_obv, fast_top_obv, _, fast_bot_obv] =
get_dcs(obv, obv, channel_length, channel_percent)
enter_long_price = high > slow_top_price[1]
enter_short_price = low < slow_bot_price[1]
exit_long_price = low < fast_bot_price[1]
exit_short_price = high > fast_top_price[1]
enter_long_obv = obv > slow_top_obv[1] and (use_osc ? obv > 0 : true)
enter_short_obv = obv < slow_bot_obv[1] and (use_osc ? obv < 0 : true)
exit_long_obv = obv < fast_bot_obv[1]
exit_short_obv = obv > fast_top_obv[1]
// Trade Conditions
can_trade = true
enter_long_condition = enter_long_obv and enter_long_price
exit_long_condition = exit_long_obv and exit_long_price
enter_short_condition = enter_short_obv and enter_short_price
exit_short_condition = exit_short_obv and exit_short_price
// Positions
long_high = 0.0, long_high := nz(long_high[1], 0)
short_low = 0.0, short_low := nz(short_low[1], 0)
long_trail_threshold = 0.0, long_trail_threshold := nz(long_trail_threshold[1], 0)
short_trail_threshold = 0.0, short_trail_threshold := nz(short_trail_threshold[1], 0)
long_stop = 0.0, long_stop := nz(long_stop[1], 0)
short_stop = 0.0, short_stop := nz(short_stop[1], 0)
can_long = trade_direction == trade_long or trade_direction == trade_both
can_short = trade_direction == trade_short or trade_direction == trade_both
if (strategy.position_size > 0)
if(high > long_high)
long_high := high
if (long_high > long_trail_threshold)
long_stop := long_high - ((long_high / trade_leverage) * (trade_trail / 100))
strategy.exit("S/L", "LONG",
stop = long_stop,
qty = abs(get_round(strategy.position_size, 4)))
if (strategy.position_size < 0)
if (low < short_low)
short_low := low
if(short_low < short_trail_threshold)
short_stop := short_low + ((short_low / trade_leverage) * (trade_trail / 100))
strategy.exit("S/L", "SHORT",
stop = short_stop,
qty = abs(get_round(strategy.position_size, 4)))
if (exit_long_condition)
strategy.close("LONG")
if (exit_short_condition)
strategy.close("SHORT")
test_time = timestamp(test_year, test_month, test_day, 0, 0)
if (time >= test_time and strategy.opentrades == 0)
if (can_long)
if(enter_long_condition and strategy.position_size == 0)
contracts = get_round((strategy.equity * trade_leverage / close) * (trade_risk / 100), 4)
strategy.entry(
"LONG",
strategy.long,
qty = contracts)
long_high := low
long_trail_threshold := close + ((close / trade_leverage) * (trade_trail_threshold / 100))
long_stop := close - ((close / trade_leverage) * (trade_stop / 100))
if (can_short)
if (enter_short_condition and strategy.position_size == 0)
contracts = get_round((strategy.equity * trade_leverage / close) * (trade_risk / 100), 4)
strategy.entry(
"SHORT",
strategy.short,
qty = contracts)
short_low := high
short_trail_threshold := close - ((close / trade_leverage) * (trade_trail_threshold / 100))
short_stop := close + ((close / trade_leverage) * (trade_stop / 100))
// Plots
plotshape(enter_long_condition, "Enter Long", shape.diamond, location.top, color.green)
plotshape(exit_long_condition, "Exit Long", shape.diamond, location.top, color.red)
plotshape(enter_short_condition, "Enter Short", shape.diamond, location.bottom, color.green)
plotshape(exit_short_condition, "Exit Short", shape.diamond, location.bottom, color.red)
color_green = #63b987
color_red = #eb3d5c
hline(use_osc ? 0 : na)
plot(use_osc ? obv : na, color = color.silver, style = plot.style_area, transp = 90)
plot(obv, color = color.white, style = plot.style_line, linewidth = 2, transp = 0)
plot_slow_top = plot(slow_top_obv, color = color_green, linewidth = 2, transp = 60)
plot_slow_bot = plot(slow_bot_obv, color = color_green, linewidth = 2, transp = 60)
fill(plot_slow_top, plot_slow_bot, color = color_green, transp = 90)
plot_fast_top = plot(fast_top_obv, color = color_red, linewidth = 2, transp = 60)
plot_fast_bot = plot(fast_bot_obv, color = color_red, linewidth = 2, transp = 60)
fill(plot_fast_top, plot_fast_bot, color = color_red, transp = 90) |
Donchain Breakout | https://www.tradingview.com/script/fF9nC8iP-Donchain-Breakout/ | Senthaamizh | https://www.tradingview.com/u/Senthaamizh/ | 492 | 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/
// © Senthaamizh
//Break out trading system works best in a weekly chart and daily chart of Nifty and BankNifty
//@version=4
strategy("Donchain BO",shorttitle = "DBO",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true)
length = input(20, minval=1)
exit = input(1, minval=1, maxval=2,title = "Exit Option") // Use Option 1 to exit using lower band; Use Option 2 to exit using basis line
lower = lowest(length)
upper = highest(length)
basis = avg(upper, lower)
l = plot(lower, color=color.blue)
u = plot(upper, color=color.blue)
plot(basis, color=color.orange)
fill(u, l, color=color.blue)
longCondition = crossover(close,upper[1])
if (longCondition)
strategy.entry("Long", strategy.long)
if(exit==1)
if (crossunder(close,lower[1]))
strategy.close("Long")
if(exit==2)
if (crossunder(close,basis[1]))
strategy.close("Long")
|
Pair Trade L/S | https://www.tradingview.com/script/BijGRmNw-Pair-Trade-L-S/ | femisapien | https://www.tradingview.com/u/femisapien/ | 169 | 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/
// © femisapien
//@version=4
strategy("Pair Trade L/S", overlay=true)
source = close
smalength = input(title = "SMA Length", defval = 20, minval=1)
entryzscore = input(title = "Entry ZScore", defval = 2.0, minval=0, maxval = 50)
startYear = input(title="Backtest Start Year", type=input.integer, defval=2016, minval=1980, maxval=2100)
ma = sma(source, smalength)
dev = entryzscore * stdev(source, smalength)
upper = ma + dev
lower = ma - dev
longEntrySignal = cross(source, lower)
shortEntrySignal = cross(source, upper)
exitSignal = cross(source, ma)
afterStartDate = (time >= timestamp(syminfo.timezone, startYear,1,1, 0, 0))
if (longEntrySignal and afterStartDate)
strategy.entry("le", strategy.long, comment = "Enter Long")
if (shortEntrySignal and afterStartDate)
strategy.entry("se", strategy.short, comment="Enter Short")
if (exitSignal and afterStartDate)
strategy.close_all(true) |
How To Set Backtest Time Ranges | https://www.tradingview.com/script/xAEG4ZJG-How-To-Set-Backtest-Time-Ranges/ | allanster | https://www.tradingview.com/u/allanster/ | 926 | 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/
// © allanster
//@version=5
strategy(title = "How To Set Time Ranges", shorttitle = "Timed", overlay = true, precision = 8, max_bars_back = 200, pyramiding = 0, initial_capital = 100000,
currency = currency.NONE, default_qty_type = strategy.cash, default_qty_value = 100000, commission_type = "percent", commission_value = 0.27)
// Revision: 2
// Author: @allanster
// Credit: Special thanks to @LucF and @a.tesla2018 for help with including ':1234567' for time ranges on weekends
// === INPUT MA LENGTHS ===
fastMA = input.int(defval = 14, title = "FastMA Length", minval = 1, step = 1)
slowMA = input.int(defval = 28, title = "SlowMA Length", minval = 1, step = 1)
// === INPUT DATE RANGE ===
fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromYear = input.int(defval = 2021, title = "From Year", minval = 1970)
thruMonth = input.int(defval = 1, title = "Thru Month", minval = 1, maxval = 12)
thruDay = input.int(defval = 1, title = "Thru Day", minval = 1, maxval = 31)
thruYear = input.int(defval = 2112, title = "Thru Year", minval = 1970)
// === INPUT TIME RANGE ===
entryTime = input.session('0000-0000', title = "Entry Time") // '0000-0000' is anytime to enter
exitTime = input.session('0000-0000', title = "Exit Time") // '0000-0000' is anytime to exit
// === INPUT SHOW PLOTS ===
showDate = input(true, title = "Show Date Range")
showTimeE = input(true, title = "Show Time Entry")
showTimeX = input(true, title = "Show Time Exit")
// === DATE & TIME RANGE FUNCTIONS ===
isDate() => // create function "within window of dates"
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // date start
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // date finish
isDate = time >= start and time <= finish // current date is "within window of dates"
isTime(_position) => // create function "within window of time"
isTime = time(timeframe.period, _position + ':1234567') // current time is "within window of time"
// === LOGIC ===
enterLong = ta.crossover (ta.sma(close, fastMA), ta.sma(close, slowMA)) // enter when fastMA crosses over slowMA
exitLong = ta.crossunder(ta.sma(close, fastMA), ta.sma(close, slowMA)) // exits when fastMA crosses under slowMA
// === EXECUTION ===
strategy.entry("L", strategy.long, when = isDate() and isTime(entryTime) and enterLong) // enter "within window of dates and time" AND crossover
strategy.close("L", when = isDate() and isTime(exitTime) and exitLong) // exits "within window of dates and time" AND crossunder
// === PLOTTING ===
bgcolor(color = showDate and isDate() ? color.new(color.gray, 90) : color(na)) // plot "within window of dates"
bgcolor(color = showTimeE and isDate() and isTime(entryTime) ? color.new(color.lime, 90) : color(na)) // plot "within window of entry time"
bgcolor(color = showTimeX and isDate() and isTime(exitTime) ? color.new(color.purple, 90) : color(na)) // plot "within window of exit time"
plot(ta.sma(close, fastMA), title = 'FastMA', color = color.new(color.yellow, 0), linewidth = 2, style = plot.style_line) // plot FastMA
plot(ta.sma(close, slowMA), title = 'SlowMA', color = color.new(color.aqua, 0), linewidth = 2, style = plot.style_line) // plot SlowMA |
RSI-VWAP | https://www.tradingview.com/script/4e8SSKeK/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 872 | 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
//#####©ÉÉÉɶN###############################################
//####*..´´´´´´,,,»ëN########################################
//###ë..´´´´´´,,,,,,''%©#####################################
//###'´´´´´´,,,,,,,'''''?¶###################################
//##o´´´´´´,,,,,,,''''''''*©#################################
//##'´´´´´,,,,,,,'''''''^^^~±################################
//#±´´´´´,,,,,,,''''''''^í/;~*©####æ%;í»~~~~;==I±N###########
//#»´´´´,,,,,,'''''''''^;////;»¶X/í~~/~~~;=~~~~~~~~*¶########
//#'´´´,,,,,,''''''''^^;////;%I^~/~~/~~~=~~~;=?;~~~~;?ë######
//©´´,,,,,,,''''''''^^~/////X~/~~/~~/~~»í~~=~~~~~~~~~~^;É####
//¶´,,,,,,,''''''''^^^;///;%;~/~~;í~~»~í?~?~~~?I/~~~~?*=íÑ###
//N,,,,,,,'''''''^^^^^///;;o/~~;;~~;£=»í»;IX/=~~~~~~^^^^'*æ##
//#í,,,,,''''''''^^^^^;;;;;o~»~~~~íX//~/»~;í?IíI»~~^/*?'''=N#
//#%,,,'''''''''^^^^^^í;;;;£;~~~//»I»/£X/X/»í*&~~~^^^^'^*~'É#
//#©,,''''''''^^^^^^^^~;;;;&/~/////*X;í;o*í»~=*?*===^'''''*£#
//##&''''''''^^^^^^^^^^~;;;;X=í~~~»;;;/~;í»~»±;^^^^^';=''''É#
//##N^''''''^^^^^^^^^^~~~;;;;/£;~~/»~~»~~///o~~^^^^''''?^',æ#
//###Ñ''''^^^^^^^^^^^~~~~~;;;;;í*X*í»;~~IX?~~^^^^/?'''''=,=##
//####X'''^^^^^^^^^^~~~~~~~~;;íííííí~~í*=~~~~Ií^'''=''''^»©##
//#####£^^^^^^^^^^^~~~~~~~~~~~íííííí~~~~~*~^^^;/''''='',,N###
//######æ~^^^^^^^^~~~~~~~~~~~~~~íííí~~~~~^*^^^'=''''?',,§####
//########&^^^^^^~~~~~~~~~~~~~~~~~~~~~~~^^=^^''=''''?,íN#####
//#########N?^^~~~~~~~~~~~~~~~~~~~~~~~~^^^=^''^?''';í@#######
//###########N*~~~~~~~~~~~~~~~~~~~~~~~^^^*'''^='''/É#########
//##############@;~~~~~~~~~~~~~~~~~~~^^~='''~?'';É###########
//#################É=~~~~~~~~~~~~~~^^^*~'''*~?§##############
//#####################N§£I/~~~~~~»*?~»o§æN##################
//@version=4
strategy("RSI-VWAP #STRATEGY#", overlay=true, initial_capital = 1000, currency = "USD", pyramiding = 10, default_qty_type = strategy.cash, default_qty_value = 1000, commission_value = 0.04)
//Uncomment for alerts
//study("RSI-VWAP INDICATOR", overlay=true)
// ================================================================================================================================================================================
// VARIABLES
// ================================================================================================================================================================================
var bool long = na, var bool short = na
var bool longCondition = na, var bool shortCondition = na
var bool Xlong = na, var bool Xshort = na,
var int CondIni_long = 0, var int CondIni_short = 0
var bool XlongCondition = na, var bool XshortCondition = na
var float last_open_longCondition = na, var float last_open_shortCondition = na
var int last_longCondition = 0, var int last_shortCondition = 0
var bool in_longCondition = na, var bool in_shortCondition = na
var int last_long_sl = na, var int last_short_sl = na
var bool CondIni_long_sl = 0, var bool CondIni_short_sl = 0
var int nLongs = na, var int nShorts = na, var int pyr = na
var float sum_long = 0.0, var float sum_short = 0.0
var float Position_Price = 0.0, Position_Price := nz(Position_Price[1])
var bool Final_Long_sl = na, var bool Final_Short_sl = na, var bool Act_sl = na, var float sl = na
var int last_long_tp = na, var int last_short_tp = na
var bool CondIni_long_tp = 0, var bool CondIni_short_tp = 0
var float Quantity = na, var float Increase = na
var float sum_qty_l = na, var float sum_qty_s = na
// ================================================================================================================================================================================
// RSI VWAP INDICATOR
// ================================================================================================================================================================================
// Initial inputs
Long_only = input(true, "🐮 ACTIVATE BULLS")
RSI_VWAP_length_long = input(17, "RSI-VWAP LENGTH", minval = 1, maxval = 99)
RSI_VWAP_overSold_long = input(19, "OVERSOLD (LONG)", type=input.float, minval = 1, maxval = 99)
RSI_VWAP_overBought_long = input(78, "OVERBOUGHT (XLONG)", type=input.float, minval = 1, maxval = 99)
RSI_VWAP_overSold_long2 = input(38, "OVERSOLD 2 (LONG)", type=input.float, minval = 1, maxval = 99)
Short_only = input(false, "🐻 ACTIVATE BEARS")
RSI_VWAP_length_short = input(17, "RSI-VWAP LENGTH", minval = 1, maxval = 99)
RSI_VWAP_overSold_short = input(19, "OVERSOLD (XSHORT)", type=input.float, minval = 1, maxval = 99)
RSI_VWAP_overBought_short = input(80, "OVERBOUGHT (SHORT)", type=input.float, minval = 1, maxval = 99)
RSI_VWAP_overBought_short2 = input(59, "OVERBOUGHT 2 (SHORT)", type=input.float, minval = 1, maxval = 99)
// RSI with VWAP as source
RSI_VWAP_long = rsi(vwap(close), RSI_VWAP_length_long)
RSI_VWAP_short = rsi(vwap(close), RSI_VWAP_length_short)
// ================================================================================================================================================================================
// STRATEGY
// ================================================================================================================================================================================
// Long/Short conditions, next entry always at better price
long := (((crossover(RSI_VWAP_long, RSI_VWAP_overSold_long2)) and nz(CondIni_long[1]) == -1) or (crossover(RSI_VWAP_long, RSI_VWAP_overSold_long))) and (nz(nLongs[1]) < pyr) and Long_only
longCondition := in_longCondition and nLongs > 0 ? long and (close < fixnan(Position_Price[1])) : long
short := (((crossunder(RSI_VWAP_short, RSI_VWAP_overBought_short2)) and nz(CondIni_short[1]) == -1) or (crossunder(RSI_VWAP_short, RSI_VWAP_overBought_short))) and (nz(nShorts[1]) < pyr) and Short_only
shortCondition := in_shortCondition and nShorts > 0 ? short and (close > fixnan(Position_Price[1])) : short
// Xlong/Xshort Conditions, closing with profit only?
Xlong := (crossunder(RSI_VWAP_long, RSI_VWAP_overBought_long)) and Long_only and not Short_only
Xshort := (crossover(RSI_VWAP_short, RSI_VWAP_overSold_short)) and Short_only and not Long_only
CondIni_long := longCondition ? 1 : Xlong or shortCondition ? -1 : nz(CondIni_long[1])
CondIni_short := shortCondition ? 1 : Xshort or longCondition ? -1 : nz(CondIni_short[1])
XlongCondition := Xlong and nz(CondIni_long[1]) == 1
XshortCondition := Xshort and nz(CondIni_short[1]) == 1
// Get the price of the last opened long or short
last_open_longCondition := longCondition ? close : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition ? close : nz(last_open_shortCondition[1])
// Get the bar time of the last opened long or short
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
// In long/short conditions
in_longCondition := last_longCondition > last_shortCondition
in_shortCondition := last_shortCondition > last_longCondition
// ================================================================================================================================================================================
// PRICE AVERAGE / PYRAMIDING
// ================================================================================================================================================================================
// Pyramiding
pyr := input(10, "MAX. PYRAMIDING 🎢" , minval = 1, maxval = 10)
// Counting long & short iterations
nLongs := nz(nLongs[1])
nShorts := nz(nShorts[1])
// Longs Counter
if longCondition or (Final_Long_sl and not Act_sl)
nLongs := nLongs + 1
nShorts := 0
// Shorts Counter
if shortCondition or (Final_Short_sl and not Act_sl)
nLongs := 0
nShorts := nShorts + 1
// Quantity Factor
QF_l = Quantity+(Increase*(nLongs-1))
QF_s = Quantity+(Increase*(nShorts-1))
// Price average of your position according to the quantities
if longCondition
sum_long := nz(last_open_longCondition)*QF_l + nz(sum_long[1])
sum_short := 0.0
sum_qty_l := QF_l + nz(sum_qty_l[1])
sum_qty_s := na
if Final_Long_sl and not Act_sl
sum_long := ((1-(sl/100))*last_open_longCondition)*QF_l + nz(sum_long[1])
sum_short := 0.0
sum_qty_l := QF_l + nz(sum_qty_l[1])
sum_qty_s := na
if shortCondition
sum_short := nz(last_open_shortCondition)*QF_s + nz(sum_short[1])
sum_long := 0.0
sum_qty_s := QF_s + nz(sum_qty_s[1])
sum_qty_l := na
if Final_Short_sl and not Act_sl
sum_long := 0.0
sum_short := ((1+(sl/100))*last_open_shortCondition)*QF_s + nz(sum_short[1])
sum_qty_s := QF_s + nz(sum_qty_s[1])
sum_qty_l := na
// Calculating and Plotting the price average
Position_Price := nz(Position_Price[1])
Position_Price := longCondition or (Final_Long_sl and not Act_sl) ? sum_long/(sum_qty_l) : shortCondition or (Final_Short_sl and not Act_sl) ? sum_short/(sum_qty_s) : na
plot(Position_Price[1], title = "Average Price", color = in_longCondition ? color.blue : color.red, linewidth = 2, style = plot.style_cross, transp = 0)
// ================================================================================================================================================================================
// STOP LOSS / RE-ENTRY
// ================================================================================================================================================================================
// SL initial inputs
Act_sl := input(false, "ACTIVATE SL / DEACTIVATE RE-ENTRY")
sl := input(10, "STOP LOSS / RE-ENTRY %", type = input.float, minval = 0, step = 0.5)
// Initial SL conditions
long_sl = crossunder(low, (1-(sl/100))*last_open_longCondition) and in_longCondition and not longCondition
short_sl = crossover(high, (1+(sl/100))*last_open_shortCondition) and in_shortCondition and not shortCondition
// Get the time of the last sl
last_long_sl := long_sl ? time : nz(last_long_sl[1])
last_short_sl := short_sl ? time : nz(last_short_sl[1])
// Sl counter
CondIni_long_sl := long_sl or XlongCondition ? 1 : longCondition ? -1 : nz(CondIni_long_sl[1])
CondIni_short_sl := short_sl or XshortCondition ? 1 : shortCondition ? -1 : nz(CondIni_short_sl[1])
// Final SL conditions
Final_Long_sl := long_sl and nz(CondIni_long_sl[1]) == -1 and in_longCondition and not longCondition
Final_Short_sl := short_sl and nz(CondIni_short_sl[1]) == -1 and in_shortCondition and not shortCondition
// ================================================================================================================================================================================
// TAKE PROFIT
// ================================================================================================================================================================================
// Take Profit input
Act_tp = input(false, "ACTIVATE TAKE PROFIT")
tp = input(5.0, "TAKE PROFIT %", type = input.float, minval = 0, step = 0.5)
qty_TP = input(50, "QUANTITY TO CLOSE TP %", minval = 0, maxval = 100)
// Initial TP conditions
long_tp = crossover(high, (1+(tp/100))*fixnan(Position_Price)) and in_longCondition and not longCondition and not Final_Long_sl and Act_tp
short_tp = crossunder(low, (1-(tp/100))*fixnan(Position_Price)) and in_shortCondition and not shortCondition and not Final_Short_sl and Act_tp
// Get the time of the last tp
last_long_tp := long_tp ? time : nz(last_long_tp[1])
last_short_tp := short_tp ? time : nz(last_short_tp[1])
// Tp signal ordering
CondIni_long_tp := (Final_Long_sl and Act_sl) or XlongCondition ? 1 : longCondition ? -1 : nz(CondIni_long_tp[1])
CondIni_short_tp := Final_Short_sl and Act_sl ? 1 : shortCondition ? -1 : nz(CondIni_short_tp[1])
// Final tp condition
Final_Long_tp = long_tp and last_longCondition > nz(last_long_tp[1]) and nz(CondIni_long_tp[1]) == -1
Final_Short_tp = short_tp and last_shortCondition > nz(last_short_tp[1]) and nz(CondIni_short_tp[1]) == -1
if Final_Long_tp or (Final_Long_sl and Act_sl) or XlongCondition
sum_long := 0.0
nLongs := na
CondIni_long_sl := 1
sum_qty_l := na
if Final_Short_tp or (Final_Short_sl and Act_sl) or XshortCondition
sum_short := 0.0
nShorts := na
CondIni_short_sl := 1
sum_qty_s := na
// ================================================================================================================================================================================
// SIGNALS
// ================================================================================================================================================================================
// Longs
//label.new(
// x = longCondition[1] ? time : na,
// y = na,
// text = 'LONG '+tostring(nLongs),
// color = color.blue,
// textcolor = color.black,
// style = label.style_labelup,
// xloc = xloc.bar_time,
// yloc = yloc.belowbar,
// size = size.tiny
// )
// Shorts
//label.new(
// x = shortCondition[1] ? time : na,
// y = na,
// text = 'SHORT '+tostring(nShorts),
// color = color.red,
// textcolor = color.black,
// style = label.style_labeldown,
// xloc = xloc.bar_time,
// yloc = yloc.abovebar,
// size = size.tiny
// )
// XLongs
//label.new(
// x = XlongCondition[1] ? time : na,
// y = na,
// text = 'XLONG',
// color = color.yellow,
// textcolor = color.black,
// style = label.style_labeldown,
// xloc = xloc.bar_time,
// yloc = yloc.abovebar,
// size = size.tiny
// )
// XShorts
//label.new(
// x = XshortCondition[1] ? time : na,
// y = na,
// text = 'XSHORT',
// color = color.yellow,
// textcolor = color.black,
// style = label.style_labelup,
// xloc = xloc.bar_time,
// yloc = yloc.belowbar,
// size = size.tiny
// )
// Tp on longs
//label.new(
// x = Final_Long_tp ? time : na,
// y = na,
// text = 'TP '+tostring(tp)+'%',
// color = color.orange,
// textcolor = color.black,
// style = label.style_labeldown,
// xloc = xloc.bar_time,
// yloc = yloc.abovebar,
// size = size.tiny
// )
//ltp = iff(Final_Long_tp, (fixnan(Position_Price)*(1+(tp/100))), na), plot(ltp, style=plot.style_cross, linewidth=3, color = color.white, editable = false)
// Tp on shorts
//label.new(
// x = Final_Short_tp ? time : na,
// y = na,
// text = 'TP '+tostring(tp)+'%',
// color = color.orange,
// textcolor = color.black,
// style = label.style_labelup,
// xloc = xloc.bar_time,
// yloc = yloc.belowbar,
// size = size.tiny
// )
//stp = iff(Final_Short_tp, (fixnan(Position_Price)*(1-(tp/100))), na), plot(stp, style=plot.style_cross, linewidth=3, color = color.white, editable = false)
// Sl on Longs
//label.new(
// x = Final_Long_sl ? time : na,
// y = na,
// text = Act_sl ? ('SL '+tostring(sl)+'%') : ('RE '+tostring(sl)+'%'),
// color = color.green,
// textcolor = color.black,
// style = label.style_labelup,
// xloc = xloc.bar_time,
// yloc = yloc.belowbar,
// size = size.tiny
// )
// Sl on Longs dot
//lsl = iff(Final_Long_sl, (last_open_longCondition*(1-(sl/100))), na), plot(lsl, style=plot.style_cross, linewidth=3, color = color.white, editable = false)
// Sl on Shorts
//label.new(
// x = Final_Short_sl ? time : na,
// y = na,
// text = Act_sl ? ('SL '+tostring(sl)+'%') : ('RE '+tostring(sl)+'%'),
// color = color.maroon,
// textcolor = color.black,
// style = label.style_labeldown,
// xloc = xloc.bar_time,
// yloc = yloc.abovebar,
// size = size.tiny
// )
// Sl on Shorts dot
//ssl = iff(Final_Short_sl, (last_open_shortCondition*(1+(sl/100))), na), plot(ssl, style=plot.style_cross, linewidth=3, color = color.white, editable = false)
// ================================================================================================================================================================================
// BACKTEST
// ================================================================================================================================================================================
// Backtest inputs
Act_BT = input(true, "BACKTEST 💹")
contracts_or_cash = input("CASH", "CONTRACTS ₿ / CASH $", options = ["CONTRACTS","CASH"])
cc_factor = (contracts_or_cash == "CASH") ? close : 1
Quantity := input(1000, "$ QUANTITY 1ST ENTRY", minval = 0)/cc_factor
Increase := input(500, "$ INCREASE NEXT ENTRY", minval = 0)/cc_factor
// Backtest Period inputs
testStartYear = input(2019, "BACKTEST START YEAR ⏲️", minval = 1980, maxval = 2222)
testStartMonth = input(01, "BACKTEST START MONTH", minval = 1, maxval = 12)
testStartDay = input(01, "BACKTEST START DAY", minval = 1, maxval = 31)
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testStopYear = input(2222, "BACKTEST STOP YEAR", minval=1980, maxval = 2222)
testStopMonth = input(12, "BACKTEST STOP MONTH", minval=1, maxval=12)
testStopDay = input(31, "BACKTEST STOP DAY", minval=1, maxval=31)
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
// Backtest Condition
testPeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false
// Backtest entries
if (Act_BT and testPeriod)
strategy.entry("Long", strategy.long, qty = QF_l, when = longCondition or (Final_Long_sl and not Act_sl))
strategy.close("Long", when = XlongCondition)
strategy.entry("Short", strategy.short, qty = QF_s, when = shortCondition or (Final_Short_sl and not Act_sl))
strategy.close("Short", when = XshortCondition)
strategy.exit("TPl", "Long", qty_percent = qty_TP, limit = Act_tp ? (fixnan(Position_Price)*(1+(tp/100))) : na)
strategy.close("Long", when = Act_sl and Final_Long_sl)
strategy.exit("TPs", "Short", qty_percent = qty_TP, limit = Act_tp ? (fixnan(Position_Price)*(1-(tp/100))) : na)
strategy.close("Short", when = Act_sl and Final_Short_sl)
// ================================================================================================================================================================================
// ALERTS
// ================================================================================================================================================================================
// LONGS
alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)), title="All Longs Alert",
message = "LONG")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 1, title="Long 1 Alert",
// message = "LONG1")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 2, title="Long 2 Alert",
// message = "LONG2")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 3, title="Long 3 Alert",
// message = "LONG3")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 4, title="Long 4 Alert",
// message = "LONG4")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 5, title="Long 5 Alert",
// message = "LONG5")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 6, title="Long 1 Alert",
// message = "LONG6")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 7, title="Long 1 Alert",
// message = "LONG7")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 8, title="Long 1 Alert",
// message = "LONG8")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 9, title="Long 1 Alert",
// message = "LONG9")
//alertcondition((longCondition[1] or (Final_Long_sl and not Act_sl)) and nLongs == 10, title="Long 1 Alert",
// message = "LONG10")
alertcondition(Final_Long_tp, title="TPL Alert",
message = "TPL")
alertcondition(XlongCondition[1] or (Final_Long_sl and Act_sl), title="Close Long / SL Alert",
message = "XL/SLL")
// SHORTS
alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)), title="All Shorts Alert",
message = "SHORT")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 1, title="Short 1 Alert",
// message = "SHORT1")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 2, title="Short 2 Alert",
// message = "SHORT2")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 3, title="Short 3 Alert",
// message = "SHORT3")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 4, title="Short 4 Alert",
// message = "SHORT4")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 5, title="Short 5 Alert",
// message = "SHORT5")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 6, title="Short 6 Alert",
// message = "SHORT6")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 7, title="Short 7 Alert",
// message = "SHORT7")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 8, title="Short 8 Alert",
// message = "SHORT8")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 9, title="Short 9 Alert",
// message = "SHORT9")
//alertcondition((shortCondition[1] or (Final_Short_sl and not Act_sl)) and nShorts == 10, title="Short 10 Alert",
// message = "SHORT10")
alertcondition(Final_Short_tp, title="TPS/SLS Alert",
message = "TPS")
alertcondition(XshortCondition[1] or (Final_Short_sl and Act_sl), title="Close Long / SL Alert",
message = "XS/SLS")
// by Xaviz
|
Volatility Traders Minds Strategy (VTM Strategy) | https://www.tradingview.com/script/nDPVOul3-Volatility-Traders-Minds-Strategy-VTM-Strategy/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 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/
// © 03.freeman
//Volatility Traders Minds Strategy (VTM Strategy)
//I found this startegy on internet, with a video explaingin how it works.
//Conditions for entry:
//1 - Candles must to be above or bellow the 48 MA (Yellow line)
//2 - Candles must to break the middle of bollinger bands
//3 - Macd must to be above or bellow zero level;
//4 - ADX must to be above 25 level
//@version=4
strategy("Volatility Traders Minds Strategy (VTM Strategy)", shorttitle="VTM",overlay=true)
source = input(close)
//MA
ma48 = sma(source,48)
//MACD
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ema(source, fastLength) - ema(source, slowlength)
aMACD = ema(MACD, MACDLength)
delta = MACD - aMACD
//BB
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)
basis = sma(source, length)
dev = mult * stdev(source, length)
upper = basis + dev
lower = basis - dev
//ADX
adxThreshold = input(title="ADX Threshold", type=input.integer, defval=25, minval=1)
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(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)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
// Strategy: (Thanks to JayRogers)
// === STRATEGY RELATED INPUTS ===
//tradeInvert = input(defval = false, title = "Invert Trade Direction?")
// the risk management inputs
inpTakeProfit = input(defval = 0, title = "Take Profit Points", minval = 0)
inpStopLoss = input(defval = 0, title = "Stop Loss Points", minval = 0)
inpTrailStop = input(defval = 0, title = "Trailing Stop Loss Points", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset Points", minval = 0)
// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// === STRATEGY - LONG POSITION EXECUTION ===
enterLong() => close>ma48 and close>basis and delta>0 and sig>adxThreshold // functions can be used to wrap up and work out complex conditions
//exitLong() => jaw>teeth or jaw>lips or teeth>lips
strategy.entry(id = "Buy", long = true, when = enterLong() ) // use function or simple condition to decide when to get in
//strategy.close(id = "Buy", when = exitLong() ) // ...and when to get out
// === STRATEGY - SHORT POSITION EXECUTION ===
enterShort() => close<ma48 and close<basis and delta<0 and sig>adxThreshold
//exitShort() => jaw<teeth or jaw<lips or teeth<lips
strategy.entry(id = "Sell", long = false, when = enterShort())
//strategy.close(id = "Sell", when = exitShort() )
// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Buy", from_entry = "Buy", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Sell", from_entry = "Sell", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
// === Backtesting Dates === thanks to Trost
testPeriodSwitch = input(false, "Custom Backtesting Dates")
testStartYear = input(2020, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testStartHour = input(0, "Backtest Start Hour")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,testStartHour,0)
testStopYear = input(2020, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(31, "Backtest Stop Day")
testStopHour = input(23, "Backtest Stop Hour")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,testStopHour,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
isPeriod = testPeriodSwitch == true ? testPeriod() : true
// === /END
if not isPeriod
strategy.cancel_all()
strategy.close_all() |
Scalping with Bill Williams Alligator | https://www.tradingview.com/script/b2ShO5Fv-Scalping-with-Bill-Williams-Alligator/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 1,676 | 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/
// © 03.freeman
//Scalping strategy based on Bill Williams Alligator technique but applied to heikin ashi candles
//This strategy has to be applied to standard candles and low time frames (1min to 5min)
//@version=4
strategy("Bill Williams Alligator improved", shorttitle="Scalping alligator",overlay=true)
//source = input(close)
useHA = input (true,"Use heikin ashi candle?")
// ----------MA calculation - ChartArt-------------
smoothinput = input(1, minval=1, maxval=5, title='Moving Average Calculation: (1=SMA), (2=EMA), (3=WMA), (4=Linear), (5=VWMA)')
calc_ma(src,l) =>
smoothinput == 1 ? sma(src, l):smoothinput == 2 ? ema(src, l):smoothinput == 3 ? wma(src, l):smoothinput == 4 ? linreg(src, l,0):smoothinput == 5 ? vwma(src,l):na
//----------------------------------------------
heikinashi_close = security(heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_open = security(heikinashi(syminfo.tickerid), timeframe.period, open)
heikinashi_hl2 = security(heikinashi(syminfo.tickerid), timeframe.period, hl2)
direzione=heikinashi_close>heikinashi_open and heikinashi_close[1]>heikinashi_open[1]? 1 : heikinashi_close<heikinashi_open and heikinashi_close[1]<heikinashi_open[1]? -1 : 0
jawLength = input(13, minval=1, title="Jaw Length")
teethLength = input(8, minval=1, title="Teeth Length")
lipsLength = input(5, minval=1, title="Lips Length")
jawOffset = input(8, title="Jaw Offset")
teethOffset = input(5, title="Teeth Offset")
lipsOffset = input(3, title="Lips Offset")
jaw = calc_ma(heikinashi_hl2, jawLength)
teeth = calc_ma(heikinashi_hl2, teethLength)
lips = calc_ma(heikinashi_hl2, lipsLength)
plot(jaw, title="jaw",offset = jawOffset, color=#3BB3E4)
plot(teeth, title="teeth",offset = teethOffset, color=#FF006E)
plot(lips, title="lips",offset = lipsOffset, color=#36C711)
longCondition = direzione[0]==1 and jaw<teeth and jaw<lips and teeth<lips
shortCondition = direzione[0]==-1 and jaw>teeth and jaw>lips and teeth>lips
// Strategy: (Thanks to JayRogers)
// === STRATEGY RELATED INPUTS ===
//tradeInvert = input(defval = false, title = "Invert Trade Direction?")
// the risk management inputs
inpTakeProfit = input(defval = 0, title = "Take Profit Points", minval = 0)
inpStopLoss = input(defval = 0, title = "Stop Loss Points", minval = 0)
inpTrailStop = input(defval = 0, title = "Trailing Stop Loss Points", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset Points", minval = 0)
// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// === STRATEGY - LONG POSITION EXECUTION ===
enterLong() => direzione[0]==1 and jaw<teeth and jaw<lips and teeth<lips // functions can be used to wrap up and work out complex conditions
exitLong() => jaw>teeth or jaw>lips or teeth>lips
strategy.entry(id = "Buy", long = true, when = enterLong() ) // use function or simple condition to decide when to get in
strategy.close(id = "Buy", when = exitLong() ) // ...and when to get out
// === STRATEGY - SHORT POSITION EXECUTION ===
enterShort() => direzione[0]==-1 and jaw>teeth and jaw>lips and teeth>lips
exitShort() => jaw<teeth or jaw<lips or teeth<lips
strategy.entry(id = "Sell", long = false, when = enterShort())
strategy.close(id = "Sell", when = exitShort() )
// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Buy", from_entry = "Buy", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Sell", from_entry = "Sell", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
// === Backtesting Dates === thanks to Trost
testPeriodSwitch = input(false, "Custom Backtesting Dates")
testStartYear = input(2020, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testStartHour = input(0, "Backtest Start Hour")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,testStartHour,0)
testStopYear = input(2020, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(31, "Backtest Stop Day")
testStopHour = input(23, "Backtest Stop Hour")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,testStopHour,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
isPeriod = testPeriodSwitch == true ? testPeriod() : true
// === /END
if not isPeriod
strategy.cancel_all()
strategy.close_all() |
RSI-VWAP INDICATOR | https://www.tradingview.com/script/ia49d7a0/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 3,550 | 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
//#####©ÉÉÉɶN###############################################
//####*..´´´´´´,,,»ëN########################################
//###ë..´´´´´´,,,,,,''%©#####################################
//###'´´´´´´,,,,,,,'''''?¶###################################
//##o´´´´´´,,,,,,,''''''''*©#################################
//##'´´´´´,,,,,,,'''''''^^^~±################################
//#±´´´´´,,,,,,,''''''''^í/;~*©####æ%;í»~~~~;==I±N###########
//#»´´´´,,,,,,'''''''''^;////;»¶X/í~~/~~~;=~~~~~~~~*¶########
//#'´´´,,,,,,''''''''^^;////;%I^~/~~/~~~=~~~;=?;~~~~;?ë######
//©´´,,,,,,,''''''''^^~/////X~/~~/~~/~~»í~~=~~~~~~~~~~^;É####
//¶´,,,,,,,''''''''^^^;///;%;~/~~;í~~»~í?~?~~~?I/~~~~?*=íÑ###
//N,,,,,,,'''''''^^^^^///;;o/~~;;~~;£=»í»;IX/=~~~~~~^^^^'*æ##
//#í,,,,,''''''''^^^^^;;;;;o~»~~~~íX//~/»~;í?IíI»~~^/*?'''=N#
//#%,,,'''''''''^^^^^^í;;;;£;~~~//»I»/£X/X/»í*&~~~^^^^'^*~'É#
//#©,,''''''''^^^^^^^^~;;;;&/~/////*X;í;o*í»~=*?*===^'''''*£#
//##&''''''''^^^^^^^^^^~;;;;X=í~~~»;;;/~;í»~»±;^^^^^';=''''É#
//##N^''''''^^^^^^^^^^~~~;;;;/£;~~/»~~»~~///o~~^^^^''''?^',æ#
//###Ñ''''^^^^^^^^^^^~~~~~;;;;;í*X*í»;~~IX?~~^^^^/?'''''=,=##
//####X'''^^^^^^^^^^~~~~~~~~;;íííííí~~í*=~~~~Ií^'''=''''^»©##
//#####£^^^^^^^^^^^~~~~~~~~~~~íííííí~~~~~*~^^^;/''''='',,N###
//######æ~^^^^^^^^~~~~~~~~~~~~~~íííí~~~~~^*^^^'=''''?',,§####
//########&^^^^^^~~~~~~~~~~~~~~~~~~~~~~~^^=^^''=''''?,íN#####
//#########N?^^~~~~~~~~~~~~~~~~~~~~~~~~^^^=^''^?''';í@#######
//###########N*~~~~~~~~~~~~~~~~~~~~~~~^^^*'''^='''/É#########
//##############@;~~~~~~~~~~~~~~~~~~~^^~='''~?'';É###########
//#################É=~~~~~~~~~~~~~~^^^*~'''*~?§##############
//#####################N§£I/~~~~~~»*?~»o§æN##################
//@version=4
strategy("RSI-VWAP INDICATOR", overlay=false, initial_capital = 1000, currency = "USD", pyramiding = 5, default_qty_type = strategy.cash, default_qty_value = 1000, commission_value = 0.04)
// ================================================================================================================================================================================
// RSI VWAP INDICATOR
// ================================================================================================================================================================================
// Initial inputs
Act_RSI_VWAP = input(true, "RSI VOLUME WEIGHTED AVERAGE PRICE")
RSI_VWAP_length = input(17, "RSI-VWAP LENGTH")
RSI_VWAP_overSold = input(19, "RSI-VWAP OVERSOLD", type=input.float)
RSI_VWAP_overBought = input(80, "RSI-VWAP OVERBOUGHT", type=input.float)
// RSI with VWAP as source
RSI_VWAP = rsi(vwap(close), RSI_VWAP_length)
// Plotting, overlay=false
r=plot(RSI_VWAP, color = RSI_VWAP > RSI_VWAP_overBought ? color.red : RSI_VWAP < RSI_VWAP_overSold ? color.lime : color.blue, title="rsi", linewidth=2, style=plot.style_line)
h1=plot(RSI_VWAP_overBought, color = color.gray, style=plot.style_stepline)
h2=plot(RSI_VWAP_overSold, color = color.gray, style=plot.style_stepline)
fill(r,h1, color = RSI_VWAP > RSI_VWAP_overBought ? color.red : na, transp = 60)
fill(r,h2, color = RSI_VWAP < RSI_VWAP_overSold ? color.lime : na, transp = 60)
// Long only Backtest
strategy.entry("Long", strategy.long, when = (crossover(RSI_VWAP, RSI_VWAP_overSold)))
strategy.close("Long", when = (crossunder(RSI_VWAP, RSI_VWAP_overBought))) |
Coinbook Statergy by shakir | https://www.tradingview.com/script/qP8fW2YG-Coinbook-Statergy-by-shakir/ | ayahanisha4 | https://www.tradingview.com/u/ayahanisha4/ | 9 | 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/
// © ayahanisha4
//@version=4
strategy("Coinbook", overlay=true, initial_capital=1000, pyramiding=1, default_qty_type=strategy.cash, default_qty_value=1000)
selltrigger = 0
selltrigger := nz(selltrigger[1])
if close[1] < sma(close[1], 50) and sma(close[1], 50) < sma(close[1], 100) and sma(close[1], 100) < sma(close[1], 200) and (close >= sma(close, 50) or sma(close, 50) >= sma(close, 100) or sma(close, 100) >= sma(close, 200))
strategy.entry("Buy", strategy.long)
if close > sma(close, 50) and sma(close, 50) > sma(close, 100) and sma(close, 100) > sma(close, 200) and close[1] > sma(close[1], 50) and sma(close[1], 50) > sma(close[1], 100) and sma(close[1], 100) > sma(close[1], 200) and strategy.position_size > 0
selltrigger := 1
if close < sma(close, 50) and selltrigger == 1
strategy.close("Buy")
selltrigger := 0 |
WMX Williams Fractals strategy V4 | https://www.tradingview.com/script/s1UnbQTF-WMX-Williams-Fractals-strategy-V4/ | WMX_Q_System_Trading | https://www.tradingview.com/u/WMX_Q_System_Trading/ | 421 | 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/
// © WMX_Q_System_Trading
//@version=4
SystemName="WMX Williams Fractals strategy V4"
InitCapital = 1000000
InitPosition = 100
InitCommission = 0.075
InitPyramidMax = 10
strategy(title=SystemName, shorttitle=SystemName, overlay=true, initial_capital=InitCapital, default_qty_type=strategy.percent_of_equity, default_qty_value=InitPosition, commission_type=strategy.commission.percent, commission_value=InitCommission)
//study("WMX Williams Fractals", shorttitle="WMX Fractals", format=format.price, precision=0, overlay=true)
// Define "n" as the number of periods and keep a minimum value of 2 for error handling.
n = input(title="Periods", defval=2, minval=2, type=input.integer)
nn=barstate.isrealtime?1:0
h=close[nn]
l=close[nn]
factorh(High)=>
upFractal = ( (High[n+2] < High[n]) and (High[n+1] < High[n]) and (High[n-1] < High[n]) and (High[n-2] < High[n]))
or ( (High[n+3] < High[n]) and (High[n+2] < High[n]) and (High[n+1] == High[n]) and (High[n-1] < High[n]) and (High[n-2] < High[n]))
or ( (High[n+4] < High[n]) and (High[n+3] < High[n]) and (High[n+2] == High[n]) and (High[n+1] <= High[n]) and (High[n-1] < High[n]) and (High[n-2] < High[n]))
or ( (High[n+5] < High[n]) and (High[n+4] < High[n]) and (High[n+3] == High[n]) and (High[n+2] == High[n]) and (High[n+1] <= High[n]) and (High[n-1] < High[n]) and (High[n-2] < High[n]))
or ((High[n+6] < High[n]) and (High[n+5] < High[n]) and (High[n+4] == High[n]) and (High[n+3] <= High[n]) and (High[n+2] == High[n]) and (High[n+1] <= High[n]) and (High[n-1] < High[n]) and (High[n-2] < High[n]))
upFractal
upFractal=factorh(h)
factorl(Low)=>
dnFractal = ( (Low[n+2] > Low[n]) and (Low[n+1] > Low[n]) and (Low[n-1] > Low[n]) and (Low[n-2] > Low[n]))
or ( (Low[n+3] > Low[n]) and (Low[n+2] > Low[n]) and (Low[n+1] == Low[n]) and (Low[n-1] > Low[n]) and (Low[n-2] > Low[n]))
or ( (Low[n+4] > Low[n]) and (Low[n+3] > Low[n]) and (Low[n+2] == Low[n]) and (Low[n+1] >= Low[n]) and (Low[n-1] > Low[n]) and (Low[n-2] > Low[n]))
or ( (Low[n+5] > Low[n]) and (Low[n+4] > Low[n]) and (Low[n+3] == Low[n]) and (Low[n+2] == Low[n]) and (Low[n+1] >= Low[n]) and (Low[n-1] > Low[n]) and (Low[n-2] > Low[n]))
or ((Low[n+6] > Low[n]) and (Low[n+5] > Low[n]) and (Low[n+4] == Low[n]) and (Low[n+3] >= Low[n]) and (Low[n+2] == Low[n]) and (Low[n+1] >= Low[n]) and (Low[n-1] > Low[n]) and (Low[n-2] > Low[n]))
dnFractal=factorl(l)
U=valuewhen(upFractal[0]!= upFractal[1],l[0],3)
L=valuewhen(dnFractal[0]!=dnFractal[1],h[0],3)
plot(U)
plot(L)
longcon=crossover(close ,L) and close>open
shortcon=crossunder(close ,U) and close<open
if longcon
strategy.entry("Long", strategy.long, when = strategy.position_size <= 0 )
if shortcon
strategy.entry("Short", strategy.short, when = strategy.position_size >= 0 )
|
Coinbook Statergy By Shakir | https://www.tradingview.com/script/D98tnPdl-Coinbook-Statergy-By-Shakir/ | ayahanisha4 | https://www.tradingview.com/u/ayahanisha4/ | 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/
// © ayahanisha4
//@version=4
strategy("Coinbook", overlay=true, initial_capital=1000, pyramiding=1, default_qty_type=strategy.cash, default_qty_value=1000)
selltrigger = 0
selltrigger := nz(selltrigger[1])
if close[1] < sma(close[1], 50) and sma(close[1], 50) < sma(close[1], 100) and sma(close[1], 100) < sma(close[1], 200) and (close >= sma(close, 50) or sma(close, 50) >= sma(close, 100) or sma(close, 100) >= sma(close, 200))
strategy.entry("Buy", strategy.long)
if close > sma(close, 50) and sma(close, 50) > sma(close, 100) and sma(close, 100) > sma(close, 200) and close[1] > sma(close[1], 50) and sma(close[1], 50) > sma(close[1], 100) and sma(close[1], 100) > sma(close[1], 200) and strategy.position_size > 0
selltrigger := 1
if close < sma(close, 50) and selltrigger == 1
strategy.close("Buy")
selltrigger := 0 |
Estamina Trend Strategy By KrisWaters | https://www.tradingview.com/script/ApSMHuLH-Estamina-Trend-Strategy-By-KrisWaters/ | kriswaters | https://www.tradingview.com/u/kriswaters/ | 109 | 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/
// © kriswaters
//@version=4
strategy("Estamina Trend Strategy By KrisWaters",overlay=true,precision=8,pyramiding=0,default_qty_type=strategy.percent_of_equity,default_qty_value=100,currency='USD',commission_type= strategy.commission.percent,commission_value=0.075,initial_capital=1000)
fastMaPeriod = input(4,title="fastMaPeriod")
smoothedMaPeriod = input(8,title="smoothedMaPeriod")
slowMaPeriod = input(15,title="slowMaPeriod")
fastMaValue = sma(close,fastMaPeriod)
smoothedMaValue = 0.0
smoothedMaValue := na(smoothedMaValue[1]) ? sma(close, smoothedMaPeriod) : (smoothedMaValue[1] * (smoothedMaPeriod - 1) + close) / smoothedMaPeriod
slowMaValue = sma(close,slowMaPeriod)
plot(fastMaValue,title="Fast MA Value",color=color.purple,linewidth=3)
plot(smoothedMaValue,title="Smoothed MA Value",color=color.orange,linewidth=3)
plot(slowMaValue,title="Slow MA Value",color=color.green,linewidth=3)
if fastMaValue > smoothedMaValue and fastMaValue > slowMaValue
strategy.entry("long",strategy.long)
if crossunder(fastMaValue,smoothedMaValue) or crossunder(fastMaValue,slowMaValue)
strategy.close("long") |
Wick Reversal Signal | https://www.tradingview.com/script/Gw34kOrf-Wick-Reversal-Signal/ | adiwajshing | https://www.tradingview.com/u/adiwajshing/ | 67 | 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/
// © adiwajshing
//@version=4
strategy("Wick Reversal Signal", overlay=true)
wickMultiplier = input(3.25)
bodyPercentage = input(0.35)
barsBack = input(50)
bodyMultiplier = input(1.1)
myCandleSize = high-low
averageCandleSize = rma(myCandleSize, barsBack)
longSignal = close > open and open-low >= (close-open)*wickMultiplier and high-close <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier
longSignal := longSignal or (close < open and close-low >= (open-close)*wickMultiplier and high-close <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier)
longSignal := longSignal or (abs(close-open) < 0.01 and close != high and high-low >= (high-close)*wickMultiplier and high-close <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier)
shortSignal = close < open and high-open >= (open-close)*wickMultiplier and close-low <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier
shortSignal := shortSignal or (close > open and high-close >= (close-open)*wickMultiplier and close-low <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier)
shortSignal := shortSignal or (abs(close-open) < 0.01 and close != low and high-low >= (close-low)*wickMultiplier and close-low <= (high-low)*bodyPercentage and high-low >= averageCandleSize*bodyMultiplier)
plotshape(longSignal, style=shape.triangleup, size=size.normal)
plotshape(shortSignal, style=shape.triangledown, size=size.normal)
strategy.entry("LONG", strategy.long, when=longSignal)
strategy.entry("SHORT", strategy.short, when=shortSignal) |