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
|
---|---|---|---|---|---|---|---|---|
T3+SMA | https://www.tradingview.com/script/jRdVqF5E-T3-SMA/ | 03.freeman | https://www.tradingview.com/u/03.freeman/ | 243 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 03.freeman
//This strategy is based only on T3 moving average, but uses sma 200 as filter for enter long or short.
//The default settings considers a daily timeframe.
//The tsrategy is very simple: long if T3 increase, short if T3 decrease.
//Note that if you set volume factor to 0 you will have an exponential moving average, while if you set to 1 you'll get a DEMA.
//@version=4
strategy("T3+SMA", overlay=true)
//INPUTS
smaLength=input(200,"SMA period")
T3Length=input(7,"T3 Moving average period")
source=input(close,"Source")
smaFilter=input(true,"Use sma only as filter?")
vFactor = input(0.7,"T3 volume factor (between 0-1)",minval=0, maxval=1)
exitT3 = input(true,"Use T3 for exit signal")
t3_funct(src, length) =>
ema(src, length) * (1+vFactor) - ema(ema(src, length), length) * vFactor
t3 = t3_funct(t3_funct(t3_funct(source, T3Length), T3Length), T3Length)
plot(sma(close, smaLength),"SMA",color.orange)
plot(t3,"T3",t3 > t3[1] ? color.green : color.red)
longCondition = smaFilter?(t3 > t3[1] and close>sma(close, smaLength)) :crossover(t3, sma(close, smaLength))
exitlong = t3 < t3[1]
if (longCondition)
strategy.entry("T3 Long", strategy.long)
strategy.close("T3 Long", when=exitlong and exitT3)
shortCondition = smaFilter?(t3 < t3[1] and close<sma(close, smaLength)) :crossunder(t3, sma(close, smaLength))
exitshort = t3 > t3[1]
if (shortCondition)
strategy.entry("T3 Short", strategy.short)
strategy.close("T3 Short", when=exitshort and exitT3)
|
CryptOli 3 MAs long/short Backtest | https://www.tradingview.com/script/zPqgsHrb-CryptOli-3-MAs-long-short-Backtest/ | Crypto-Oli | https://www.tradingview.com/u/Crypto-Oli/ | 61 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Crypto-Oli
//@version=4
strategy("CryptOli 3 MAs long/short Backtest", initial_capital=5000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, overlay=true)
// this is an educational Script - basicly its very simple - you can see how minimal changes impact results, thats why i posted it
// Credits to Quantnomad to publish tons of free educational script
// this Script is based on https://www.tradingview.com/script/0NgUadGr-Ultimate-MA-Cross-Indicator/ Quantnomads Ultimate MA Indicator
// HA - Option for calcucaltion based on HA-Candles (very famous recently)
// Source Input - Option (Candletype for calculation, close, ohlc4 ect.) --- there are huge differences --- try it by your own
////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
// From Date Inputs
fromDay = input(defval=1, title="From Day", minval=1, maxval=31)
fromMonth = input(defval=1, title="From Month", minval=1, maxval=12)
fromYear = input(defval=2015, title="From Year", minval=1970)
// To Date Inputs
toDay = input(defval=1, title="To Day", minval=1, maxval=31)
toMonth = input(defval=1, title="To Month", minval=1, maxval=12)
toYear = input(defval=2020, title="To Year", minval=1970)
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
////////////////////////////////////////////////////////////////////////////////
h = input(false, title = "Signals from Heikin Ashi Candles")
ma_type = input(title = "MA Type", type = input.string, defval = "SMMA", options = ['SMA', 'EMA', 'WMA', 'VWMA', 'HMA', 'SMMA', 'DEMA'])
src = input(ohlc4)
short_ma_len = input(title = "Short MA Length", type = input.integer, defval = 7, minval = 1)
short_ma_src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, src, lookahead = false) : close
middle_ma_len = input(title = "Middle MA Length", type = input.integer, defval = 13, minval = 2)
middle_ma_src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, src, lookahead = false) : close
long_ma_len = input(title = "Long MA Length", type = input.integer, defval = 21, minval = 2)
long_ma_src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, src, lookahead = false) : close
tick_round(x) =>
round(x / syminfo.mintick) * syminfo.mintick
// Set initial values to 0
short_ma = 0.0
middle_ma = 0.0
long_ma = 0.0
// Simple Moving Average (SMA)
if ma_type == 'SMA'
short_ma := sma(short_ma_src, short_ma_len)
middle_ma := sma(middle_ma_src, middle_ma_len)
long_ma := sma(long_ma_src, long_ma_len)
// Exponential Moving Average (EMA)
if ma_type == 'EMA'
short_ma := ema(short_ma_src, short_ma_len)
middle_ma := ema(middle_ma_src, middle_ma_len)
long_ma := ema(long_ma_src, long_ma_len)
// Weighted Moving Average (WMA)
if ma_type == 'WMA'
short_ma := wma(short_ma_src, short_ma_len)
middle_ma := wma(middle_ma_src, middle_ma_len)
long_ma := wma(long_ma_src, long_ma_len)
// Hull Moving Average (HMA)
if ma_type == 'HMA'
short_ma := wma(2*wma(short_ma_src, short_ma_len/2)-wma(short_ma_src, short_ma_len), round(sqrt(short_ma_len)))
middle_ma := wma(2*wma(middle_ma_src, middle_ma_len/2)-wma(middle_ma_src, middle_ma_len), round(sqrt(middle_ma_len)))
long_ma := wma(2*wma(long_ma_src, long_ma_len /2)-wma(long_ma_src, long_ma_len), round(sqrt(long_ma_len)))
// Volume-weighted Moving Average (VWMA)
if ma_type == 'VWMA'
short_ma := vwma(short_ma_src, short_ma_len)
middle_ma := vwma(middle_ma_src, middle_ma_len)
long_ma := vwma(long_ma_src, long_ma_len)
// Smoothed Moving Average (SMMA)
if ma_type == 'SMMA'
short_ma := na(short_ma[1]) ? sma(short_ma_src, short_ma_len) : (short_ma[1] * (short_ma_len - 1) + short_ma_src) / short_ma_len
middle_ma := na(middle_ma[1]) ? sma(middle_ma_src, middle_ma_len) : (middle_ma[1] * (middle_ma_len - 1) + middle_ma_src) / middle_ma_len
long_ma := na(long_ma[1]) ? sma(long_ma_src, long_ma_len) : (long_ma[1] * (long_ma_len - 1) + long_ma_src) / long_ma_len
// Double Exponential Moving Average (DEMA)
if ma_type == 'DEMA'
e1_short = ema(short_ma_src, short_ma_len)
e1_middle = ema(middle_ma_src, middle_ma_len)
e1_long = ema(long_ma_src, long_ma_len)
short_ma := 2 * e1_short - ema(e1_short, short_ma_len)
middle_ma := 2 * e1_middle - ema(e1_middle, middle_ma_len)
long_ma := 2 * e1_long - ema(e1_long, long_ma_len)
// Plot MAs
plot(short_ma, color = color.green, linewidth = 1)
plot(middle_ma, color = color.yellow, linewidth = 1)
plot(long_ma, color = color.red, linewidth = 1)
if close>long_ma and short_ma>middle_ma and time_cond
strategy.entry("Long", strategy.long)
if close<long_ma and short_ma<middle_ma and time_cond
strategy.entry("Short", strategy.short)
|
Volatility stop strategy | https://www.tradingview.com/script/u9Y3XVL1-volatility-stop-strategy/ | laptevmaxim92 | https://www.tradingview.com/u/laptevmaxim92/ | 146 | 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/
// © laptevmaxim92
//@version=4
strategy("Volatility stop strategy", overlay=true)
length = input(20)
mult = input(2, step = 0.1)
utp = input(false, "Use take profit?")
pr = input(100, "Take profit pips")
usl = input(false, "Use stop loss?")
sl = input(100, "Stop loss pips")
fromday = input(01, defval=01, minval=01, maxval=31, title="From Day")
frommonth = input(01, defval=01, minval= 01, maxval=12, title="From Month")
fromyear = input(2000, minval=1900, maxval=2100, title="From Year")
today = input(31, defval=01, minval=01, maxval=31, title="To Day")
tomonth = input(12, defval=12, minval=01, maxval=12, title="To Month")
toyear = input(2019, minval=1900, maxval=2100, title="To Year")
use_date = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))
atr_ = atr(length)
max_ = 0.0
min_ = 0.0
max1 = 0.0
max1 := max(nz(max_[1]), close)
min1 = 0.0
min1 := min(nz(min_[1]), close)
vstop = 0.0
is_uptrend = false
is_uptrend_prev = false
is_uptrend_prev := nz(is_uptrend[1], true)
stop = is_uptrend_prev ? max1 - mult * atr_ : min1 + mult * atr_
vstop_prev = nz(vstop[1])
vstop1 = is_uptrend_prev ? max(vstop_prev, stop) : min(vstop_prev, stop)
is_uptrend := close - vstop1 >= 0
is_trend_changed = is_uptrend != is_uptrend_prev
max_ := is_trend_changed ? close : max1
min_ := is_trend_changed ? close : min1
vstop := is_trend_changed ? is_uptrend ? max_ - mult * atr_ : min_ + mult * atr_ : vstop1
plot(vstop, color = is_uptrend ? color.green : color.red, linewidth=2)
longCondition = is_uptrend
if (longCondition and use_date)
strategy.entry("BUY", strategy.long)
shortCondition = not is_uptrend
if (shortCondition and use_date)
strategy.entry("SELL", strategy.short)
if (utp and not usl)
strategy.exit("TP", "BUY", profit = pr)
strategy.exit("TP", "SELL", profit = pr)
if (usl and not utp)
strategy.exit("SL", "BUY", loss = sl)
strategy.exit("SL", "SELL", loss = sl)
if (usl and utp)
strategy.exit("TP/SL", "BUY", loss = sl, profit = pr)
strategy.exit("TP/SL", "SELL", loss = sl, profit = pr) |
Ichimoku Kinko Hyo Cloud - no offset - no repaint - strategy | https://www.tradingview.com/script/MGSCiuSP-Ichimoku-Kinko-Hyo-Cloud-no-offset-no-repaint-strategy/ | KryptoNight | https://www.tradingview.com/u/KryptoNight/ | 1,490 | 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.USD, initial_capital = 10000, 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.075)
// ==============================================================================
// ------------------------------------------------------------------------------
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(26, 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")
// ==============================================================================
|
Leverage Strategy and a few words on risk/opportunity | https://www.tradingview.com/script/vOaKc2FV-Leverage-Strategy-and-a-few-words-on-risk-opportunity/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 542 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=4
//@author=Daveatt
// Breakout on 2H high/low break Strategy
SystemName = "Leverage Strategy"
TradeId = "🙏"
InitCapital = 100000
InitPosition = 100
UseMarginCall = input(true, title="Use Margin Call?")
MarginValue = input(25000, title="Margin Value", type=input.float)
// use 1 for no leverage
// use 0.1 for be underleveraged and bet 1/10th of a pip value
// use any value > 1 for full-degen mode
UseLeverage = input(true, title="Use Leverage")
LeverageValue = input(4, title="Leverage mult (1 for no leverage)", minval=0.1, type=input.float)
// Risk Management
UseRiskManagement = input(true, title="Use Risk Management?")
// ticks = 1/10th of a pip value
StopLoss = input(5, title="Stop Loss in ticks value", type=input.float)
TakeProfit = input(500, title="Take Profit in ticks value", type=input.float)
InitCommission = 0.075
InitPyramidMax = 1
CalcOnorderFills = false
CalcOnTick = true
DefaultQtyType = strategy.cash
DefaultQtyValue = strategy.cash
Currency = currency.USD
Precision = 2
Overlay=false
MaxBarsBack=3000
strategy
(
title=SystemName,
shorttitle=SystemName,
overlay=Overlay,
pyramiding=InitPyramidMax,
initial_capital=InitCapital,
default_qty_type=DefaultQtyType,
default_qty_value=InitPosition,
commission_type=strategy.commission.percent,
commission_value=InitCommission,
calc_on_order_fills=CalcOnorderFills,
calc_on_every_tick=CalcOnTick,
currency = Currency,
precision=Precision,
max_bars_back=MaxBarsBack
)
//////////////////////////// UTILITIES ///////////////////////////
f_print(_txt, _condition) =>
var _lbl = label(na)
label.delete(_lbl)
if _condition
// saving the candle where we got rekt :(
_index = barssince(_condition)
_lbl := label.new(bar_index - _index, highest(100), _txt, xloc.bar_index, yloc.price, size = size.normal, style=label.style_labeldown)
//////////////////////////// STRATEGY LOGIC ///////////////////////////
// Date filterigng
_Date = input(true, title="[LABEL] DATE")
FromYear = input(2019, "From Year", minval=1900), FromMonth = input(12, "From Month", minval=1, maxval=12), FromDay = input(1, "From Day", minval=1, maxval=31)
ToYear = input(2019, "To Year", minval=1900), ToMonth = input(12, "To Month", minval=1, maxval=12), ToDay = input(9, "To Day", minval=1, maxval=31)
FromDate = timestamp(FromYear, FromMonth, FromDay, 00, 00)
ToDate = timestamp(ToYear, ToMonth, ToDay, 23, 59)
TradeDateIsAllowed = (time >= FromDate and time <= ToDate)
// non-repainting security version
four_hours_H = security(syminfo.tickerid, '240', high[1], lookahead=true)
four_hours_L = security(syminfo.tickerid, '240', low[1], lookahead=true)
buy_trigger = crossover(close, four_hours_H)
sell_trigger = crossunder(close, four_hours_L)
// trend states
since_buy = barssince(buy_trigger)
since_sell = barssince(sell_trigger)
buy_trend = since_sell > since_buy
sell_trend = since_sell < since_buy
change_trend = (buy_trend and sell_trend[1]) or (sell_trend and buy_trend[1])
// plot(four_hours_H, title="4H High", linewidth=2, color=#3c91c2, style=plot.style_linebr, transp=0,
// show_last=1, trackprice=true)
// plot(four_hours_L, title="4H Low", linewidth=2, color=#3c91c2, style=plot.style_linebr, transp=0,
// show_last=1, trackprice=true)
plot(strategy.equity, color=color.blue, linewidth=3, title="Strategy Equity")
// get the entry price
entry_price = valuewhen(buy_trigger or sell_trigger, close, 0)
// SL and TP
SL_price = buy_trend ? entry_price - StopLoss : entry_price + StopLoss
is_SL_hit = buy_trend ? crossunder(low, SL_price) : crossover(high, SL_price)
TP_price = buy_trend ? entry_price + TakeProfit : entry_price - TakeProfit
is_TP_hit = buy_trend ? crossover(high, TP_price) : crossunder(low, TP_price)
// Account Margin Management:
f_account_margin_call_cross(_amount)=>
_return = crossunder(strategy.equity, _amount)
f_account_margin_call(_amount)=>
_return = strategy.equity <= _amount
is_margin_call_cross = f_account_margin_call_cross(MarginValue)
is_margin_call = f_account_margin_call(MarginValue)
plot(strategy.equity, title='strategy.equity', transp=0, linewidth=4)
//plot(barssince(is_margin_call ), title='barssince(is_margin_call)', transp=100)
can_trade = iff(UseMarginCall, not is_margin_call, true)
trade_size = InitPosition * (not UseLeverage ? 1 : LeverageValue)
// We can take the trade if not liquidated/margined called/rekt
buy_final = can_trade and buy_trigger and TradeDateIsAllowed
sell_final = can_trade and sell_trigger and TradeDateIsAllowed
close_long = buy_trend and
(UseRiskManagement and (is_SL_hit or is_TP_hit)) or sell_trigger
close_short = sell_trend and
(UseRiskManagement and (is_SL_hit or is_TP_hit)) or buy_trigger
strategy.entry(TradeId + ' B', long=true, qty=trade_size, when=buy_final)
strategy.entry(TradeId + ' S', long=false, qty=trade_size, when=sell_final)
strategy.close(TradeId + ' B', when=close_long)
strategy.close(TradeId + ' S', when=close_short)
// FULL DEGEN MODE ACTIVATED
// Margin called - Broker closing your account
strategy.close_all(when=is_margin_call)
if UseMarginCall and is_margin_call_cross
f_print("☠️REKT☠️", is_margin_call_cross)
|
Simple RSI Strategy Buy/Sell at a certain level | https://www.tradingview.com/script/ZhEP9D9i-Simple-RSI-Strategy-Buy-Sell-at-a-certain-level/ | Bitduke | https://www.tradingview.com/u/Bitduke/ | 343 | 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/
// © Bitduke
//@version=4
strategy("Simple RSI Buy/Sell at a level", shorttitle="Simple RSI Strategy", overlay=true,calc_on_every_tick=false,pyramiding=0, default_qty_type=strategy.cash,default_qty_value=1000, currency=currency.USD, initial_capital=1000,commission_type=strategy.commission.percent, commission_value=0.075)
overbought = input(70, title="overbought value")
oversold = input(30, title="oversold value")
myrsi = rsi(close, 14) > overbought
myrsi2 = rsi(close, 14) < oversold
barcolor(myrsi ? color.black : na)
barcolor(myrsi2 ? color.blue : na)
strategy.entry("Buy Signal",strategy.long, when = myrsi)
strategy.entry("Sell Signal",strategy.short, when = myrsi2) |
Simple EMA_Hull_RSI Strategy | https://www.tradingview.com/script/exMcL6PB-Simple-EMA-Hull-RSI-Strategy/ | Bitduke | https://www.tradingview.com/u/Bitduke/ | 76 | 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/
// © Bitduke
//@version=4
strategy(shorttitle="EHR", title="Simple EMA_Hull_RSI", overlay=false,
calc_on_every_tick=false, pyramiding=0, default_qty_type=strategy.cash,
default_qty_value=1000, currency=currency.USD, initial_capital=1000,
commission_type=strategy.commission.percent, commission_value=0.075)
// EMA
len = input(minval=1, title="EMA Length", defval=50)
src = input(close, title="EMA Source")
final_ema = ema(src, len)
plot(final_ema, color=color.red, title="EMA")
overbought = input(60, title="overbought value")
oversold = input(45, title="oversold value")
overbought_signal = rsi(close, 14) > overbought
oversold_signal = rsi(close, 14) < oversold
barcolor(overbought_signal ? color.black : na)
barcolor(oversold_signal ? color.blue : na)
// Hull MA
n = input(title="Hull Length", defval=7)
n2ma=2*wma(close,round(n/2))
nma=wma(close,n)
diff=n2ma-nma
sqn=round(sqrt(n))
n2ma1=2*wma(close[1],round(n/2))
nma1=wma(close[1],n)
diff1=n2ma1-nma1
sqn1=round(sqrt(n))
n1=wma(diff,sqn)
n2=wma(diff1,sqn)
c=n1>n2?color.green:color.red
ma=plot(n1,color=c)
// Strategy Logic
longCondition = overbought_signal and crossover(n1,final_ema)
shortCondition = oversold_signal and crossover(final_ema,n1)
strategy.entry("EHR_Long", strategy.long, when=longCondition)
strategy.entry("EHR_Short", strategy.short, when=shortCondition)
|
Mean Reversion Strategy by KrisWaters | https://www.tradingview.com/script/30AJfvAa-Mean-Reversion-Strategy-by-KrisWaters/ | kriswaters | https://www.tradingview.com/u/kriswaters/ | 256 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kriswaters
//@version=4
strategy("Mean Reversion Strategy by KrisWaters",overlay=false,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)
maPeriod = input(defval=6,title="SMA Period")
dropRate = input(defval=1,title="Drop Rate",type=input.float,step=0.1)
rateOfChange = (change(close)/close)*100
changeMovAvg = sma(rateOfChange,maPeriod)
//#### CONDITIONS ####
if changeMovAvg > changeMovAvg[1] and changeMovAvg[1] < (-1)*dropRate and volume[1] < volume and strategy.position_size == 0
strategy.entry("buy",strategy.long)
if changeMovAvg > 0 and volume[1] > volume and strategy.position_size > 0
strategy.close("buy")
//#### PLOTS ####
plot(changeMovAvg,linewidth=3,color=changeMovAvg > 0 ? color.green : color.red,style=plot.style_columns,transp=0)
plot(0,linewidth=3,color=color.black)
plot(-1*dropRate,linewidth=3,color=color.red,style=plot.style_line)
|
ATR Strategy FOREX for long only with market filter | https://www.tradingview.com/script/O2EJEYKm/ | Investoz | https://www.tradingview.com/u/Investoz/ | 81 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Investoz
//@version=4
strategy("ATR Strategy FOREX", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
len = input(26, type=input.integer, minval=1, title="Length")
mul = input(2.618, type=input.float, minval=0, title="Length")
mullow = input(2.386, type=input.float, minval=0, title="Length")
price = sma(close, 1)
average = ema(close, len)
diff = atr(len) * mul
difflow = atr(len) * mullow
bull_level = average + diff
bear_level = average - difflow
bull_cross = crossunder(price, bear_level)
bear_cross = crossunder(bull_level, price)
FromMonth = input(defval = 8, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 18, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2008, title = "From Year", minval = 2008)
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 = 2020, title = "To Year", minval = 2019)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
startTimeOk() => time >= start and time <= finish ? true : false
if (startTimeOk()) and ema(close,1) > ema(close,528)
strategy.entry("KOP", strategy.long, when=bull_cross)
strategy.close("KOP", when=bear_cross)
//if (startTimeOk()) and ema(close,1) < ema(close,528)
// strategy.entry("SALJ", strategy.short, when=bear_cross)
// strategy.close("SALJ", when=bull_cross)
plot(price, title="price", color=color.black, transp=50, linewidth=2)
a0 = plot(average, title="average", color=color.red, transp=50, linewidth=1)
a1 = plot(bull_level, title="bull", color=color.green, transp=50, linewidth=1)
a2 = plot(bear_level, title="bear", color=color.red, transp=50, linewidth=1)
fill(a0, a1, color=color.green, transp=97)
fill(a0, a2, color=color.red, transp=97) |
SuPeR-RePaNoCHa #2TP# | https://www.tradingview.com/script/GhIu10zW/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 1,301 | 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(title = "SuPeR-RePaNoCHa #2TP#", overlay = true, initial_capital = 10000, pyramiding = 100, currency = "USD",
calc_on_order_fills = false, calc_on_every_tick = false, default_qty_type = strategy.fixed, default_qty_value = 1, commission_value = 0.03)
//study(title="SuPeR-RePaNoCHa #2TP#", overlay=true)
// ================================================================================================================================================================================
// VARIABLES
// ================================================================================================================================================================================
// Long/Short
var bool longCond = na, var bool shortCond = na, longCond := nz(longCond[1]), shortCond := nz(shortCond[1])
var bool XlongCond = na, var bool XshortCond = na, XlongCond := nz(XlongCond[1]), XshortCond := nz(XshortCond[1])
var int CondIni_long0 = 0, var int CondIni_short0 = 0, CondIni_long0 := nz(CondIni_long0[1]), CondIni_short0 := nz(CondIni_short0[1])
var int CondIni_long = 0, var int CondIni_short = 0, CondIni_long := nz(CondIni_long[1]), CondIni_short := nz(CondIni_short[1])
var int CondIniX0 = 0, var int CondIniX = 0, CondIniX0 := nz(CondIniX0[1]), CondIniX := nz(CondIniX[1])
var bool Final_longCondition0 = na, var bool Final_shortCondition0 = na, Final_longCondition0 := nz(Final_longCondition0[1]), Final_shortCondition0 := nz(Final_shortCondition0[1])
var bool Final_longCondition = na, var bool Final_shortCondition = na, Final_longCondition := nz(Final_longCondition[1]), Final_shortCondition := nz(Final_shortCondition[1])
var bool BT_Final_longCondition = na, var bool BT_Final_shortCondition = na, BT_Final_longCondition := nz(BT_Final_longCondition[1]), BT_Final_shortCondition := nz(BT_Final_shortCondition[1])
var float last_open_longCondition = na, var float last_open_shortCondition = na
var int last_longCondition0 = na, var int last_shortCondition0 = na
var int last_longCondition = na, var int last_shortCondition = na
var int last_XlongCondition0 = na, var int last_XshortCondition0 = na
var int last_XlongCondition = na, var int last_XshortCondition = na
var int nLongs = na, var int nShorts = na, nLongs := nz(nLongs[1]), nShorts := nz(nShorts[1])
// Xlong/Xshort
var bool Final_XlongCondition0 = na, var bool Final_XshortCondition0 = na, Final_XlongCondition0 := nz(Final_XlongCondition0[1]), Final_XshortCondition0 := nz(Final_XshortCondition0[1])
var bool Final_XlongCondition = na, var bool Final_XshortCondition = na, Final_XlongCondition := nz(Final_XlongCondition[1]), Final_XshortCondition := nz(Final_XshortCondition[1])
var int CondIni_Xlong0 = 0, var int CondIni_Xshort0 = 0, CondIni_Xlong0 := nz(CondIni_Xlong0[1]), CondIni_Xshort0 := nz(CondIni_Xshort0[1])
var int CondIni_Xlong = 0, var int CondIni_Xshort = 0, CondIni_Xlong := nz(CondIni_Xlong[1]), CondIni_Xshort := nz(CondIni_Xshort[1])
// Take profit
var bool long_tp = na, var bool short_tp = na
var bool long_tp2 = na, var bool short_tp2 = na
var bool long_tp_pump_last_minute = na, var bool short_tp_pump_last_minute = na
var bool long_tp_pump = na, var bool short_tp_pump = na
var int last_long_tp = na, var int last_short_tp = na
var int last_long_tp_pump = na, var int last_short_tp_pump = na
var int last_long_tp2 = na, var int last_short_tp2 = na
var bool Final_Long_tp = na, var bool Final_Short_tp = na, Final_Long_tp := nz(Final_Long_tp[1]), Final_Short_tp := nz(Final_Short_tp[1])
var bool Final_Long_tp2 = na, var bool Final_Short_tp2 = na, Final_Long_tp2 := nz(Final_Long_tp2[1]), Final_Short_tp2 := nz(Final_Short_tp2[1])
var bool Final_Long_tp_pump = na, var bool Final_Short_tp_pump = na
// Stop Loss
var int CondIni_long_sl = 0, var int CondIni_short_sl = 0
var bool Final_Long_sl0 = na, var bool Final_Short_sl0 = na, Final_Long_sl0 := nz(Final_Long_sl0[1]), Final_Short_sl0 := nz(Final_Short_sl0[1])
var bool Final_Long_sl = na, var bool Final_Short_sl = na, Final_Long_sl := nz(Final_Long_sl[1]), Final_Short_sl := nz(Final_Short_sl[1])
var int last_long_sl = na, var int last_short_sl = na
// Indicators
var bool JMA_longCond = na, var bool JMA_shortCond = na
var bool RF_longCond = na, var bool RF_shortCond = na
var bool ADX_longCond = na, var bool ADX_shortCond = na
var bool SAR_longCond = na, var bool SAR_shortCond = na
var bool RSI_longCond = na, var bool RSI_shortCond = na
var bool MACD_longCond = na, var bool MACD_shortCond = na
var bool VOL_longCond = na, var bool VOL_shortCond = na
var bool JMA_XlongCond = na, var bool JMA_XshortCond = na
var bool RF_XlongCond = na, var bool RF_XshortCond = na
var bool ADX_XlongCond = na, var bool ADX_XshortCond = na
var bool SAR_XlongCond = na, var bool SAR_XshortCond = na
// ================================================================================================================================================================================
// INITIAL SETTINGS
// ================================================================================================================================================================================
// Market side and source inputs
Position = input("BOTH", "LONG / SHORT", options = ["BOTH","LONG","SHORT"])
src = hlc3
is_Long = Position == "SHORT" ? na : true
is_Short = Position == "LONG" ? na : true
// ================================================================================================================================================================================
// JURIK MOVING AVERAGE
// ================================================================================================================================================================================
// JMA inputs
Act_JMA = input(true, "JURIK MOVING AVERAGE")
length = input(22, title="JMA LENGTH", type=input.integer, minval = 0)
phase = input(22, title="JMA PHASE", type=input.integer, minval = 0)
power = input(2, title="JMA POWER", type=input.float, minval = 0, step = 0.5)
// JMA calculation
JMA(src)=>
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = pow(beta, power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * pow(1 - alpha, 2) + pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
// Defining JMA trend
JMA_Rising = JMA(src) > JMA(src)[1]
JMA_Falling = JMA(src) < JMA(src)[1]
// JMA Plotting
JMA_color = JMA_Rising ? color.green : JMA_Falling ? color.red : color.yellow
plot(Act_JMA ? JMA(src) : na, color=JMA_color, linewidth = 3, title= "JMA")
// ================================================================================================================================================================================
// RANGE FILTER
// ================================================================================================================================================================================
// Range Filter inputs
Act_RF = input(true, "RANGE FILTER")
per = input(defval=42, title="SAMPLING PERIOD", minval=1)
mult = input(defval=1.5, title="RANGE MULTIPLIER", minval=0.1, step = 0.1)
// Range Filter calculation
Range_filter(_src, _per, _mult)=>
var float _upward = 0.0
var float _downward = 0.0
wper = (_per*2) - 1
avrng = ema(abs(_src - _src[1]), _per)
_smoothrng = ema(avrng, wper)*_mult
_filt = _src
_filt := _src > nz(_filt[1]) ? ((_src-_smoothrng) < nz(_filt[1]) ? nz(_filt[1]) : (_src-_smoothrng)) : ((_src+_smoothrng) > nz(_filt[1]) ? nz(_filt[1]) : (_src+_smoothrng))
_upward := _filt > _filt[1] ? nz(_upward[1]) + 1 : _filt < _filt[1] ? 0 : nz(_upward[1])
_downward := _filt < _filt[1] ? nz(_downward[1]) + 1 : _filt > _filt[1] ? 0 : nz(_downward[1])
[_smoothrng,_filt,_upward,_downward]
// Defining variables for include in future conditions
[smoothrng, filt, upward, downward] = Range_filter(src, per, mult)
// Defining high and low bands
hband = filt + smoothrng
lband = filt - smoothrng
// Range Filter Plotting
filtcolor = upward > 0 ? color.lime : downward > 0 ? color.red : color.orange
filtplot = plot(Act_RF ? filt : na, color = filtcolor, linewidth = 3, title="Range Filter", editable = false)
hbandplot = plot(Act_RF ? hband : na, color = color.aqua, transp = 60, title = "High Target", editable = false)
lbandplot = plot(Act_RF ? lband : na, color = color.aqua, transp = 60, title = "Low Target", editable = false)
fill(hbandplot, filtplot, color = color.aqua, title = "High Target Range", editable = false)
fill(lbandplot, filtplot, color = color.aqua, title = "Low Target Range", editable = false)
// ================================================================================================================================================================================
// ADX
// ================================================================================================================================================================================
// ADX inputs
Act_ADX = input(true, "ORIGINAL AVERAGE DIRECTIONAL INDEX")
ADX_len = input(17, title="ADX LENGTH", type=input.integer, minval = 1)
th = input(17, title="ADX THRESHOLD", type=input.integer, minval = 0)
// ADX calculating
calcADX(_len)=>
up = change(high)
down = -change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = rma(tr, _len)
_plus = fixnan(100 * rma(plusDM, _len) / truerange)
_minus = fixnan(100 * rma(minusDM, _len) / truerange)
sum = _plus + _minus
_adx = 100 * rma(abs(_plus - _minus) / (sum == 0 ? 1 : sum), _len)
[_plus,_minus,_adx]
// Defining variables for include in future conditions
[DIPlus,DIMinus,ADX] = calcADX(ADX_len)
// Plotting ADX bar colors
macol = DIPlus > DIMinus and ADX > th ? color.lime : DIPlus < DIMinus and ADX > th ? color.red : color.orange
barcolor(color = Act_ADX ? macol : na, title = "ADX")
// ================================================================================================================================================================================
// SAR
// ================================================================================================================================================================================
// SAR inputs
Act_SAR = input(true, "PARABOLIC SAR")
Sst = input (0.25, "SAR STAR", step=0.01, minval = 0.01)
Sinc = input (0.5, "SAR INC", step=0.01, minval = 0.01)
Smax = input (0.12, "SAR MAX", step=0.01, minval = 0.01)
// SAR calculation from TV
SAR = sar(Sst, Sinc, Smax)
// SAR Plotting
plot(Act_SAR ? SAR : na, color = macol, style = plot.style_cross, title = "SAR")
// ================================================================================================================================================================================
// RSI VOLUME WEIGHTED
// ================================================================================================================================================================================
// RSI with volume inputs
Act_RSI = input(true, "RSI VOLUME WEIGHTED")
RSI_len = input(29, "RSI LENGHT", minval = 1)
RSI_obos = input(52,title="RSI CENTER LINE", type=input.integer, minval = 1)
// RSI with volume calculation
WiMA(src, length) =>
var float MA_s=0.0
MA_s:=(src + nz(MA_s[1] * (length-1)))/length
MA_s
RSI_Volume(fv, length) =>
up=iff(fv>fv[1],abs(fv-fv[1])*volume,0)
dn=iff(fv<fv[1],abs(fv-fv[1])*volume,0)
upt=WiMA(up,length)
dnt=WiMA(dn,length)
100*(upt/(upt+dnt))
// Defining variable for include in conditions
RSI_V = RSI_Volume(src, RSI_len)
// ================================================================================================================================================================================
// MACD
// ================================================================================================================================================================================
// MACD inputs
Act_MACD = input(true, "MOVING AVERAGE CONVERGENCE / DIVERGENCE")
fast_length = input(8, title="MACD FAST LENGTH", type=input.integer, minval = 1)
slow_length = input(11, title="MACD SLOW LENGTH", type=input.integer, minval = 1)
signal_length = input(10, title="MACD SIGNAL SMOOTHING", type=input.integer, minval = 1, maxval = 50)
// MACD calculation from TV (histogram only)
[_,_,hist] = macd(src,fast_length,slow_length,signal_length)
// ================================================================================================================================================================================
// STRATEGY
// ================================================================================================================================================================================
// Volume inputs for entry conditions
Act_Vol = input(true, "VOLUME CONDITION")
volume_f = input(1.0, "VOLUME FACTOR", minval = 0, step = 0.1)
sma_length = input(35, "SMA VOLUME LENGTH", minval = 1)
// Confirmed/Unconfirmed options input
Act_not_conf = input(true, "UNCONFIRMED FIRST ENTRY 🤞")
Act_not_conf_X = input(false, "UNCONFIRMED XL/XS")
Act_X = input(false, "ACTIVATE XL/XS ON LONG&SHORT MODE")
// All indicators with long conditions and enable/disable option
JMA_longCond := (Act_JMA ? (JMA_Rising) : RF_longCond)
RF_longCond := (Act_RF ? (high > hband and upward > 0) : ADX_longCond)
ADX_longCond := (Act_ADX ? (DIPlus > DIMinus and ADX > th) : SAR_longCond)
SAR_longCond := (Act_SAR ? (SAR < close) : RSI_longCond)
RSI_longCond := (Act_RSI ? (RSI_V > RSI_obos) : MACD_longCond)
MACD_longCond := (Act_MACD ? (hist > 0) : VOL_longCond)
VOL_longCond := (Act_Vol ? (volume > sma(volume,sma_length)*volume_f) : JMA_longCond)
// All indicators with short conditions and enable/disable option
JMA_shortCond := (Act_JMA ? (JMA_Falling) : RF_shortCond)
RF_shortCond := (Act_RF ? (low < lband and downward > 0) : ADX_shortCond)
ADX_shortCond := (Act_ADX ? (DIPlus < DIMinus and ADX > th) : SAR_shortCond)
SAR_shortCond := (Act_SAR ? (SAR > close) : RSI_shortCond)
RSI_shortCond := (Act_RSI ? (RSI_V < RSI_obos) : MACD_shortCond)
MACD_shortCond := (Act_MACD ? (hist < 0) : VOL_shortCond)
VOL_shortCond := (Act_Vol ? (volume > sma(volume,sma_length)*volume_f) : JMA_shortCond)
// Defining long/short condition from indicators + volume
longCond := JMA_longCond and RF_longCond and ADX_longCond and SAR_longCond and RSI_longCond and MACD_longCond and VOL_longCond
shortCond := JMA_shortCond and RF_shortCond and ADX_shortCond and SAR_shortCond and RSI_shortCond and MACD_shortCond and VOL_shortCond
// All indicators with long closing conditions and enable/disable option
JMA_XlongCond := (Act_JMA ? (JMA_Falling) : RF_XlongCond)
RF_XlongCond := (Act_RF ? (low < lband and downward > 0) : ADX_XlongCond)
ADX_XlongCond := (Act_ADX ? (DIPlus > DIMinus and ADX > th) : SAR_XlongCond)
SAR_XlongCond := (Act_SAR ? (SAR > close) : JMA_XlongCond)
// All indicators with short closing conditions and enable/disable option
JMA_XshortCond := (Act_JMA ? (JMA_Rising) : RF_XshortCond)
RF_XshortCond := (Act_RF ? (high > hband and upward > 0) : ADX_XshortCond)
ADX_XshortCond := (Act_ADX ? (DIPlus < DIMinus and ADX > th) : SAR_XshortCond)
SAR_XshortCond := (Act_SAR ? (SAR < close) : JMA_XshortCond)
// Defining the closing long/short condition from indicators
XlongCond := JMA_XlongCond and RF_XlongCond and ADX_XlongCond and SAR_XlongCond
XshortCond := JMA_XshortCond and RF_XshortCond and ADX_XshortCond and SAR_XshortCond
// Avoiding unconfirmed long/short simultaneity
CondIni_long0 := longCond ? 1 : shortCond ? -1 : nz(CondIni_long0[1])
CondIni_short0 := longCond ? 1 : shortCond ? -1 : nz(CondIni_short0[1])
// Unconfirmed long/short conditions
longCondition0 = (longCond and nz(CondIni_long0[1]) == -1)
shortCondition0 = (shortCond and nz(CondIni_short0[1]) == 1)
// Avoiding confirmed long/short simultaneity
CondIni_long := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_long[1])
CondIni_short := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_short[1])
// Confirmed long/short conditions
longCondition = (longCond[1] and nz(CondIni_long[1]) == -1)
shortCondition = (shortCond[1] and nz(CondIni_short[1]) == 1)
// Avoiding unconfirmed long/short closing simultaneity
CondIniX0 := XlongCond ? 1 : XshortCond ? -1 : nz(CondIniX0[1])
// Unconfirmed long/short closing conditions
XlongCondition0 = XlongCond and nz(CondIniX0[1]) == -1
XshortCondition0 = XshortCond and nz(CondIniX0[1]) == 1
// Avoiding confirmed long/short closing simultaneity
CondIniX := XlongCond[1] ? 1 : XshortCond[1] ? -1 : nz(CondIniX[1])
// Confirmed long/short closing conditions
XlongCondition = XlongCond[1] and nz(CondIniX[1]) == -1
XshortCondition = XshortCond[1] and nz(CondIniX[1]) == 1
// ================================================================================================================================================================================
// POSITION PRICE
// ================================================================================================================================================================================
// Last opened long/short price on unconfirmed/confirmed conditions
last_open_longCondition := longCondition0 and not longCondition ? max(SAR[1],hband,close[1]) : longCondition ? close[1] : nz(last_open_longCondition[1])
last_open_shortCondition := shortCondition0 and not shortCondition ? min(SAR[1],lband,close[1]) : shortCondition ? close[1] : nz(last_open_shortCondition[1])
// Check if your last position was an unconfirmed long or a short
last_longCondition0 := longCondition0 ? time : nz(last_longCondition0[1])
last_shortCondition0 := shortCondition0 ? time : nz(last_shortCondition0[1])
in_longCondition0 = last_longCondition0 > last_shortCondition0
in_shortCondition0 = last_shortCondition0 > last_longCondition0
// Check if your last position was a confirmed long or a short
last_longCondition := longCondition ? time : nz(last_longCondition[1])
last_shortCondition := shortCondition ? time : nz(last_shortCondition[1])
in_longCondition = last_longCondition > last_shortCondition
in_shortCondition = last_shortCondition > last_longCondition
// Check if your last position was an unconfirmed Xlong or a Xshort
last_XlongCondition0 := XlongCondition0 ? time : nz(last_XlongCondition0[1])
last_XshortCondition0 := XshortCondition0 ? time : nz(last_XshortCondition0[1])
in_longConditionX0 = last_longCondition > last_XlongCondition0
in_shortConditionX0 = last_shortCondition > last_XshortCondition0
// Check if your last position closing was a confirmed Xlong or Xshort
last_XlongCondition := XlongCondition ? time : nz(last_XlongCondition[1])
last_XshortCondition := XshortCondition ? time : nz(last_XshortCondition[1])
in_longConditionX = last_longCondition > last_XlongCondition
in_shortConditionX = last_shortCondition > last_XshortCondition
// Longs Counter
if longCondition
nLongs := nLongs + 1
nShorts := na
// Shorts Counter
if shortCondition
nLongs := na
nShorts := nShorts + 1
// ================================================================================================================================================================================
// TAKE PROFIT 1
// ================================================================================================================================================================================
// First take profit input
tp = input(0.8, "TAKE PROFIT 1 %", type = input.float, step = 0.1)
// First TP Conditions
long_tp := (is_Long and high > (last_open_longCondition*(1+(tp/100))) and not (shortCondition0 and Act_not_conf) and in_longCondition)
short_tp := (is_Short and low < (last_open_shortCondition*(1-(tp/100))) and not (longCondition0 and Act_not_conf) and in_shortCondition)
// Get the time of the last tp close
last_long_tp := long_tp ? time : nz(last_long_tp[1])
last_short_tp := short_tp ? time : nz(last_short_tp[1])
// Final Take profit condition (never after the stop loss)
Final_Long_tp := (long_tp and last_longCondition > nz(last_long_tp[1]) and last_longCondition > nz(last_long_sl[1]))
Final_Short_tp := (short_tp and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1]))
// ================================================================================================================================================================================
// TAKE PROFIT 2
// ================================================================================================================================================================================
// Second take profit input
Act_tp2 = input(true, "ACTIVATE TAKE PROFIT 2")
tp2 = input(1.8, "TAKE PROFIT 2 %", type = input.float, step = 0.1)
// Second TP Conditions
long_tp2 := (Act_tp2 and is_Long and high > (last_open_longCondition*(1+(tp2/100))) and not (shortCondition0 and Act_not_conf) and in_longCondition)
short_tp2 := (Act_tp2 and is_Short and low < (last_open_shortCondition*(1-(tp2/100))) and not (longCondition0 and Act_not_conf) and in_shortCondition)
// Get the time of the last tp2 close
last_long_tp2 := long_tp2 ? time : nz(last_long_tp2[1])
last_short_tp2 := short_tp2 ? time : nz(last_short_tp2[1])
// Final second Take profit condition (never after the stop loss)
Final_Long_tp2 := (long_tp2 and last_longCondition > nz(last_long_tp2[1]) and last_longCondition > nz(last_long_sl[1]))
Final_Short_tp2 := (short_tp2 and last_shortCondition > nz(last_short_tp2[1]) and last_shortCondition > nz(last_short_sl[1]))
// ================================================================================================================================================================================
// TAKE PROFIT FOR PUMPS
// ================================================================================================================================================================================
// Take profit on pumps input
tp_pump = input(1.0, "TAKE PROFIT FOR PUMPS % ", type = input.float, step = 0.1)
// Second TP Conditions
long_tp_pump := is_Long and longCondition0 and not longCondition and high > last_open_longCondition*(1+(tp_pump/100)) and Act_not_conf
short_tp_pump := is_Short and shortCondition0 and not shortCondition and low < last_open_shortCondition*(1-(tp_pump/100)) and Act_not_conf
// Get the time of the last take profit on pumps close
last_long_tp_pump := long_tp_pump ? time : nz(last_long_tp_pump[1])
last_short_tp_pump := short_tp_pump ? time : nz(last_short_tp_pump[1])
// Final Take profit on pumps condition (never after the stop loss)
Final_Long_tp_pump := (long_tp_pump and last_longCondition > nz(last_long_tp_pump[1]) and last_longCondition > nz(last_long_sl[1]))
Final_Short_tp_pump := (short_tp_pump and last_shortCondition > nz(last_short_tp_pump[1]) and last_shortCondition > nz(last_short_sl[1]))
// ================================================================================================================================================================================
// STOP LOSS
// ================================================================================================================================================================================
// Stop Loss input
Act_sl = input(false, "ACTIVATE STOP LOSS")
sl = input(4.0, "STOP LOSS %", type = input.float, step = 0.1)
// Stop Loss conditions
long_sl = Act_sl and is_Long and low <= ((1-(sl/100))*last_open_longCondition) and not (open < ((1-(sl/100))*last_open_longCondition))
short_sl = Act_sl and is_Short and high >= ((1+(sl/100))*last_open_shortCondition) and not (open > ((1+(sl/100))*last_open_shortCondition))
// Avoiding simultaneity with Stop loss and other signals
Final_Long_sl0 := Position == "BOTH" ? long_sl and nz(CondIni_long_sl[1]) == -1 and not Final_Long_tp and not shortCondition and not (shortCondition0 and Act_not_conf) :
long_sl and nz(CondIni_long_sl[1]) == -1 and not Final_Long_tp
Final_Short_sl0 := Position == "BOTH" ? short_sl and nz(CondIni_short_sl[1]) == -1 and not Final_Short_tp and not longCondition and not (longCondition0 and Act_not_conf) :
short_sl and nz(CondIni_short_sl[1]) == -1 and not Final_Short_tp
// Get the time of the last sl close
last_long_sl := Final_Long_sl ? time : nz(last_long_sl[1])
last_short_sl := Final_Short_sl ? time : nz(last_short_sl[1])
// Final Stop Loss condition
Final_Long_sl := Final_Long_sl0 and last_longCondition > nz(last_long_tp[1]) and last_longCondition > nz(last_long_sl[1])
Final_Short_sl := Final_Short_sl0 and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1])
// Final SL Counter
CondIni_long_sl := Final_Long_tp or Final_Long_sl or Final_shortCondition0 or Final_shortCondition or Final_XlongCondition ? 1 :
Final_longCondition0 or Final_longCondition ? -1 : nz(CondIni_long_sl[1])
CondIni_short_sl := Final_Short_tp or Final_Short_sl or Final_longCondition0 or Final_longCondition or Final_XshortCondition ? 1 :
Final_shortCondition0 or Final_shortCondition ? -1 : nz(CondIni_short_sl[1])
// ================================================================================================================================================================================
// SIGNALS PLOTTING
// ================================================================================================================================================================================
// Final unconfirmed long & short conditions
Final_longCondition0 := is_Long and longCondition0 and not longCondition and nz(CondIni_long0[1]) == -1 and Act_not_conf
Final_shortCondition0 := is_Short and shortCondition0 and not shortCondition and nz(CondIni_short0[1]) == 1 and Act_not_conf
// Final unconfirmed long & short triangles
plotshape(Final_longCondition0, title = "Not_Conf Long Signal", text = "🤞", style=shape.triangleup, location=location.belowbar, color = color.blue, transp = 0, size=size.tiny)
plotshape(Final_shortCondition0, title = "Not_Conf Short Signal", text = "🤞", style=shape.triangledown, location=location.abovebar, color = #FF0000, transp = 0, size=size.tiny)
// Final confirmed long & short conditions
Final_longCondition := is_Long and longCondition and not Final_shortCondition0 //and not (Final_longCondition0[1] and not Final_Long_ts_pump[1])
Final_shortCondition := is_Short and shortCondition and not Final_longCondition0 //and not (Final_shortCondition0[1] and not Final_Short_ts_pump[1])
// Final confirmed long & short triangles
plotshape(Final_longCondition, title = "Long Signal", style=shape.triangleup, location=location.belowbar, color = color.blue, transp = 0, size=size.tiny)
plotshape(Final_shortCondition, title = "Short Signal", style=shape.triangledown, location=location.abovebar, color = #FF0000, transp = 0, size=size.tiny)
// Avoiding simultaneity and ordering unconfirmed Xlong & Xshort with other signals
CondIni_Xlong0 := Final_Long_tp or Final_Long_tp2 or Final_Short_tp or Final_Long_sl or Final_XlongCondition0 or Final_shortCondition0 or Final_shortCondition ? 1 :
Final_longCondition0 or Final_longCondition ? -1 : nz(CondIni_Xlong0[1])
CondIni_Xshort0 := Final_Short_tp or Final_Short_tp2 or Final_Short_tp or Final_Short_sl or Final_XshortCondition0 or Final_longCondition0 or Final_longCondition ? 1 :
Final_shortCondition0 or Final_shortCondition ? -1 : nz(CondIni_Xshort0[1])
// Final unconfirmed Xlong & Xshort conditions
Final_XlongCondition0 := (Position == "SHORT" ? na : Position == "BOTH" and Act_X == true ? (XlongCondition0 and last_longCondition > last_XlongCondition0[1]) : Position == "LONG" ?
((shortCondition0 and last_longCondition > last_shortCondition0[1]) or (XlongCondition0 and last_longCondition > last_XlongCondition0[1])) : na)
and CondIni_Xlong0 == -1 and not Final_longCondition0 and not Final_shortCondition0 and not Final_longCondition and not Final_shortCondition
Final_XshortCondition0 := (Position == "LONG" ? na : Position == "BOTH" and Act_X == true ? (XshortCondition0 and last_shortCondition > last_XshortCondition0[1]) : Position == "SHORT" ?
((longCondition0 and last_shortCondition > last_longCondition0[1]) or (XshortCondition0 and last_shortCondition > last_XshortCondition0[1])) : na)
and CondIni_Xshort0 == -1 and not Final_longCondition0 and not Final_shortCondition0 and not Final_longCondition and not Final_shortCondition
// Avoiding simultaneity and ordering confirmed Xlong & Xshort with other signals
CondIni_Xlong := Final_Long_tp or Final_Short_tp or Final_Long_sl or Final_XlongCondition or Final_shortCondition0 or Final_shortCondition ? 1 :
Final_longCondition0 or Final_longCondition ? -1 : nz(CondIni_Xlong[1])
CondIni_Xshort := Final_Long_tp or Final_Short_tp or Final_Short_sl or Final_XshortCondition or Final_longCondition0 or Final_longCondition ? 1 :
Final_shortCondition0 or Final_shortCondition ? -1 : nz(CondIni_Xshort[1])
// Final confirmed Xlong & Xshort conditions
Final_XlongCondition := (Position == "SHORT" ? na : Position == "BOTH" and Act_X == true ? (XlongCondition and last_longCondition > last_XlongCondition[1]) : Position == "LONG" ?
((shortCondition and last_longCondition > last_shortCondition[1]) or (XlongCondition and last_longCondition > last_XlongCondition[1])) : na)
and CondIni_Xlong == -1 and not Final_longCondition0 and not Final_shortCondition0
Final_XshortCondition := (Position == "LONG" ? na : Position == "BOTH" and Act_X == true ? (XshortCondition and last_shortCondition > last_XshortCondition[1]) : Position == "SHORT" ?
((longCondition and last_shortCondition > last_longCondition[1]) or (XshortCondition and last_shortCondition > last_XshortCondition[1])) : na)
and CondIni_Xshort == -1 and not Final_longCondition0 and not Final_shortCondition0
// Final Confirmed or unconfirmed Xlong & Xshort conditions
Final_XL = ((Final_XlongCondition0 and Act_not_conf_X) or (Final_XlongCondition and not Act_not_conf_X))
Final_XS = ((Final_XshortCondition0 and Act_not_conf_X) or (Final_XshortCondition and not Act_not_conf_X))
// Final Confirmed or unconfirmed Xlong & Xshort triangles
plotshape(Final_XL, title = "XL Signal", text = "XL", style=shape.triangledown, location=location.abovebar, color = color.orange, transp = 0, size=size.tiny)
plotshape(Final_XS, title = "XS Signal", text = "XS", style=shape.triangleup, location=location.belowbar, color = color.aqua, transp = 0, size=size.tiny)
// TP triangles
plotshape(Final_Long_tp and not Final_Long_tp2, text ="TP", title="Take Profit Long", style=shape.triangledown, location=location.abovebar, color = color.red, editable = false, transp = 0)
plotshape(Final_Short_tp and not Final_Short_tp2, text ="TP", title="Take Profit Short", style=shape.triangleup, location=location.belowbar, color = color.lime, editable = false, transp = 0)
// TP crosses
ltp = iff(Final_Long_tp, last_open_longCondition*(1+(tp/100)), na), plot(ltp, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
stp = iff(Final_Short_tp, last_open_shortCondition*(1-(tp/100)), na), plot(stp, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
// TP2 triangles
plotshape(Final_Long_tp2 and not Final_Long_tp, text ="TP2", title="Take Profit Long 2", style=shape.triangledown, location=location.abovebar, color = color.red, editable = false, transp = 0)
plotshape(Final_Short_tp2 and not Final_Short_tp, text ="TP2", title="Take Profit Short 2", style=shape.triangleup, location=location.belowbar, color = color.lime, editable = false, transp = 0)
// TP2 crosses
ltp2 = iff(Final_Long_tp2, last_open_longCondition*(1+(tp2/100)), na), plot(ltp2, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
stp2 = iff(Final_Short_tp2, last_open_shortCondition*(1-(tp2/100)), na), plot(stp2, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
// TP & TP2 flags on condition of simultaneity
plotshape(Final_Long_tp and Final_Long_tp2, title="TP & TP2 Long", style=shape.flag, location=location.abovebar, color = color.red, editable = false, transp = 0, size=size.tiny)
plotshape(Final_Short_tp and Final_Short_tp2, title="TP & TP2 Short", style=shape.flag, location=location.belowbar, color = color.green, editable = false, transp = 0, size=size.tiny)
// TP on Pumps triangles
plotshape(Final_Long_tp_pump and Final_longCondition0, text ="PUMP", title="Take Profit Long Pump", style=shape.triangledown,
location=location.abovebar, color = color.red, editable = false, transp = 0)
plotshape(Final_Short_tp_pump and Final_shortCondition0, text ="PUMP", title="Take Profit Short Pump", style=shape.triangleup,
location=location.belowbar, color = color.lime, editable = false, transp = 0)
//TP on pumps crosses
ltp_pump = iff(Final_Long_tp_pump and Final_longCondition0, last_open_longCondition*(1+(tp_pump/100)), na), plot(ltp_pump, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
stp_pump = iff(Final_Short_tp_pump and Final_shortCondition0, last_open_shortCondition*(1-(tp_pump/100)), na), plot(stp_pump, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
// Stop Loss triangles
plotshape(Final_Long_sl, text ="SL", title="Stop Loss Long", style=shape.triangledown, location=location.abovebar, color = color.fuchsia, editable = false, transp = 0)
plotshape(Final_Short_sl, text ="SL", title="Stop Loss Short", style=shape.triangleup, location=location.belowbar, color = color.fuchsia, editable = false, transp = 0)
// Stop Loss crosses
lsl = iff(Final_Long_sl, (1-(sl/100))*last_open_longCondition, na), plot(lsl, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
ssl = iff(Final_Short_sl, (1+(sl/100))*last_open_shortCondition, na), plot(ssl, style = plot.style_cross, linewidth=3, color = color.white, editable = false)
// TP Levels
plot(is_Long and in_longCondition0 and not longCondition0 and last_longCondition > nz(last_long_tp[1]) and last_longCondition > nz(last_long_sl[1]) ?
(last_open_longCondition*(1+(tp/100))) : na, "Long Take Profit", color = color.green, style=3, linewidth=1, editable = false)
plot(is_Short and in_shortCondition0 and not shortCondition0 and last_shortCondition > nz(last_short_tp[1]) and last_shortCondition > nz(last_short_sl[1]) ?
(last_open_shortCondition*(1-(tp/100))) : na, "Short Take Profit", color =color.red , style=3, linewidth=1, editable = false)
// TP2 Levels
plot(Act_tp2 and is_Long and in_longCondition0 and not longCondition0 and last_longCondition > nz(last_long_tp2[1]) and last_longCondition > nz(last_long_sl[1]) ?
(last_open_longCondition*(1+(tp2/100))) : na, "Long Take Profit 2", color = color.green, style=3, linewidth=1, editable = false)
plot(Act_tp2 and is_Short and in_shortCondition0 and not shortCondition0 and last_shortCondition > nz(last_short_tp2[1]) and last_shortCondition > nz(last_short_sl[1]) ?
(last_open_shortCondition*(1-(tp2/100))) : na, "Short Take Profit 2", color =color.red , style=3, linewidth=1, editable = false)
// Weekend
Weekend = true
W_color = Weekend and (dayofweek == dayofweek.sunday or dayofweek == dayofweek.saturday) ? color.teal : na
bgcolor(W_color, title = "WEEKEND")
// ================================================================================================================================================================================
// RE-ENTRY CONDITIONS
// ================================================================================================================================================================================
// Re-entry on long after tp, sl or Xlong
if Final_Long_tp or Final_Long_sl or Final_XlongCondition
CondIni_long := -1
CondIni_long0 := -1
// Re-entry on short after tp, sl or Xshort
if Final_Short_tp or Final_Short_sl or Final_XshortCondition
CondIni_short := 1
CondIni_short0 := 1
// Re-entry on unconfirmed long after a confirmed long
if Final_longCondition
CondIni_long0 := 1
// Re-entry on unconfirmed short after a confirmed short
if Final_shortCondition
CondIni_short0 := -1
// ================================================================================================================================================================================
// BACKTEST
// ================================================================================================================================================================================
// Backtest input
Act_BT = input(true, "BACKTEST 💹")
// Time period input
testStartYear = input(2019, "BACKTEST START YEAR", minval = 1980, maxval = 2222)
testStartMonth = input(06, "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)
testPeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false
// Choosing between contracts or $
contracts_or_cash = input("CONTRACTS", "CONTRACTS ₿ / CASH $", options = ["CONTRACTS","CASH"])
cc_factor = (contracts_or_cash == "CASH") ? open : 1
// Entering the quantity of each entry to close on its take profit
quantity_cash_1TP = input(0.5, "QUANTITY 1ST TP", type = input.float) / cc_factor
quantity_cash_2TP = input(0.5, "QUANTITY 2ND TP", type = input.float) / cc_factor
Act_Lev = input(true, "ACTIVATE LEVERAGE BY VOLUME")
var int qty_Lev = na
qty_Lev := Act_Lev ? ceil(volume/sma(volume,sma_length)) : 1
// Defining new final unconfirmed conditions to use on the TV backtest
BT_Final_longCondition := Position == "SHORT" ? na : ((longCond and not in_longCondition) or (longCond and Final_Long_tp) or (longCond and Final_Long_sl)) or
(longCond and not longCondition and (last_long_tp > nz(last_longCondition))) or (longCond and not longCondition and (last_long_sl > nz(last_longCondition))) or
(longCond and Act_X == true and not longCondition and (last_XlongCondition0 > nz(last_longCondition)))
BT_Final_shortCondition := Position == "LONG" ? na : ((shortCond and not in_shortCondition) or (shortCond and Final_Short_tp) or (shortCond and Final_Short_sl)) or
(shortCond and not shortCondition and (last_short_tp > nz(last_shortCondition))) or (shortCond and not shortCondition and (last_short_sl > nz(last_shortCondition))) or
(shortCond and Act_X == true and not shortCondition and (last_XshortCondition0 > nz(last_shortCondition)))
// Entering long positions
if (BT_Final_longCondition)
strategy.entry("long1", strategy.long, qty = quantity_cash_1TP*qty_Lev, when = Act_BT and testPeriod)
strategy.entry("long2", strategy.long, qty = quantity_cash_2TP*qty_Lev, when = Act_BT and testPeriod and Act_tp2)
// Entering short positions
if (BT_Final_shortCondition)
strategy.entry("short1", strategy.short, qty = quantity_cash_1TP*qty_Lev, when = Act_BT and testPeriod)
strategy.entry("short2", strategy.short, qty = quantity_cash_2TP*qty_Lev, when = Act_BT and testPeriod and Act_tp2)
// Closing positions with first TP
strategy.exit("Tpl", "long1", profit = (abs((last_open_longCondition*(1+(tp/100)))-last_open_longCondition)/syminfo.mintick),
loss = Act_sl ? (abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick) : na)
strategy.exit("Tps", "short1", profit = (abs((last_open_shortCondition*(1-(tp/100)))-last_open_shortCondition)/syminfo.mintick),
loss = Act_sl ? (abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick) : na)
// Closing positions with second TP
strategy.exit("Tpl2", "long2", profit = (abs((last_open_longCondition*(1+(tp2/100)))-last_open_longCondition)/syminfo.mintick),
loss = Act_sl ? (abs((last_open_longCondition*(1-(sl/100)))-last_open_longCondition)/syminfo.mintick) : na)
strategy.exit("Tps2", "short2", profit = (abs((last_open_shortCondition*(1-(tp2/100)))-last_open_shortCondition)/syminfo.mintick),
loss = Act_sl ? (abs((last_open_shortCondition*(1+(sl/100)))-last_open_shortCondition)/syminfo.mintick) : na)
// Closing all positions with Xlong/Xshort
strategy.close_all(when = Final_XlongCondition0 or Final_XshortCondition0)
// ================================================================================================================================================================================
// ALERTS
// ================================================================================================================================================================================
//alertcondition(Final_longCondition0, title="Not_Conf Long Alert", message = "NC LONG")
//alertcondition(Final_shortCondition0, title="Not_Conf Short Alert", message = "NC SHORT")
//alertcondition(Final_longCondition, title="Long Alert", message = "LONG")
//alertcondition(Final_shortCondition, title="Short Alert", message = "SHORT")
//alertcondition(Final_Long_tp, title="Take Profit on Longs Alert", message = "LONG TP")
//alertcondition(Final_Short_tp, title="Take Profit on Shorts Alert", message = "SHORT TP")
//alertcondition(Final_Long_tp2, title="Take Profit2 on Longs Alert", message = "LONG TP2")
//alertcondition(Final_Short_tp2, title="Take Profit2 on Shorts Alert", message = "SHORT TP2")
//alertcondition(Final_XlongCondition or Final_Long_sl or (Final_Long_tp_pump and Act_not_conf), title="XLong/PUMP/Stop-Loss on Longs Alert", message = "XLONG/PUMP/STOP-LOSS")
//alertcondition(Final_XshortCondition or Final_Short_sl or (Final_Short_tp_pump and Act_not_conf), title="XShort/PUMP/Stop-Loss on Shorts Alert", message = "XSHORT/PUMP/STOP-LOSS")
// BTC BINANCE FUTURES
alertcondition(Final_longCondition0, title="BTC NC Long Alert",
message = "NC LONG | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order b=long | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short t=market ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT b=long q=25% t=market")
alertcondition(Final_shortCondition0, title="BTC NC Short Alert",
message = "NC SHORT | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order b=short | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long t=market ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT b=short q=25% t=market")
alertcondition(Final_longCondition, title="BTC Long Alert",
message = "LONG | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order b=long | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short t=market ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT b=long q=100% t=market | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long p=0.80% q=50% t=limit ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long p=1.8% q=50% t=limit ro=1")
alertcondition(Final_shortCondition, title="BTC Short Alert",
message = "SHORT | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order b=short | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long t=market ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT b=short q=100% t=market | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short p=-0.80% q=50% t=limit ro=1 | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short p=-1.8% q=50% t=limit ro=1")
//alertcondition(Final_Long_tp, title="BTC Take Profit on Longs Alert",
// message = "LONG TP | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position q=50% t=market ro=1")
//alertcondition(Final_Short_tp, title="BTC Take Profit on Shorts Alert",
// message = "SHORT TP | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position q=50% t=market ro=1")
//alertcondition(Final_Long_tp2, title="BTC Take Profit on Longs Alert",
// message = "LONG TP2 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long q=100% t=market ro=1")
//alertcondition(Final_Short_tp2, title="BTC Take Profit on Shorts Alert",
// message = "SHORT TP2 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short q=100% t=market ro=1")
alertcondition(Final_XL or Final_Long_sl or (Final_Long_tp_pump and Act_not_conf), title="BTC XLong/PUMP/Stop-Loss on Longs Alert",
message = "XLONG/PUMP/STOP-LOSS | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=long t=market ro=1")
alertcondition(Final_XS or Final_Short_sl or (Final_Short_tp_pump and Act_not_conf), title="BTC XShort/PUMP/Stop-Loss on Shorts Alert",
message = "XSHORT/PUMP/STOP-LOSS | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=order | delay=1 | e=BINANCEFUTURES a=BINANCE s=BTCUSDT c=position b=short t=market ro=1")
// by Xaviz |
STEM_MATCS_BTC_STRATEGY | https://www.tradingview.com/script/f0NnKUwv-STEM-MATCS-BTC-STRATEGY/ | UnknownUnicorn2689000 | https://www.tradingview.com/u/UnknownUnicorn2689000/ | 53 | 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/
// © IncomePipelineGenerator
//@version=4
strategy("STRAT_STEM_MATCS_BTC", overlay=true, pyramiding = 0, default_qty_value = 20, slippage = 5)
ST_EMA_PERIOD = input(1, minval=1)
ST_EMA = ema(close, ST_EMA_PERIOD)
LENGTH = input(title="ATR_PERIOD", type=input.integer, defval=95)
ATR_TUNE = input(title="ATR_TUNE", type=input.float, step=0.1, defval=2.1)
showLabels = input(title="Show_Buy/Sell_Labels ?", type=input.bool, defval=true)
highlightState = input(title="Highlight_State ?", type=input.bool, defval=true)
ATR = ATR_TUNE * atr(LENGTH)
longStop = ST_EMA - ATR
longStopPrev = nz(longStop[1], longStop)
longStop := (close[1]) > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = ST_EMA + ATR
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := (close[1]) < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and (close) > shortStopPrev ? 1 : dir == 1 and (close) < longStopPrev ? -1 : dir
fastLength = input(3, minval=1), medLength=input(9, minval=1), slowLength=input(12, minval=1), signalLength=input(16,minval=1)
fastMA = ema(close, fastLength), medMA = ema(close, medLength), slowMA = ema(close, slowLength)
macd = fastMA - slowMA
fmacd = fastMA - medMA
smacd = slowMA - medMA
signal = ema(macd, signalLength)
fsignal = ema(fmacd, signalLength)
ssignal = ema(smacd, signalLength)
SetStopLossShort = 0.0
SetStopLossShort := if(strategy.position_size < 0)
StopLossShort = shortStop
min(StopLossShort,SetStopLossShort[1])
SetStopLossLong = 0.0
SetStopLossLong := if(strategy.position_size > 0)
StopLossLong = longStop
max(StopLossLong,SetStopLossLong[1])
ATR_CrossOver_Period = input(5, type=input.integer, minval=1, maxval=2000)
ATR_SIGNAL_FINE_TUNE = input(0.962, type=input.float)
ATR_CS = atr(ATR_CrossOver_Period)*ATR_SIGNAL_FINE_TUNE
StopLoss_Initial_Short = input(0.0, type=input.float)
StopLoss_Initial_Long = input(0.0, type=input.float)
StopLoss_Long_Adjust = input(0.0, type=input.float)
StopLoss_Short_Adjust = input(0.0, type=input.float)
VOLUME_CHECK = input(200)
//Custom Time Interval
fromMinute = input(defval = 0, title = "From Minute", minval = 0, maxval = 60)
fromHour = input(defval = 0, title = "From Hour", minval = 0, maxval = 24)
fromDay = input(defval = 1, title = "From Day", minval = 1)
fromMonth = input(defval = 1, title = "From Month", minval = 1)
fromYear = input(defval = 2019, title = "From Year", minval = 1900)
tillMinute = input(defval = 0, title = "Till Minute", minval = 0, maxval = 60)
tillHour = input(defval = 0, title = "Till Hour", minval = 0, maxval = 24)
tillDay = input(defval = 1, title = "Till Day", minval = 1)
tillMonth = input(defval = 1, title = "Till Month", minval = 1)
tillYear = input(defval = 2020, title = "Till Year", minval = 1900)
timestampStart = timestamp(fromYear,fromMonth,fromDay,fromHour,fromMinute)
timestampEnd = timestamp(tillYear,tillMonth,tillDay,tillHour,tillMinute)
//Custom Buy Signal Code -- This is where you design your own buy and sell signals. You now have millions of possibilites with the use of simple if/and/or statements.
if ( (time >= timestampStart and time <= timestampEnd) and dir==1 and dir[1]==-1 and volume > VOLUME_CHECK and ((fsignal[1] -fsignal) <= 0) and cross(fmacd, smacd) )
strategy.exit("SELL")
strategy.entry("BUY", strategy.long)
strategy.exit("BUY_STOP","BUY", stop = close - StopLoss_Initial_Long)
//Custom Sell Signal Code
if ( (time >= timestampStart and time <= timestampEnd) and dir == -1 and dir[1] == 1 and dir[2] == 1 and dir[3] == 1 and dir[4] == 1 and cross(fmacd, smacd) )
strategy.exit( "BUY")
strategy.entry("SELL", strategy.short)
strategy.exit("SELL_STOP","SELL", stop = close + StopLoss_Initial_Short)
//Slight adjustments to ST for fine tuning
if (strategy.opentrades > 0 )
strategy.exit("BUY_TRAIL_STOP","BUY", stop = longStop - StopLoss_Long_Adjust)
strategy.exit("SELL_TRAIL_STOP","SELL", stop = shortStop + StopLoss_Short_Adjust) |
TradingView Alerts to MT4 MT5 + dynamic variables NON-REPAINTING | https://www.tradingview.com/script/9MJO3AgE-TradingView-Alerts-to-MT4-MT5-dynamic-variables-NON-REPAINTING/ | Peter_O | https://www.tradingview.com/u/Peter_O/ | 5,939 | 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/
// © Peter_O
//@version=5
strategy(title='TradingView Alerts to MT4 MT5 Strategy example', commission_type=strategy.commission.cash_per_order, commission_value=0.00003, overlay=false, default_qty_value=100000, initial_capital=1000)
//study(title="TradingView Alerts to MT4 MT5 Strategy example") //uncomment this line and comment previous one to make it a study producing alerts
//
// This script was created for educational purposes only.
// It is showing how to use dynamic variables in TradingView alerts.
// And how to execute them in Forex, indices and commodities markets
TakeProfitDistance = input(400)
TakePartialProfitDistance = input(150)
// **** Entries logic **** {
periodK = input.int(13, title='K', minval=1)
periodD = input.int(3, title='D', minval=1)
smoothK = input.int(4, title='Smooth', minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
plot(k, title='%K', color=color.new(color.blue, 0))
plot(d, title='%D', color=color.new(color.orange, 0))
h0 = hline(80)
h1 = hline(20)
fill(h0, h1, color=color.new(color.purple, 75))
GoLong = ta.crossover(k, d) and k < 80
GoShort = ta.crossunder(k, d) and k > 20
// } End of entries logic
// **** Pivot-points and stop-loss logic **** {
piv_high = ta.pivothigh(high, 1, 1)
piv_low = ta.pivotlow(low, 1, 1)
var float stoploss_long = low
var float stoploss_short = high
pl = ta.valuewhen(piv_low, piv_low, 0)
ph = ta.valuewhen(piv_high, piv_high, 0)
if GoLong
stoploss_long := low < pl ? low : pl
stoploss_long
if GoShort
stoploss_short := high > ph ? high : ph
stoploss_short
// } End of Pivot-points and stop-loss logic
strategy.entry('Long', strategy.long, when=GoLong)
strategy.exit('XPartLong', from_entry='Long', qty_percent=50, profit=TakePartialProfitDistance)
strategy.exit('XLong', from_entry='Long', stop=stoploss_long, profit=TakeProfitDistance)
strategy.entry('Short', strategy.short, when=GoShort)
strategy.exit('XPartShort', from_entry='Short', qty_percent=50, profit=TakePartialProfitDistance)
strategy.exit('XShort', from_entry='Short', stop=stoploss_short, profit=TakeProfitDistance)
if GoLong
alertsyntax_golong = 'long slprice=' + str.tostring(stoploss_long) + ' tp1=' + str.tostring(TakePartialProfitDistance) + ' part1=0.5 tp=' + str.tostring(TakeProfitDistance)
alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close)
if GoShort
alertsyntax_goshort = 'short slprice=' + str.tostring(stoploss_short) + ' tp1=' + str.tostring(TakePartialProfitDistance) + ' part1=0.5 tp=' + str.tostring(TakeProfitDistance)
alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close)
|
Baseline Strategy - evo | https://www.tradingview.com/script/ztLkQJ55-Baseline-Strategy-evo/ | EvoCrypto | https://www.tradingview.com/u/EvoCrypto/ | 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/
// © EvoCrypto
//@version=4
strategy("Baseline Strategy - evo", "Baseline Strategy", true)
// INPUTS
Resolution = input("", "Resolution", type=input.resolution)
Show_Ma = input(false, "Show moving average")
// Strategy entry should be good on this setting
Repaint = (true)
Type = input("SMA", "Type", options=["SMA", "EMA", "HMA", "RMA", "WMA", "VWMA", "ALMA", "Donchian"])
Length = input(30, "Length", minval=1)
ALMA_Offset = (0.85)
ALMA_Sigma = (6)
Strategy = input("CLOSE", "Closing Strategy", options=["OHLC4", "HLC3", "HL2", "CLOSE"])
Signals = input(false, "Show signals")
Bars = input(false, "Show barcolor")
Background = input(false, "Show Background")
Fill = input(false, "Fill baseline")
// SETTINGS
O = Repaint ? open : open[1]
H = Repaint ? high : high[1]
L = Repaint ? low : low[1]
C = Repaint ? close : close[1]
OHLC = Repaint ? ohlc4 : ohlc4[1]
HLC = Repaint ? hlc3 : hlc3[1]
HL = Repaint ? hl2 : hl2[1]
OPEN = security(syminfo.tickerid, Resolution, O)
HIGH = security(syminfo.tickerid, Resolution, H)
LOW = security(syminfo.tickerid, Resolution, L)
CLOSE = security(syminfo.tickerid, Resolution, C)
OHLC4 = security(syminfo.tickerid, Resolution, OHLC)
HLC3 = security(syminfo.tickerid, Resolution, HLC)
HL2 = security(syminfo.tickerid, Resolution, HL)
Average_ =
Type == "SMA" ? sma(CLOSE, Length) :
Type == "EMA" ? ema(CLOSE, Length) :
Type == "HMA" ? hma(CLOSE, Length) :
Type == "RMA" ? rma(CLOSE, Length) :
Type == "WMA" ? wma(CLOSE, Length) :
Type == "VWMA" ? vwma(CLOSE, Length) :
Type == "ALMA" ? alma(CLOSE, Length, ALMA_Offset, ALMA_Sigma) :
Type == "Donchian" ? avg(highest(CLOSE, Length), lowest(CLOSE, Length)) : na
Upper_ =
Type == "SMA" ? sma(HIGH, Length) :
Type == "EMA" ? ema(HIGH, Length) :
Type == "HMA" ? hma(HIGH, Length) :
Type == "RMA" ? rma(HIGH, Length) :
Type == "WMA" ? wma(HIGH, Length) :
Type == "VWMA" ? vwma(HIGH, Length) :
Type == "ALMA" ? alma(HIGH, Length, ALMA_Offset, ALMA_Sigma) :
Type == "Donchian" ? avg(highest(HIGH, Length), lowest(HIGH, Length)) : na
Lower_ =
Type == "SMA" ? sma(LOW, Length) :
Type == "EMA" ? ema(LOW, Length) :
Type == "HMA" ? hma(LOW, Length) :
Type == "RMA" ? rma(LOW, Length) :
Type == "WMA" ? wma(LOW, Length) :
Type == "VWMA" ? vwma(LOW, Length) :
Type == "ALMA" ? alma(LOW, Length, ALMA_Offset, ALMA_Sigma) :
Type == "Donchian" ? avg(highest(LOW, Length), lowest(LOW, Length)) : na
Average = security(syminfo.tickerid, Resolution, Average_)
Upper = security(syminfo.tickerid, Resolution, Upper_)
Lower = security(syminfo.tickerid, Resolution, Lower_)
H_Set = Strategy == "OHLC4" ? OHLC4 : Strategy == "HLC3" ? HLC3 : Strategy == "HL2" ? HL2 : Strategy == "CLOSE" ? CLOSE : na
L_Set = Strategy == "OHLC4" ? OHLC4 : Strategy == "HLC3" ? HLC3 : Strategy == "HL2" ? HL2 : Strategy == "CLOSE" ? CLOSE : na
Dir_1 = float(na), Dir_1 := L_Set > Upper ? 1 : H_Set < Lower ? -1 : nz(Dir_1[1])
Up_Sig = Dir_1 != Dir_1[1] and Dir_1 == 1 and Signals
Dn_Sig = Dir_1 != Dir_1[1] and Dir_1 == -1 and Signals
Color_1_1 = Dir_1 == 1 ? (close > open ? color.new(#a5d6a7, 0) : color.new(#81c784, 0)) : (close > open ? color.new(#ef9a9a, 0) : color.new(#e57373, 0))
Color_1_2 = Dir_1 == 1 ? color.new(#4caf50, 80) : color.new(#f44336, 80)
Dir_2 = float(na), Dir_2 := Average > Average[1] ? 1 : Average < Average[1] ? -1 : nz(Dir_2[1])
Color_2 = Dir_2 == 1 ? color.new(#000000, 1) : color.new(#000000, 0)
Color_3 = Fill ? color.new(#000000, 90) : color.new(#000000, 100)
// PLOT
plot(Show_Ma ? Average : na, "Moving Average", Color_2, 2)
P1 = plot(Upper, "Upper Line", Color_2, 2)
P2 = plot(Lower, "Upper Line", Color_2, 2)
fill(P1, P2, title="Baseline Fill", color=Color_3)
plotshape(Up_Sig ? Lower : na, "Buy", color=color.new(#00ff00, 40), location=location.absolute, size=size.small, style=shape.labelup, text="Buy", textcolor=color.new(#000000, 0))
plotshape(Dn_Sig ? Upper : na, "Sell", color=color.new(#ff0000, 40), location=location.absolute, size=size.small, style=shape.labeldown, text="Sell", textcolor=color.new(#ffffff, 0))
barcolor(Bars ? Color_1_1 : na, title="Bar Color")
bgcolor(Background ? Color_1_2 : na, title="Background")
// STRATEGY
if (Dir_1 == 1)
strategy.entry("Long", strategy.long)
if (Dir_1 == -1)
strategy.entry("Short", strategy.short) |
Harmonic System Strategy | https://www.tradingview.com/script/WG8oLdFX/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 582 | 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("Harmonic System Strategy", overlay=true)
harm_average(x,y,z) =>3 / (1 / x + 1 / y + 1 / z)
T1 = harm_average(close[1], close[2], close[3])
T2 = harm_average(T1, T1[1], T1[2])
T3 = harm_average(T2, T2[1], T2[2])
T4 = harm_average(T3, T3[1], T3[2])
T5 = harm_average(T4, T4[1], T4[2])
T6 = harm_average(T5, T5[1], T5[2])
Balance = 18 / (1 / T1 * 3 + 1 / T2 * 3 + 1 / T3 * 3 + 1 / T4 * 3 + 1 / T5 * 3 + 1 / T6 * 3)
plot(T1,linewidth=2, color=color.green,title="T1")
plot(T2,linewidth=1, color=color.blue,title="T2")
plot(T3,linewidth=1, color=color.blue,title="T3")
plot(Balance,linewidth=2, color=color.black,title="Balance")
plot(T4,linewidth=1, color=color.blue,title="T4")
plot(T5,linewidth=1, color=color.blue,title="T5")
plot(T6,linewidth=2, color=color.red,title="T6")
X1 = min(min(T1,T2),T3)
X2 = max(max(T4,T5),T6)
X3 = min(T1,T2)
X4 = max(T3,T4)
Buy=crossover(X1,X2)
Sell=crossunder(X3,X4)
if crossover(X1,X2)
strategy.entry("Long", strategy.long, comment="Long")
if crossunder(X3,X4)
strategy.entry("Short", strategy.short, comment="Short")
|
How To Set Trade Dates | https://www.tradingview.com/script/1P9pouqq-How-To-Set-Trade-Dates/ | allanster | https://www.tradingview.com/u/allanster/ | 346 | 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 Trade Dates", shorttitle = "Seasonality", overlay = true, precision = 2, max_bars_back = 200, pyramiding = 0, initial_capital = 10000,
currency = currency.NONE, default_qty_type = strategy.cash, default_qty_value = 10000, commission_type = "percent", commission_value = 0.27)
// Revision: 2
// Author: @allanster
// === INPUT BACKTEST RANGE ===
toolTipA = 'Use with Daily or lower timeframe. If using Daily set desired dates 1 day earlier.'
toolTipB = '\n\nUse 0 as wild card for all. Examples:\nEntry Year: 0 is "Every Year".\nEntry Month: 0 is "Every Month".'
toolTipC = '\n\nWhen using 0 wild card dates on Daily period will not buy on 1st day of month. If market is closed will buy on next open day.'
inpEntrY = input.int (defval = 2020, title = "Entry Year", minval = 0, tooltip = toolTipA + toolTipB + toolTipC)
inpEntrM = input.int (defval = 9, title = "Entry Month", minval = 0, maxval = 12)
inpEntrD = input.int (defval = 1, title = "Entry Day", minval = 0, maxval = 31)
inpExitY = input.int (defval = 2021, title = "Exit Year", minval = 0)
inpExitM = input.int (defval = 5, title = "Exit Month", minval = 0, maxval = 12)
inpExitD = input.int (defval = 1, title = "Exit Day", minval = 0, maxval = 31)
inpPostn = input.string(defval = "LONG", title = "Position", confirm = false, options = ["LONG", "SHORT"])
// === LOGIC ===
dates2trade() =>
entrD = inpEntrD == 0 ? dayofmonth : inpEntrD
entrM = inpEntrM == 0 ? month : inpEntrM
entrY = inpEntrY == 0 ? year : inpEntrY
exitD = inpExitD == 0 ? dayofmonth : inpExitD
exitM = inpExitM == 0 ? month : inpExitM
exitY = inpExitY == 0 ? year : inpExitY
dates2entr = time >= timestamp(entrY, entrM, entrD, 00, 00, 00) and time <= timestamp(entrY, entrM, entrD + 4, 00, 00, 00)
dates2exit = time >= timestamp(exitY, exitM, exitD, 00, 00, 00) and time <= timestamp(exitY, exitM, exitD + 4, 00, 00, 00)
[dates2entr,dates2exit]
[entr,exit] = dates2trade()
// === EXECUTION ===
strategy.entry("L", strategy.long, when = inpPostn == "LONG" and entr)
strategy.entry("S", strategy.short, when = inpPostn == "SHORT" and entr)
strategy.close_all(when = exit) |
Scaled Normalized Vector Strategy, ver.4.1 | https://www.tradingview.com/script/LDk7bX6z-scaled-normalized-vector-strategy-ver-4-1/ | capissimo | https://www.tradingview.com/u/capissimo/ | 310 | 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/
// © capissimo
//@version=4
strategy("Scaled Normalized Vector Strategy (ver.4.1)", '', false, precision=2)
// Description:
// This modification of the Scaled Normalized Vector Strategy uses trailing stops and is optimized for lower TFs
price = input(close, "Price Data")
tf = input(6, "Timeframe", minval=1, maxval=1440)
thresh = input(14., "Threshold", minval=.1, step=.1)
div = input(1000000,"Divisor", options=[1,10,100,1000,10000,100000,1000000,10000000,100000000])
mmx = input(233, "Minimax Lookback", options=[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584])
showVol = input(false, "Volume")
useold = input(true, "Use Old System")
method = input("Swish","Activation", options=["Step", "LReLU", "Swish", "None"])
useStop = input(true, "Use Trailing Stop?")
slPoints = input(200, "Stop Loss Trail Points", minval = 1)
slOffset = input(400, "Stop Loss Trail Offset", minval = 1)
scaleMinimax(X, p, min, max) =>
hi = highest(X, p), lo = lowest(X, p)
(max - min) * (X - lo)/(hi - lo) + min
getdiff(prc, tf) =>
prev = scaleMinimax((useold ? security(syminfo.tickerid, tostring(tf), prc[1], barmerge.gaps_off, barmerge.lookahead_on)
: security(syminfo.tickerid, tostring(tf), prc[1])), tf, 0, 1)
curr = scaleMinimax((useold ? security(syminfo.tickerid, tostring(tf), hlc3, barmerge.gaps_off, barmerge.lookahead_on)
: security(syminfo.tickerid, tostring(tf), hlc3)), tf, 0, 1)
(curr/prev) - 1
relu(x) => max(x, 0)
lrelu(x, alpha) => relu(x) - alpha * relu(-x)
step(x) => x >= 0 ? 1 : -1
sigmoid(x) => 1 / (1 + exp(-x))
swish(x) => x * sigmoid(x)
f(m) => method==m
vol = useold ? security(syminfo.tickerid, tostring(tf), volume, barmerge.gaps_off, barmerge.lookahead_on)
: security(syminfo.tickerid, tostring(tf), volume)
changed = change(price)
obvvar = cum(changed > 0 ? vol : changed < 0 ? -vol : 0*vol)
prix = showVol ? obvvar : price
x = getdiff(prix, tf)
p = f("Swish") ? swish(x) : f("Step") ? step(x) : f("LReLU") ? lrelu(x, .8) : x
th = thresh/div
long = crossover(p, th)
short= crossunder(p, -th)
lime = color.new(color.lime, 10), fuchsia = color.new(color.fuchsia, 10),
black = color.new(color.black, 100), gray = color.new(color.gray, 50)
bg = long ? lime : short ? fuchsia : black
cl = p > th ? color.green : p < -th ? color.red : color.silver
bgcolor(bg, editable=false)
plot(scaleMinimax(th, mmx, -1, 1), color=lime, editable=false, transp=0)
hline(0, linestyle=hline.style_dotted, title="base line", color=gray, editable=false)
plot(scaleMinimax(-th, mmx, -1, 1), color=fuchsia, editable=false, transp=0)
plot(scaleMinimax(p, mmx, -1, 1), color=cl, style=plot.style_histogram, transp=70, editable=false)
plot(scaleMinimax(p, mmx, -1, 1), color=cl, style=plot.style_linebr, title="prediction", transp=0, editable=false)
strategy.entry("L", true, 1, when=long)
strategy.entry("S", false, 1, when=short)
if (useStop) // in case of using the trailing stop
strategy.exit("L", from_entry="L", trail_points=slPoints, trail_offset=slOffset)
strategy.exit("S", from_entry="S", trail_points=slPoints, trail_offset=slOffset)
alertcondition(long, title='Long', message='Long Signal!')
alertcondition(short, title='Short', message='Short Signal!')
//*** Karobein Oscillator
per = input(8, "Karobein Osc Lookback")
prix2 = ema(price, per)
a = ema(prix2 < prix2[1] ? prix2/prix2[1] : 0, per)
b = ema(prix2 > prix2[1] ? prix2/prix2[1] : 0, per)
c = (prix2/prix2[1])/(prix2/prix2[1] + b)
d = 2*((prix2/prix2[1])/(prix2/prix2[1] + c*a)) - 1
plot(scaleMinimax(d, mmx, -1, 1), color=color.orange, transp=0)
|
MA 10/20 Crossover | https://www.tradingview.com/script/2cbpO8lO-MA-10-20-Crossover/ | StratifyTrade | https://www.tradingview.com/u/StratifyTrade/ | 432 | 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/
// © HunterAlgos
//@version=5
strategy('MA 10/20 Crossover', overlay=true)
ma10 = ta.sma(close, 10)
ma20 = ta.sma(close, 20)
long = ta.cross(ma10, ma20) and ma10 > ma20
short = ta.cross(ma10, ma20) and ma10 < ma20
plot(ma10, title='10', color=color.new(color.yellow, 0), linewidth=2)
plot(ma20, title='20', color=color.new(color.red, 0), linewidth=2)
testStartYear = input(2016, 'Backtest Start Year')
testStartMonth = input(4, 'Backtest Start Month')
testStartDay = input(1, 'Backtest Start Day')
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)
testStopYear = input(2018, 'BackTest Stop Year')
testStopMonth = input(10, 'Backtest Stop Month')
testStopDay = input(15, 'Backtest Stop Day')
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
if time >= testPeriodStart
if time <= testPeriodStop
strategy.entry('Long', strategy.long, 1.0, when=long)
strategy.entry('Short', strategy.short, 1.0, when=short)
|
How To Set Backtest Date Range | https://www.tradingview.com/script/62hUcP6O-How-To-Set-Backtest-Date-Range/ | allanster | https://www.tradingview.com/u/allanster/ | 4,726 | 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
// Revision: 7
//@version=5
strategy(title = "How To Set Backtest Range", shorttitle = "Dates", overlay = true, format = format.price, precision = 8,
default_qty_type = strategy.cash, default_qty_value = 100, initial_capital = 10000, currency = currency.NONE,
slippage = 2, commission_type = strategy.commission.percent, commission_value = 0.25)
// === INPUT MA SOURCES AND LENGTHS ===
i_srcF = input (defval = hlc3, title = "Faster ", inline = 'F')
i_lenF = input.int (defval = 12, title = "Length", minval = 1, step = 1, inline = 'F')
i_srcS = input (defval = hlc3, title = "Slower ", inline = 'S')
i_lenS = input.int (defval = 26, title = "Length", minval = 1, step = 1, inline = 'S')
// === INPUT BACKTEST RANGE ===
i_from = input.time(defval = timestamp("01 Jan 2023 00:00 +0000"), title = "From")
i_thru = input.time(defval = timestamp("01 Mar 2023 00:00 +0000"), title = "Thru")
// === INPUT SHOW PLOT ===
i_show = input (defval = true, title = "Show Date Range")
// === FUNCTION EXAMPLE ===
date() => time >= i_from and time <= i_thru // create date function "within window of time"
// === LOGIC ===
fastMA = ta.ema(i_srcF, i_lenF) // create Fast MA
slowMA = ta.ema(i_srcS, i_lenS) // create Slow MA
crsOvr = ta.crossover (fastMA, slowMA) // true when Fast MA crosses over Slow MA
crsUnd = ta.crossunder(fastMA, slowMA) // true when Fast MA crosses under Slow MA
// === EXECUTION ===
if date() and crsOvr // if "within window of time" AND crossover
strategy.entry("Long", strategy.long) // enter long
if date() and crsUnd // if "within window of time" AND crossunder
strategy.close("Long") // close long
// === PLOTTING ===
bgcolor(color = i_show and date() ? color.new(color.gray, 90) : na) // plot if "Show Date Range" and "within window of time"
plot(series = fastMA, title = 'FastMA', color = color.yellow, linewidth = 2, style = plot.style_line) // plot Fast MA
plot(series = slowMA, title = 'SlowMA', color = color.aqua, linewidth = 2, style = plot.style_line) // plot Slow MA |
Ichimoku + Daily-Candle_X + HULL-MA_X + MacD | https://www.tradingview.com/script/RJBjyl2W-Ichimoku-Daily-Candle-X-HULL-MA-X-MacD/ | SeaSide420 | https://www.tradingview.com/u/SeaSide420/ | 9,034 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SeaSide420
//@version=4
// Any timeFrame/pair , Ichimoku + Daily-Candle_cross + HULL-MA_cross + custom Hull/MacD combination 420 special blend
strategy("Ichimoku + Daily-Candle_X + HULL-MA_X + MacD", shorttitle="٩(̾●̮̮̃̾•̃̾)۶", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, max_bars_back=2999, default_qty_value=100, commission_type=strategy.commission.percent,commission_value=0.25,slippage=1)
Period=input(title="Double HullMA X Period",type=input.integer,defval=14, minval=1)
//SL = input(defval=-1000, title="Stop Loss in $", type=input.float, step=0.001)
//TP = input(defval=1000, title="Target Point in $", type=input.float, step=0.001)
res = input(title="Candle X Resolution", type=input.resolution, defval="D")
price=input(title="Source of Price",type=input.source,defval=open)
hma1=hma(price, Period)
hma2=hma(price[1], Period)
b=hma1>hma2?color.lime:color.red
c=hma1>hma2?color.green:color.red
d=hma1>hma2?color.red:color.green
D1=security(syminfo.tickerid, res, price, barmerge.gaps_off, barmerge.lookahead_off)
D2=security(syminfo.tickerid, res, price[1], barmerge.gaps_off, barmerge.lookahead_off)
conversionPeriod = input(9, minval=1, title="Conversion Line Period")
basePeriod = input(26, minval=1, title="Base Line Period")
laggingSpanPeriod = input(52, minval=1, title="Lagging Span 2 Period")
displacement = input(26, minval=1, title="Displacement")
donchian(len) => avg(lowest(len), highest(len))
conversionLine = donchian(conversionPeriod)
baseLine = donchian(basePeriod)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpanPeriod)
LS=price, offset = -displacement
MACD_Length = input(9)
MACD_fastLength = input(12)
MACD_slowLength = input(26)
MACD = hma(price, MACD_fastLength) - hma(price, MACD_slowLength)
aMACD = hma(MACD, MACD_Length)
//if (strategy.openprofit>TP)
// strategy.close_all(comment="close all")
//closelong = strategy.position_size>0 and strategy.openprofit<SL and hma1>hma2 and price>hma2 or strategy.position_size>0 and strategy.openprofit>TP// or hma1<hma2 and price<hma2
//if (closelong)
// strategy.close("Long",comment="close long")
//closeshort = strategy.position_size<0 and strategy.openprofit<SL and hma1<hma2 and price<hma2 or strategy.position_size<0 and strategy.openprofit>TP// or hma1>hma2 and price>hma2
//if (closeshort)
// strategy.close("Short",comment="close short")
longCondition = hma1>hma2 and D1>D2 and price>hma2 and leadLine1>leadLine2 and MACD>aMACD
if (longCondition)
strategy.entry("Long",strategy.long)
shortCondition = hma1<hma2 and D1<D2 and price<hma2 and leadLine1<leadLine2 and MACD<aMACD
if (shortCondition)
strategy.entry("Short",strategy.short)// /L'-,
// ,'-. /MM . . / L '-,
// . _,--dMMMM\ /MMM `.. / '-,
// : _,--, )MMMMMMMMM),. `QMM ,<> /_ '-,'
// ; ___,--. \MM( `-' )M//MM\ ` ,',.; .-'* ; .'
// | \MMMMMM) \MM\ ,dM//MMM/ ___ < ,; `. )`--' /
// | \MM()M MMM)__ /MM(/MP' ___, \ \ ` `. `. /__, ,'
// | MMMM/ MMMMMM( /MMMMP'__, \ | / `. `-,_\ /
// | MM /MMM---' `--'_ \ |-' |/ `./ .\----.___
// | /MM' `--' __,- \"" |-' |_, `.__) . .F. )-.
// | `--' \ \ |-' |_, _,-/ J . . . J-'-. `-.,
// | __ \`. | | | \ / _ |. . . . \ `-. F
// | ___ / \ | `| ' __ \ | /-' F . . . . \ '`
// | \ \ \ / | __ / \ | |,-' __,- J . . . . . \
// | | / |/ __,- \ ) \ / |_,- __,--' |. .__.----,'
// | |/ ___ \ |'. |/ __,--' `.-;;;;;;;;;\
// | ___ \ \ | | ` __,--' /;;;;;;;;;;;;.
// | \ \ |-'\ ' __,--' /;;;;;;;;;;;;;;\
// \ | | / | __,--' `--;;/ \;-'\
// \ | |/ __,--' / / \ \
// \ | __,--' / / \ \
// \|__,--' _,-;M-K, ,;-;\
// <;;;;;;;; '-;;;;
//a1=plot(hma1,color=c)// remove the "//" from before the plot script if want to see the indicators on chart
//a2=plot(hma2,color=c)// remove the "//" from before the plot script if want to see the indicators on chart
//plot(cross(hma1, hma2) ? hma1 : na, style = circles, color=b, linewidth = 4)// remove the "//" from before the plot script if want to see the indicators on chart
//plot(cross(hma1, hma2) ? hma1 : na, style = line, color=d, linewidth = 4)// remove the "//" from before the plot script if want to see the indicators on chart
//plot(conversionLine, color=#0496ff, title="Conversion Line")// remove the "//" from before the plot script if want to see the indicators on chart
//plot(baseLine, color=#991515, title="Base Line")// remove the "//" from before the plot script if want to see the indicators on chart
//plot(price, offset = -displacement, color=color.black, title="Lagging Span")// remove the "//" from before the plot script if want to see the indicators on chart
//p1=plot (leadLine1, offset = displacement, color=color.green, title="Lead 1")// remove the "//" from before the plot script if want to see the indicators on chart
//p2=plot (leadLine2, offset = displacement, color=color.red, title="Lead 2")// remove the "//" from before the plot script if want to see the indicators on chart
//fill(p1, p2, color = leadLine1 > leadLine2 ? color.green : color.red)// remove the "//" from before the plot script if want to see the indicators on chart
// remove the "//" from before the plot script if want to see the indicators on chart |
How To Auto Set Date Range | https://www.tradingview.com/script/zXEErEs9-How-To-Auto-Set-Date-Range/ | allanster | https://www.tradingview.com/u/allanster/ | 346 | 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 Auto Set Date Range", shorttitle = "AutoDates", 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: 3
// Author: @allanster
// === INPUT MA LENGTHS ===
fastMA = input.int (defval = 12, title = "FastMA Length", minval = 1, step = 1)
slowMA = input.int (defval = 26, title = "SlowMA Length", minval = 1, step = 1)
// === INPUT BACKTEST RANGE ===
useRange = input.string(defval = "WEEKS", title = "Date Range", confirm = false, options = ["ALL", "DAYS", "WEEKS", "MANUAL"])
nDaysOrWeeks = input.int (defval = 52, title = "# Days or Weeks", minval = 1)
fromTime = input.time (defval = timestamp("01 Jan 2021 00:00 +0000"), title = "From Date & Time")
thruTime = input.time (defval = timestamp("01 Jan 2112 00:00 +0000"), title = "Thru Date & Time")
// === INPUT SHOW PLOT ===
showDate = input (defval = true, title = "Show Date Range")
// === FUNCTION EXAMPLE ===
window() => // create function "within window of time"
oneDay = 24 * 60 * 60 * 1000
oneWeek = 7 * oneDay
present = timenow
start = useRange == "DAYS" ? present - nDaysOrWeeks * oneDay :
useRange == "WEEKS" ? present - nDaysOrWeeks * oneWeek : fromTime
finish = useRange == "DAYS" or useRange == "WEEKS" ? timestamp(2112, 1, 1, 23, 59) : thruTime
useRange != "ALL" ? time >= start and time <= finish : true
// === LOGIC ===
crossOv = ta.crossover (ta.ema(hlc3, fastMA), ta.ema(hlc3, slowMA)) // true when fastMA crosses over slowMA
crossUn = ta.crossunder(ta.ema(hlc3, fastMA), ta.ema(hlc3, slowMA)) // true when fastMA crosses under slowMA
// === EXECUTION ===
strategy.entry("L", strategy.long, when=window() and crossOv) // enter long when "within window of time" AND crossover
strategy.close("L", when=window() and crossUn) // exit long when "within window of time" AND crossunder
// === PLOTTING ===
bgcolor(color = showDate and window() ? color.rgb(120,123,134, 90) : na) // plot "within window of dates"
plot(ta.ema(hlc3, fastMA), title = 'FastMA', color = color.rgb(0,188,212), linewidth = 2, style = plot.style_line) // plot FastMA
plot(ta.ema(hlc3, slowMA), title = 'SlowMA', color = color.rgb(255,235,59), linewidth = 2, style = plot.style_line) // plot SlowMA |
WMX Keltner Channels strategy | https://www.tradingview.com/script/OQ7jRpHl-WMX-Keltner-Channels-strategy/ | WMX_Q_System_Trading | https://www.tradingview.com/u/WMX_Q_System_Trading/ | 138 | 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/
// © WMX_Q_System_Trading
//@version=3
strategy(title = "WMX Keltner Channels strategy", shorttitle = "WMX Keltner Channels strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.075)
useTrueRange = input(true)
length = input(20, minval=5)
mult = input(2.618, minval=0.1)
mah =ema(ema( ema(high, length),length),length)
mal =ema(ema( ema(low, length),length),length)
range = useTrueRange ? tr : high - low
rangema =ema(ema( ema(range, length),length),length)
upper = mah + rangema * mult
lower = mal - rangema * mult
ma=(upper+lower)/2
uc = red
lc=green
u = plot(upper, color=uc, title="Upper")
basis=plot(ma, color=yellow, title="Basis")
l = plot(lower, color=lc, title="Lower")
fill(u, basis, color=uc, transp=95)
fill(l, basis, color=lc, transp=95)
strategy.entry("Long", strategy.long, stop = upper, when = strategy.position_size <= 0 and close >upper)
strategy.entry("Short", strategy.short, stop = lower, when = strategy.position_size >= 0 and close<lower)
if strategy.position_size > 0
strategy.exit("Stop Long", "Long", stop = ma)
if strategy.position_size < 0
strategy.exit("Stop Short", "Short", stop = ma)
|
TrendLines with Alerts | https://www.tradingview.com/script/vOyqoCwS-TrendLines-with-Alerts/ | puneetghai | https://www.tradingview.com/u/puneetghai/ | 724 | 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/
// © pune3tghai
//Originally posted by matsu_bitmex
//tried adding alerts on plots and cleared the chart for a cleaner view.
//Publishing the script in hope of getting it improved by someone else.
//Added strategy code for easier calculations
//Needs work on TP and SL part.
//P.S - THE ORIGINAL CODE IS MUCH BETTER BUT I have tried to be more usable and understandable.
//@version=4
strategy("TrendLines with Alerts", overlay=true) //study("TrendLines with Alerts", overlay=true)
//update
length1 = input(20)
check = input(9)
//length2 = input(200)
u=0.0
u := u[1]
l=0.0
l := l[1]
y=0.0
y := y[1]
yl=0.0
yl := yl[1]
angle = 0.0
angle := angle[1]
anglel = 0.0
anglel := anglel[1]
if (highest(length1) == high[check] and highest(length1) == highest(length1)[check] and barssince(barstate.isfirst) > check)
u := high[check]
if (lowest(length1) == low[check] and lowest(length1) == lowest(length1)[check] and barssince(barstate.isfirst) > check)
l := low[check]
p = round(barssince(u == high[check]))
pl = round(barssince(l == low[check]))
if p == 0 and barssince(barstate.isfirst) > check
y := high[abs(p[1]+1+check)]
if pl == 0 and barssince(barstate.isfirst) > check
yl := low[abs(pl[1]+1+check)]
if p == 0
angle := (u-y)/p[1]
if pl == 0
anglel := (l-yl)/pl[1]
uppertrend = u+ (p * angle)
lowertrend = l+ (pl * anglel)
extendup = if barssince(barstate.isfirst) > check
uppertrend[check] + angle[check] * check*2
extenddown = if barssince(barstate.isfirst) > check
lowertrend[check] + anglel[check] * check*2
//plot(l[offset]-u,color=red)
//plot(u[offset]-l,color = green )
plot(lowertrend, color = color.green, transp=30,offset = -check)
plot(extenddown, color = color.green, transp=100)
plot(uppertrend, color = color.red, transp=30, offset = -check)
plot(extendup, color = color.red, transp=100)
//plot(l[offset], color = red)
l1 = lowertrend
l2 = extenddown
u1 = uppertrend
u2 = extendup
l2sell = crossunder(high, l2)
u2buy = crossover(low, u2)
buy1 = (low<=lowertrend) and open>lowertrend and high>lowertrend and close>lowertrend
buy2 = (low<=extenddown) and open>extenddown and high>extenddown and close>extenddown
buy = buy1 or buy2 or u2buy
plotshape(series=buy, title="Buy", style=shape.triangleup, size=size.tiny, color=color.lime, location=location.belowbar)
sell1 = (high>=uppertrend) and open<uppertrend and low<uppertrend and close<uppertrend
sell2 = (high>=extendup) and open<extendup and low<extendup and close<extendup
sell = sell1 or sell2 or l2sell
plotshape(series=sell, title="Sell", style=shape.triangledown, size=size.tiny, color=color.red, location=location.abovebar)
longCond = buy
shortCond = sell
tp = input(0.2, title="Take Profit")
tpbuyval = valuewhen(buy, close, 1) + (tp/100)*(valuewhen(buy, close, 1))
tpsellval = valuewhen(sell, close, 1) - (tp/100)*(valuewhen(sell, close, 1))
sl = input(0.2, title="Stop Loss")
slbuyval = valuewhen(buy, close, 0) - (sl/100)*(valuewhen(buy, close, 0))
slsellval = valuewhen(sell, close, 0) + (sl/100)*(valuewhen(sell, close, 0))
// === STRATEGY ===
tradeType = input("BOTH", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"])
// stop loss
slPoints = input(defval=0, title="Initial Stop Loss Points (zero to disable)", minval=0)
tpPoints = input(defval=0, title="Initial Target Profit Points (zero for disable)", minval=0)
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//
testStartYear = input(2019, "Backtest Start Year", minval=1980)
testStartMonth = input(1, "Backtest Start Month", minval=1, maxval=12)
testStartDay = input(1, "Backtest Start Day", minval=1, maxval=31)
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)
testStopYear = input(9999, "Backtest Stop Year", minval=1980)
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)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//
//
//set up exit parameters
TP = tpPoints > 0 ? tpPoints : na
SL = slPoints > 0 ? slPoints : na
// Make sure we are within the bar range, Set up entries and exit conditions
if testPeriod() and tradeType != "NONE"
strategy.entry("long", strategy.long, when=longCond == true and tradeType != "SHORT")
strategy.entry("short", strategy.short, when=shortCond == true and tradeType != "LONG")
strategy.close("long", when=shortCond == true and tradeType == "LONG")
strategy.close("short", when=longCond == true and tradeType == "SHORT")
strategy.exit("XL", from_entry="long", profit=tpbuyval, loss=slbuyval)
strategy.exit("XS", from_entry="short", profit=tpsellval, loss=slsellval)
// === /STRATEGY ===
//EOF
////ALERT SYNTEX
//alertcondition(longCond, title="Long", message="Killer Market")
//alertcondition(shortCond, title="Short", message="Poopy Market") |
ATR Strategy for most volatile FOREX pairs | https://www.tradingview.com/script/xjPuvhUZ/ | Investoz | https://www.tradingview.com/u/Investoz/ | 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/
// © Investoz
//@version=4
strategy("ATR Strategy FOREX", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
len = input(26, type=input.integer, minval=1, title="Length")
mul = input(1, type=input.float, minval=0, title="Length")
mullow = input(2, type=input.float, minval=0, title="Length")
price = sma(close, 1)
average = ema(close, len)
diff = atr(len) * mul
difflow = atr(len) * mullow
bull_level = average + diff
bear_level = average - difflow
bull_cross = crossunder(price, bear_level)
bear_cross = crossunder(bull_level, price)
FromMonth = input(defval = 8, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 18, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2008, title = "From Year", minval = 2008)
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 = 2020, title = "To Year", minval = 2019)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
startTimeOk() => time >= start and time <= finish ? true : false
if (startTimeOk())
strategy.entry("KOP", strategy.long, when=bull_cross)
strategy.close("KOP", when=bear_cross)
strategy.entry("SALJ", strategy.short, when=bear_cross)
strategy.close("SALJ", when=bull_cross)
plot(price, title="price", color=color.black, transp=50, linewidth=2)
a0 = plot(average, title="average", color=color.red, transp=50, linewidth=1)
a1 = plot(bull_level, title="bull", color=color.green, transp=50, linewidth=1)
a2 = plot(bear_level, title="bear", color=color.red, transp=50, linewidth=1)
fill(a0, a1, color=color.green, transp=97)
fill(a0, a2, color=color.red, transp=97) |
BLANK Strategy + TSL + Backtestrange | https://www.tradingview.com/script/BAvAyyPq-BLANK-Strategy-TSL-Backtestrange/ | Crypto-Oli | https://www.tradingview.com/u/Crypto-Oli/ | 53 | 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/
// © Crypto-Oli
//@version=4
strategy("BLANK Strategy + TSL", initial_capital=5000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, pyramiding=1, commission_value=0.075, overlay=true)
////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
// From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2019, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
////////////////////////////////////////////////////////////////////////////////
/// YOUR INPUTS BELOW - DELET EXAPLES ///
ema1=ema(close,input(3))
ema2=ema(close,input(7))
ema3=ema(close,input(13))
/// PLOTS IF YOU NEED BELOW - DELET EXAPLES ///
plot(ema1, "EMA1", color.yellow)
plot(ema2, "EMA2", color.white)
plot(ema3, "EMA3", color.blue)
/// YOUR CONDITIONS BELOW - DELET EXAPLES ///
longCondition = close>ema1 and ema1>ema2 and ema2>ema3 and time_cond
shortCondition = close<ema1 and ema1<ema2 and ema2<ema3 and time_cond
/// EXECUTION ///
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Long Exit", "Long", trail_points = close * 0.05 / syminfo.mintick, trail_offset = close * 0.02 / syminfo.mintick)
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", "Short", trail_points = close * 0.05 / syminfo.mintick, trail_offset = close * 0.02 / syminfo.mintick) |
Variable Moving Average Strategy | https://www.tradingview.com/script/j8hsADAF-variable-moving-average-strategy/ | laptevmaxim92 | https://www.tradingview.com/u/laptevmaxim92/ | 130 | 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/
// © laptevmaxim92
//@version=4
strategy("Variable Moving Average Strategy", overlay=true)
src=close
l =input(5, title="VMA Length")
std=input(true, title="Show Trend Direction Colors")
utp = input(false, "Use take profit?")
pr = input(100, "Take profit pips")
usl = input(false, "Use stop loss?")
sl = input(100, "Stop loss pips")
fromday = input(01, defval=01, minval=01, maxval=31, title="From Day")
frommonth = input(01, defval=01, minval= 01, maxval=12, title="From Month")
fromyear = input(2000, minval=1900, maxval=2100, title="From Year")
today = input(31, defval=01, minval=01, maxval=31, title="To Day")
tomonth = input(12, defval=12, minval=01, maxval=12, title="To Month")
toyear = input(2019, minval=1900, maxval=2100, title="To Year")
use_date = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))
k = 1.0/l
pdm = 0.0
pdm := max((src - src[1]), 0)
mdm = 0.0
mdm := max((src[1] - src), 0)
pdmS = 0.0
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS = 0.0
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = 0.0
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS = 0.0
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = 0.0
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = highest(iS, l)
llv = lowest(iS, l)
d1 = hhv - llv
vI = (iS - llv)/d1
vma = 0.0
vma := (1 - k*vI)*nz(vma[1]) + k*vI*src
vmaC=(vma > vma[1]) ? color.lime : (vma<vma[1]) ? color.red : (vma==vma[1]) ? color.yellow : na
plot(vma, color=std?vmaC:color.white, linewidth=3, title="VMA")
longCondition = vma > vma[1]
if (longCondition and use_date)
strategy.entry("BUY", strategy.long)
shortCondition = vma < vma[1]
if (shortCondition and use_date)
strategy.entry("SELL", strategy.short)
if (utp and not usl and use_date)
strategy.exit("TP", "BUY", profit = pr)
strategy.exit("TP", "SELL", profit = pr)
if (usl and not utp and use_date)
strategy.exit("SL", "BUY", loss = sl)
strategy.exit("SL", "SELL", loss = sl)
if (usl and utp and use_date)
strategy.exit("TP/SL", "BUY", loss = sl, profit = pr)
strategy.exit("TP/SL", "SELL", loss = sl, profit = pr) |
Noro's Bands Strategy | https://www.tradingview.com/script/OOBWuKih-noro-s-bands-strategy/ | ROBO_Trading | https://www.tradingview.com/u/ROBO_Trading/ | 268 | 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 Bands Strategy", shorttitle = "Bands", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.1)
//Sattings
needlong = input(true, defval = true, title = "Long")
needshort = input(true, defval = true, title = "Short")
lotsize = input(100, defval = 100, minval = 1, maxval = 10000, title = "Lot, %")
len = input(20, defval = 20, minval = 1, maxval = 1000, title = "Length")
src = input(ohlc4, title = "Source")
showbb = input(true, title = "Show Bands")
showof = input(true, title = "Show Offset")
showbg = input(false, title = "Show Background")
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")
//PriceChannel
lasthigh = highest(src, len)
lastlow = lowest(src, len)
center = (lasthigh + lastlow) / 2
//Distance
dist = abs(src - center)
distsma = sma(dist, len)
hd = center + distsma
ld = center - distsma
hd2 = center + distsma * 2
ld2 = center - distsma * 2
//Trend
trend = 0
trend := high > hd2 ? 1 : low < ld2 ? -1 : trend[1]
bgcol = showbg == false ? na : trend == 1 ? color.lime : color.red
bgcolor(bgcol, transp = 70)
//Lines
colo = showbb == false ? na : color.black
offset = showof ? 1 : 0
plot(hd2, color = colo, linewidth = 1, transp = 0, offset = offset, title = "High band 2")
plot(hd, color = colo, linewidth = 1, transp = 0, offset = offset, title = "High band 1")
plot(center, color = colo, linewidth = 1, transp = 0, offset = offset, title = "center")
plot(ld, color = colo, linewidth = 1, transp = 0, offset = offset, title = "Low band 1")
plot(ld2, color = colo, linewidth = 1, transp = 0, offset = offset, title = "Low band 2")
//Trading
size = strategy.position_size
needstop = needlong == false or needshort == false
truetime = time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)
lot = 0.0
lot := size != size[1] ? strategy.equity / close * lotsize / 100 : lot[1]
if distsma > 0
strategy.entry("Long", strategy.long, lot, stop = hd2, when = truetime and needlong)
strategy.entry("Short", strategy.short, lot, stop = ld2, when = truetime and needshort)
sl = size > 0 ? ld2 : size < 0 ? hd2 : na
if size > 0 and needstop
strategy.exit("Stop Long", "Long", stop = sl)
if size < 0 and needstop
strategy.exit("Stop Short", "Short", stop = sl)
if time > timestamp(toyear, tomonth, today, 23, 59)
strategy.close_all()
strategy.cancel("Long")
strategy.cancel("Short") |
Pine Utils | https://www.tradingview.com/script/NONVj8eU-Pine-Utils/ | felipefs | https://www.tradingview.com/u/felipefs/ | 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/
// © felipefs
//@version=4
strategy("Meu Script", overlay=true)
plot(ohlc4)
//Funçao de Datas
testStartYear = input(2018, "Backtest Start Year")
testStartMonth = input(6, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testStopYear = input(2019, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false
//Funções de Trailing Stop
long_stop_price = 0.0
short_stop_price = 0.0
long_trail_perc = 0
short_trail_perc = 0
long_stop_price := if (strategy.position_size > 0)
stopValue = close * (1 - long_trail_perc)
max(stopValue, long_stop_price[1])
else
0
short_stop_price := if (strategy.position_size < 0)
stopValue = close * (1 + short_trail_perc)
min(stopValue, short_stop_price[1])
else
999999
//Função de Debug
debug(value) =>
x = bar_index
y = close
label.new(x, y, tostring(value))
//Take Profit
profit = close * (1 + 0.12)
strategy.entry("Long", true)
strategy.exit("Take Profit 1 Long", from_entry="Long", limit=profit, qty_percent=50.0)
//ATR Stop
// xATRTrailingStopLong = 0.0
// xATR = atr(nATRPeriod)
// nLossLong = nATRMultipLong * xATR
// if (strategy.position_size > 0)
// xATRTrailingStopLong := max(nz(xATRTrailingStopLong[1]), close - nLossLong) |
expected range STRATEGY | https://www.tradingview.com/script/kJM4hmpk-expected-range-STRATEGY/ | Jomy | https://www.tradingview.com/u/Jomy/ | 211 | 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/
// © Jomy
//@version=4
//2h chart BITMEX:XBTUSD
//use on low leverage 1-2x only
strategy("expected range STRATEGY",overlay=false,initial_capital=1000,precision=2)
leverage=input(1,"leverage",step=.5)
tp=input(53,"take profit %",step=1)
sl=input(7,"stoploss %",step=1)
stoploss=1-(sl/100)
plot(stoploss)
level=input(.70,"level to initiate trade",step=.02)
closelevel=input(0.0,"level to close trade",step=.02)
levelshort=input(.68,"level to initiate trade",step=.02)
closelevelshort=input(0.0,"level to close trade",step=.02)
// === INPUT BACKTEST RANGE ===
startMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
startDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
startYear = input(defval = 2010, title = "From Year", type = input.integer, minval = 1970)
endMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
endDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
endYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
// === FUNCTION EXAMPLE ===
start = timestamp(startYear, startMonth, startDay, 00, 00) // backtest start window
finish = timestamp(endYear, endMonth, endDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
wa=input(1.158,"weight a",step=.2)
wb=input(1.119,"weight b",step=.2)
wc=input(1.153,"weight c",step=.2)
wd=input(1.272,"weight d",step=.2)
we=input(1.295,"weight e",step=.2)
wf=input(1.523,"weight f",step=.2)
wg=input(1.588,"weight g",step=.2)
wh=input(2.100,"weight h",step=.2)
wi=input(1.816,"weight i",step=.2)
wj=input(2.832,"weight j",step=.2)
a=1
b=2
c=3
d=5
e=8
f=13
g=21
h=34
i=55
j=89
n=0
n:=if volume > -1
nz(n[1])+1
ra=highest(high,a)-lowest(low,a)
aa=sma(ohlc4,a)
ha=aa[1]+ra[1]/2
la=aa[1]-ra[1]/2
rb=highest(high,b)-lowest(low,b)
ab=sma(ohlc4,b)
hb=ab[1]+rb[1]/2
lb=ab[1]-rb[1]/2
rc=highest(high,c)-lowest(low,c)
ac=sma(ohlc4,c)
hc=ac[1]+rc[1]/2
lc=ac[1]-rc[1]/2
rd=highest(high,d)-lowest(low,d)
ad=sma(ohlc4,d)
hd=ad[1]+rd[1]/2
ld=ad[1]-rd[1]/2
re=highest(high,e)-lowest(low,e)
ae=sma(ohlc4,e)
he=ae[1]+re[1]/2
le=ae[1]-re[1]/2
rf=highest(high,f)-lowest(low,f)
af=sma(ohlc4,f)
hf=af[1]+rf[1]/2
lf=af[1]-rf[1]/2
rg=highest(high,g)-lowest(low,g)
ag=sma(ohlc4,g)
hg=ag[1]+rg[1]/2
lg=ag[1]-rg[1]/2
rh=highest(high,h)-lowest(low,h)
ah=sma(ohlc4,h)
hh=ah[1]+rh[1]/2
lh=ah[1]-rh[1]/2
ri=highest(high,i)-lowest(low,i)
ai=sma(ohlc4,i)
hi=ai[1]+ri[1]/2
li=ai[1]-ri[1]/2
rj=highest(high,j)-lowest(low,j)
aj=sma(ohlc4,j)
hj=aj[1]+rj[1]/2
lj=aj[1]-rj[1]/2
placea=((close-la)/(ha-la)-.5)*-100
placeb=((close-lb)/(hb-lb)-.5)*-100
placec=((close-lc)/(hc-lc)-.5)*-100
placed=((close-ld)/(hd-ld)-.5)*-100
placee=((close-le)/(he-le)-.5)*-100
placef=((close-lf)/(hf-lf)-.5)*-100
placeg=((close-lg)/(hg-lg)-.5)*-100
placeh=((close-lh)/(hh-lh)-.5)*-100
placei=((close-li)/(hi-li)-.5)*-100
placej=((close-lj)/(hj-lj)-.5)*-100
sentiment=((placea/j)*ra*wa+(placeb/i)*rb*wb+(placec/h)*rc*wc+(placed/g)*rd*wd+(placee/f)*re*we+(placef/e)*rf*wf+(placeg/d)*rg*wg+(placeh/c)*rh*wh+(placei/b)*ri*wi+(placej/a)*rj*wj)/(wa+wb+wc+wd+we+wf+wg+wh+wi+wj)
deltalong=0.0
deltalong:=if sentiment>0
nz(deltalong[1])+sentiment-sentiment[1]
else
0
deltashort=0.0
deltashort:=if sentiment<0
nz(deltashort[1])+((sentiment-sentiment[1])*-1)
else
0
//plot(sentiment*-1,color=color.blue)
//plot(deltalong,color=color.red)
//plot(deltashort,color=color.lime)
peakfindlong=highest(deltalong,j)*level
peakfindshort=highest(deltashort,j)*levelshort
contracts=(strategy.equity/close)*leverage
//reason for o is this strategy makes dumb trades before the sentiment line crosses the 0 point the first time
o=0
o:=if cross(0,sentiment) and n>j
1
else
nz(o[1])
long=deltashort>peakfindlong and o==1
short=deltalong>peakfindshort and o==1
longstart=0.0
longstart:=if strategy.position_size>0 and strategy.position_size[1]<=0
close
else
nz(longstart[1])
shortstart=0.0
shortstart:=if strategy.position_size<0 and strategy.position_size[1]>=0
close
else
nz(shortstart[1])
highsincelong = 0.0
highsincelong := if strategy.position_size>0
max(max(highsincelong[1],high),high[1])
else
0
lowsinceshort = 1000000.0
lowsinceshort := if strategy.position_size<0
min(min(lowsinceshort[1],low),low[1])
else
10000000
closelong=strategy.position_size > 0 and ((highsincelong/longstart-1)*100) > tp
closeshort=strategy.position_size < 0 and ((shortstart/lowsinceshort-1)*100) > tp
stoptrade=0
stoptrade:= if closelong
1
else
nz(stoptrade[1])
stoptrade:= if short and stoptrade[1]==1
0
else
stoptrade
stoptrade:= if closeshort
-1
else
stoptrade
stoptrade:= if long and stoptrade[1]==-1
0
else
stoptrade
if(closelong)
strategy.close("Long1")
pnllong = ((close - strategy.position_avg_price) / strategy.position_avg_price)*100
pnlshort = ((strategy.position_avg_price-close) / strategy.position_avg_price) *100
plot (strategy.position_size > 0 ?(highsincelong/longstart-1)*100 : 0.0,color=color.lime,linewidth=2)
plot (strategy.position_size < 0 ?(shortstart/lowsinceshort-1)*100 : 0.0,color=color.red,linewidth=2)
plot( strategy.position_size > 0 ? pnllong:0, color=strategy.position_size > 0 ?color.yellow:color.black,linewidth=2 )
plot( strategy.position_size < 0 ? pnlshort:0, color=strategy.position_size < 0 ?color.orange:color.black,linewidth=2)
longuntilshort=0
longuntilshort:=if long
1
else
if short
-1
else
nz(longuntilshort[1])
bgcolor(stoptrade!=0?color.black:longuntilshort==1?color.lime:longuntilshort==-1?color.red:na,transp=70)
if(long and stoptrade==0 and window())
strategy.entry("Long1",strategy.long,qty=max(.000001,min(contracts,1000000000)))
if(closelong)
strategy.close("Long1")
strategy.exit("Long1",stop=longstart * stoploss,when = strategy.position_size>0)
if(short and stoptrade==0 and window())
strategy.entry("Short1",strategy.short,max(.000001,min(contracts,1000000000)))
if(closeshort)
strategy.close("Short1")
strategy.exit("Long1",stop=shortstart / stoploss,when = strategy.position_size<0) |
Bollinger Band Breakout | https://www.tradingview.com/script/UHsvM5JR-Bollinger-Band-Breakout/ | Senthaamizh | https://www.tradingview.com/u/Senthaamizh/ | 736 | 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
//@version=4
strategy(title="Bollinger Band Breakout", shorttitle = "BB-BO",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true)
source = close
length = input(20, minval=1, title = "Period") //Length of the Bollinger Band
mult = input(1.5, minval=0.001, maxval=50, title = "Standard Deviation") // Use 1.5 SD for 20 period MA; Use 2 SD for 10 period MA
exit = input(1, minval=1, maxval=2,title = "Exit Option") // Use Option 1 to exit using lower band; Use Option 2 to exit using moving average
basis = sma(source, length)
dev = mult * stdev(source, length)
upper = basis + dev
lower = basis - dev
if (crossover(source, upper))
strategy.entry("Long", strategy.long)
if(exit==1)
if (crossunder(source, lower))
strategy.close("Long")
if(exit==2) //basis is good for N50 but lower is good for BN (High volatility)
if (crossunder(source, basis))
strategy.close("Long")
plot(basis, color=color.red,title= "SMA")
p1 = plot(upper, color=color.blue,title= "UB")
p2 = plot(lower, color=color.blue,title= "LB")
fill(p1, p2)
|
M-SQUEEZE | https://www.tradingview.com/script/CDahf1uS/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 637 | 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(title="M-SQUEEZE", overlay = true, initial_capital = 10000, pyramiding = 1, currency = "USD", calc_on_order_fills = false, calc_on_every_tick = false,
default_qty_type = strategy.fixed, default_qty_value = 10, commission_value = 0.2, commission_type = strategy.commission.cash_per_contract)
//study(title="M-SQUEEZE", overlay = true)
// ███▓▒░░ INITIAL SETTINGS ░░▒▓███
Positions = input("LONG ONLY", "LONG / SHORT", options = ["LONG & SHORT","LONG ONLY"])
Long_only = Positions == "LONG ONLY" ? true : na
// ███▓▒░░ VARIABLES ░░▒▓███
var bool longCond = na, var bool shortCond = na
var int CondIni_long0 = 0, var int CondIni_short0 = 0
var int CondIni_long = 0, var int CondIni_short = 0
var bool SMI_longCond = na, var bool SMI_shortCond = na
var bool RSI_longCond = na, var bool RSI_shortCond = na
var bool ADX_longCond = na, var bool ADX_shortCond = na
var bool SAR_longCond = na, var bool SAR_shortCond = na
// ███▓▒░░ SQUEEZE MOMENTUM INDICATOR ░░▒▓███
Act_SMI = input(true, "SQUEEZE MOMENTUM INDICATOR")
BB_length = input(85, title="BOLLINGER BANDS LENGTH", minval = 1)
BB_mult = input(2.1, title="BOLLINGER BANDS MULTI-FACTOR", minval = 0.1, step = 0.1)
KC_length = input(38, title="KELTNER CHANNEL LENGTH", minval = 1)
KC_mult = input(2.0, title="KELTNER CHANNEL MULTI-FACTOR", minval = 0.1, step = 0.1)
SQUEEZE_M(_src,_BB_length,_BB_mult,_KC_length,_KC_mult)=>
// Calculate BB
basis = sma(_src, _BB_length)
dev = _BB_mult * stdev(_src, _BB_length)
upperBB = basis + dev
lowerBB = basis - dev
// Calculate KC
ma = sma(_src, _KC_length)
rangema = sma(tr, _KC_length)
upperKC = ma + rangema * _KC_mult
lowerKC = ma - rangema * _KC_mult
// Squeeze
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
nosqz = sqzOn == false and sqzOff == false
// Linear Regression curve
val = linreg(_src - avg(avg(highest(high, _KC_length), lowest(low, _KC_length)), sma(close, _KC_length)), _KC_length, 0)
[nosqz,val]
[NOSQZ,VAL] = SQUEEZE_M(close,BB_length,BB_mult,KC_length,KC_mult)
barcolor(iff(VAL > 0, iff(VAL > nz(VAL[1]), color.lime, color.green), iff(VAL < nz(VAL[1]), color.red, color.maroon)))
// ███▓▒░░ SAR ░░▒▓███
Act_SAR = input(true, "PARABOLIC SAR")
Sst = input (0.73, "SAR STAR", step=0.01, minval = 0.01)
Sinc = input (0.5, "SAR INC", step=0.01, minval = 0.01)
Smax = input (0.06, "SAR MAX", step=0.01, minval = 0.01)
SAR = sar(Sst, Sinc, Smax)
plot(SAR, style = plot.style_cross, title = "SAR")
// ███▓▒░░ RSI VOLUME WEIGHTED ░░▒▓███
Act_RSI = input(true, "RSI VOLUME WEIGHTED")
RSI_len = input(22, "RSI LENGHT", minval = 1)
RSI_obos = input(45,title="RSI CENTER LINE", type=input.integer, minval = 1)
WiMA(_src, _length)=>
var float MA_s=0.0
MA_s:=(_src + nz(MA_s[1] * (_length-1)))/_length
MA_s
RSI_Volume(fv, length)=>
up=iff(fv>fv[1],abs(fv-fv[1])*volume,0)
dn=iff(fv<fv[1],abs(fv-fv[1])*volume,0)
upt=WiMA(up,length)
dnt=WiMA(dn,length)
100*(upt/(upt+dnt))
RSI_V = RSI_Volume(close, RSI_len)
// ███▓▒░░ STRATEGY ░░▒▓███
SMI_longCond := (Act_SMI ? (VAL > 0 and (VAL > nz(VAL[1])) and not NOSQZ) : RSI_longCond)
RSI_longCond := (Act_RSI ? (RSI_V > RSI_obos) : SAR_longCond)
SAR_longCond := (Act_SAR ? (SAR < close) : SMI_longCond)
SMI_shortCond := (Act_SMI ? (VAL < 0 and (VAL < nz(VAL[1])) and not NOSQZ) : RSI_shortCond)
RSI_shortCond := (Act_RSI ? (RSI_V < RSI_obos) : SAR_shortCond)
SAR_shortCond := (Act_SAR ? (SAR > close) : SMI_shortCond)
longCond := SMI_longCond and RSI_longCond and SAR_longCond
shortCond := SMI_shortCond and RSI_shortCond and SAR_shortCond
CondIni_long0 := longCond ? 1 : shortCond ? -1 : CondIni_long0[1]
CondIni_short0 := longCond ? 1 : shortCond ? -1 : CondIni_short0[1]
longCondition0 = (longCond and CondIni_long0[1] == -1)
shortCondition0 = (shortCond and CondIni_short0[1] == 1)
CondIni_long := longCond[1] ? 1 : shortCond[1] ? -1 : CondIni_long[1]
CondIni_short := longCond[1] ? 1 : shortCond[1] ? -1 : CondIni_short[1]
longCondition = (longCond[1] and CondIni_long[1] == -1)
shortCondition = (shortCond[1] and CondIni_short[1] == 1)
// ███▓▒░░ ALERTS & SIGNALS ░░▒▓███
plotshape(longCondition, title = "Long Signal", style = shape.triangleup, location = location.belowbar, color = color.blue, transp = 0, size = size.tiny)
plotshape(shortCondition, title = "Short Signal", style = shape.triangledown, location = location.abovebar, color = #FF0000, transp = 0, size = size.tiny)
//alertcondition(longCondition, title="Long Alert", message = "LONG")
//alertcondition(shortCondition, title="Short Alert", message = "SHORT")
// ███▓▒░░ BACKTESTING ░░▒▓███
Act_BT = input(true, "BACKTEST 💹")
testStartYear = input(2018, "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)
testPeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false
strategy.entry("Long", strategy.long, when = longCondition0 and testPeriod and Act_BT)
strategy.close("Long", when = Long_only and shortCondition0 and testPeriod and Act_BT)
strategy.entry("Short", strategy.short, when = not Long_only and shortCondition0 and testPeriod and Act_BT) |
Breakout Strategy #1 | https://www.tradingview.com/script/BTC1dwCT-Breakout-Strategy-1/ | Yo_adriiiiaan | https://www.tradingview.com/u/Yo_adriiiiaan/ | 297 | 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/
// © Yo_adriiiiaan
//@version=4
strategy("Breakout Strategy", overlay = true, commission_type=strategy.commission.percent,commission_value=0, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
left = input(10)
right = input(10)
pivot_high = 0.000
pivot_low = 0.000
pivot_high := nz(pivothigh(high,left,right), pivot_high[1])
pivot_low := nz(pivotlow(low,left,right), pivot_low[1])
plot(pivot_high)
plot(pivot_low)
breakout_bull = close > pivot_high[1]
breakdown_bear = close < pivot_low[1]
testStartYear = input(2017, "Backtest Start Year")
testStartMonth = input(8, "Backtest Start Month")
testStartDay = input(20, "Backtest Start Day")
testStartHour = input(0, "Backtest Start Hour")
testStartMin = input(0, "Backtest Start Minute")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,testStartHour,testStartMin)
testStopYear = input(2099, "Backtest Stop Year")
testStopMonth = input(1, "Backtest Stop Month")
testStopDay = input(30, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
barcolor(close > pivot_high[1]? color.green:close < pivot_low[1]? color.red:close < pivot_high[1]? color.orange:na)
strategy.entry("Long", strategy.long, when = breakout_bull and testPeriod())
strategy.close_all(when = breakdown_bear and testPeriod())
//strategy.entry("Short", strategy.short, when = breakdown_bear)
alertcondition( breakout_bull, title = "Bullish Breakout")
alertcondition(breakdown_bear, title = "Bearish Breakdown") |
Donchian Moving Average System | https://www.tradingview.com/script/zcwztQsU/ | dongyun | https://www.tradingview.com/u/dongyun/ | 89 | 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)
longperiod = input(20,'长线')
shortperiod = input(5,'短线')
bandfactor = input(1.0,'')
TrueHigh = 0.0
TrueLow = 0.0
TrueRange = 0.0
TrueHigh := close[1] > high ? close[1] : high
TrueLow := close[1] < low ? close[1] : low
TrueRange := TrueHigh - TrueLow
AvgTrueRange = sma(TrueRange,longperiod)
MAlong = sma(close,longperiod)
MAshort = sma(close,shortperiod)
band = AvgTrueRange * bandfactor
if close > MAlong[1] + band[1] and close > MAshort[1] + band[1]
strategy.entry("Long", strategy.long, when=strategy.position_size < 1)
else
if close < MAlong[1] - band[1] and close < MAshort[1] - band[1]
strategy.entry("Short", strategy.short, when=strategy.position_size > -1)
if close < MAlong[1] - band[1] or close < MAshort[1] - band[1]
strategy.close("Long", when=strategy.position_size > 0)
else
if close > MAlong[1] + band[1] or close > MAshort[1] + band[1]
strategy.close("Short", when=strategy.position_size < 0) |
Trend Following or Mean Reverting | https://www.tradingview.com/script/JTEmA2hf-Trend-Following-or-Mean-Reverting/ | Senthaamizh | https://www.tradingview.com/u/Senthaamizh/ | 201 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Senthaamizh
//Identifies whether the instrument is trending or mean reverting
//@version=4
strategy("Trend Following or Mean Reverting",shorttitle = "TF/MR",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true)
buy = close>high[1]
sell = close<low[1]
if (buy)
strategy.entry("Long", strategy.long,qty=1)
if (sell)
strategy.entry("Short", strategy.short,qty=1)
|
Long Term Long/Short Strategy (Pair Trading) | https://www.tradingview.com/script/G1P0dpHu-Long-Term-Long-Short-Strategy-Pair-Trading/ | danilogalisteu | https://www.tradingview.com/u/danilogalisteu/ | 147 | 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("Long Term L/S", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
base = input("BMFBOVESPA:IBOV")
period = input(5, 'SMA Period', input.integer)
resolution = input(title="SMA Resolution", type=input.resolution, defval='M')
strat = input(title="Strategy", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"])
strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1
base_cl = security((base), resolution, close)
base_ma = sma(base_cl, period)
longCondition = crossover(base_cl, base_ma)
if (longCondition)
if strat_val > -1
strategy.entry("LONG", strategy.long)
if strat_val < 1
strategy.close("SHORT")
shortCondition = crossunder(base_cl, base_ma)
if (shortCondition)
if strat_val > -1
strategy.close("LONG")
if strat_val < 1
strategy.entry("SHORT", strategy.short)
//plot(longCondition?1:0, 'L', color.blue)
//plot(shortCondition?-1:0, 'S', color.red) |
Why is it ok to backtest on TradingView from now on! | https://www.tradingview.com/script/9CG43Ho2-Why-is-it-ok-to-backtest-on-TradingView-from-now-on/ | Peter_O | https://www.tradingview.com/u/Peter_O/ | 291 | 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/
// © Peter_O
//@version=4
strategy(title = "NoBackTestBugAnymore", overlay = true, pyramiding = 0, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.fixed, default_qty_value=100000, calc_on_every_tick=false, max_bars_back=5000)
GoLong=crossover(rsi(close,14),20)
GoShort=crossunder(rsi(close,14),80)
KillShort=GoLong
KillLong=GoShort
strategy.entry("long", strategy.long, when=GoLong)
strategy.entry("short", strategy.short, when=GoShort)
strategy.close("long", when=KillLong)
strategy.close("short", when=KillShort)
strategy.exit("XL", from_entry = "long", loss = 40, profit=30)
strategy.exit("XS", from_entry = "short", loss = 40, profit=30) |
Grover Llorens Activator Strategy Analysis | https://www.tradingview.com/script/VuYM89Tw-Grover-Llorens-Activator-Strategy-Analysis/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 699 | 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 & Lucía Llorens
//@version=4
strategy("Grover Llorens Activator")
length = input(480),mult = input(14),src = input(close)
//----
ts = 0.
diff = src - nz(ts[1],src[1])
atr = atr(length)
//----
up = crossover(diff,0)
dn = crossunder(diff,0)
val = valuewhen(up or dn,atr/length,0)
bars = barssince(up or dn)
ts := up ? nz(ts[1],src) - atr*mult : dn ? nz(ts[1],src) + atr*mult : nz(ts[1],src) + sign(diff)*val*bars
//----
if up
strategy.entry("Buy", strategy.long)
if dn
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) |
kurdistan MACD & RSI & EMA | https://www.tradingview.com/script/d3VaCs8a-kurdistan-MACD-RSI-EMA/ | Mokri | https://www.tradingview.com/u/Mokri/ | 255 | 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/
// © Mokri
//@version=4
strategy("kurdistan MACD & RSI & EMA ", 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.yellow)
plot(_rsi_signal, color=color.green)
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)
|
Donchian Channel Strategy | https://www.tradingview.com/script/ZZ0T9Wc7-Donchian-Channel-Strategy/ | RafaelPiccolo | https://www.tradingview.com/u/RafaelPiccolo/ | 393 | 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("Donchian Channel Strategy", overlay=true)
length = input(20)
longRule = input("Higher High", "Long Entry", options=["Higher High", "Basis"])
shortRule = input("Lower Low", "Short Entry", options=["Lower Low", "Basis"])
hh = highest(high, length)
ll = lowest(low, length)
up = plot(hh, 'Upper Band', color = color.green)
dw = plot(ll, 'Lower Band', color = color.red)
mid = (hh + ll) / 2
midPlot = plot(mid, 'Basis', color = color.orange)
fill(up, midPlot, color=color.green, transp = 95)
fill(dw, midPlot, color=color.red, transp = 95)
if (not na(close[length]))
strategy.entry("Long", strategy.long, stop=longRule=='Basis' ? mid : hh)
strategy.entry("Short", strategy.short, stop=shortRule=='Basis' ? mid : ll)
|
Squeeze Breakout using BB and KC [v1.0][Bishnu103] | https://www.tradingview.com/script/eaDmt5hj-Squeeze-Breakout-using-BB-and-KC-v1-0-Bishnu103/ | Bishnu103 | https://www.tradingview.com/u/Bishnu103/ | 365 | 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="Squeeze Breakout using BB and KC [v1.0][Bishnu103]",shorttitle="BB BREAKOUT",overlay=true,calc_on_every_tick=true,backtest_fill_limits_assumption=2)
// ***********************************************************************************************************************
// input variables
bb_squeeze_switch = input(title="BB Squeeze Check", type=input.bool, defval=true)
bb_squeeze_width = input(title="BB Squeeze Width", minval=1.0, defval=3.0)
bb_in_kc_switch = input(title="BB within KC Check", type=input.bool, defval=false)
ema_trend_switch = input(title="EMA Trend Check", type=input.bool, defval=false)
ma200_trend_switch = input(title="200MA Trend Check", type=input.bool, defval=true)
vol_check_switch = input(title="Average Volume Check", type=input.bool, defval=false)
vol_check_length = input(title="No of bars for Volume Check", minval=1, maxval=20, defval=20)
buy_session = input(title="Buy 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)
show_kc_switch = input(title="Show KC", type=input.bool, defval=true)
show_8ema_switch = input(title="Show 8EMA", type=input.bool, defval=true)
show_emas_switch = input(title="Show EMAs", type=input.bool, defval=false)
//
bbLength = input(title="BB Length", minval=1, defval=20)
bbStdDev = input(title="BB StdDev", minval=1, defval=2)
kcLength = input(title="KC Length", minval=1, defval=20)
kcMult = input(title="KC Mult", defval=1.5)
atrLength = input(title="ATR Length", minval=1, defval=20)
// ***********************************************************************************************************************
// global variables
closed_above_bb = false
closed_below_bb = false
long_entry = false
short_entry = false
// variable values available across candles
var entry_price = 0.0
var sl_price = 0.0
var exit_price = 0.0
var candle_count = 0
// ***********************************************************************************************************************
// function to return bollinger band values based on candle poition passed
getBB(pos) =>
float basis = sma(close[pos], bbLength)
float dev = bbStdDev * stdev(close[pos], bbLength)
[basis, basis + dev, basis - dev]
// function to return Keltner Channel values based on candle poition passed
getKC(pos) =>
mKC = ema(close[pos],kcLength)
range = kcMult * atr(atrLength)[pos]
uKC = mKC + range
lKC = mKC - range
[mKC,uKC,lKC]
// 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)
[mBB_1,uBB_1,lBB_1] = getBB(1)
// if a candle closes above bb and previous candle closed inside bb then it's a bullish signal
if close[0] > uBB_0
closed_above_bb := true
entry_price := high[0]
// if a candle closes above bb and previous candle closed inside bb then it's a bullish signal
if close[0] < lBB_0
closed_below_bb := true
entry_price := low[0]
// check if BB is in squeeze
bb_in_squeeze = bb_squeeze_switch ? ((uBB_1 - lBB_1) < (atr(20)[1] * bb_squeeze_width)) : true
// 6 candle's bb prior to the alert candle, are within keltner channel on either upper side of the bands or on lower side of the bands
// bb
[mBB_2,uBB_2,lBB_2] = getBB(2)
[mBB_3,uBB_3,lBB_3] = getBB(3)
[mBB_4,uBB_4,lBB_4] = getBB(4)
[mBB_5,uBB_5,lBB_5] = getBB(5)
[mBB_6,uBB_6,lBB_6] = getBB(6)
// kc
[mKC_1,uKC_1,lKC_1] = getKC(1)
[mKC_2,uKC_2,lKC_2] = getKC(2)
[mKC_3,uKC_3,lKC_3] = getKC(3)
[mKC_4,uKC_4,lKC_4] = getKC(4)
[mKC_5,uKC_5,lKC_5] = getKC(5)
[mKC_6,uKC_6,lKC_6] = getKC(6)
// check if either side 6 candle's bb are inside kc
lower_squeeze_is_good = uBB_1 < uKC_1 and uBB_2 < uKC_2 and uBB_3 < uKC_3 and uBB_4 < uKC_4 and uBB_5 < uKC_5 and uBB_6 < uKC_6
upper_squeeze_is_good = lBB_1 > lKC_1 and lBB_2 > lKC_2 and lBB_3 > lKC_3 and lBB_4 > lKC_4 and lBB_5 > lKC_5 and lBB_6 > lKC_6
squeeze_is_good = bb_in_kc_switch ? (upper_squeeze_is_good or lower_squeeze_is_good) : true
// EMAs (8, 21, 34, 55, 89) should be aligned in sequence
ema_8 = ema(close,8)
ema_21 = ema(close,21)
ema_34 = ema(close,34)
ema_55 = ema(close,55)
ema_89 = ema(close,89)
ema_trend_check1 = ema_trend_switch and closed_above_bb and ema_8 > ema_21 and ema_21 > ema_34 and ema_34 > ema_55 and ema_55 > ema_89
ema_trend_check2 = ema_trend_switch and closed_below_bb and ema_8 < ema_21 and ema_21 < ema_34 and ema_34 < ema_55 and ema_55 < ema_89
ema_trend_check = ema_trend_switch ? (ema_trend_check1 or ema_trend_check2) : true
// average volume check
avg_vol = sma(volume,vol_check_length)
avg_vol_is_good = vol_check_switch ? (volume > avg_vol) : true
// consolidation
//long_consolidation = (highest(high[1],10) - lowest(low[1],10)) < (atr(10)[1] * 2.5)
//long_consolidation = lowest(low[1],6) / highest(high[1],6) >= 0.98
// buy above 200MA and sell below 200MA
above_200ma = ma200_trend_switch ? (close[1] > sma(close[1],200) and (sma(close[1],200)/close[1]) >= 0.97) : true
below_200ma = ma200_trend_switch ? (close[1] < sma(close[1],200) and (close[1]/sma(close[1],200)) >= 0.97) : true
// ***********************************************************************************************************************
// entry conditions
long_entry := closed_above_bb and bb_in_squeeze and squeeze_is_good and ema_trend_check and avg_vol_is_good and above_200ma
short_entry := closed_below_bb and bb_in_squeeze and squeeze_is_good and ema_trend_check and avg_vol_is_good and below_200ma
// 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
if long_entry or short_entry
exit_price := na
if long_entry or short_entry
sl_price := mBB_0
// ***********************************************************************************************************************
// risk management
//
// long trade - a candle closes below 8ema and in next candle price crosses low of previous candle
// short trade - a candle closes above 8ema and in next candle price crosses high of previous candle
long_exit_8ema = strategy.position_size > 0 and crossunder(close,ema(close,8))
short_exit_8ema = strategy.position_size < 0 and crossover(close,ema(close,8))
if long_exit_8ema
exit_price := low
if short_exit_8ema
exit_price := high
// ***********************************************************************************************************************
// position sizing
price = if close[0] > 25000
25000
else
price = close[0]
qty = 25000/price
// ***********************************************************************************************************************
// entry
if long_entry and candle_count < entry_distance and strategy.position_size == 0
strategy.entry("BUY", strategy.long, qty, stop=entry_price, comment="BUY @ "+ tostring(entry_price))
if short_entry and candle_count < entry_distance and strategy.position_size == 0
strategy.entry("SELL", strategy.short, qty, stop=entry_price, comment="SELL @ "+ tostring(entry_price))
// cancel an order if N number of candles are completed after alert candle
strategy.cancel_all(candle_count > entry_distance)
// 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 long_exit_8ema
strategy.exit("EXIT using 8EMA", "BUY", stop=exit_price, comment="EXIT @ "+ tostring(exit_price))
if strategy.position_size < 0 and short_exit_8ema
strategy.exit("EXIT using 8EMA", "SELL", stop=exit_price, comment="EXIT @ "+ tostring(exit_price))
// close if sl hit
strategy.close("BUY", when=(strategy.position_size > 0 and close < sl_price), qty=strategy.position_size, comment="EXIT @ "+ tostring(close))
strategy.close("SELL", when=(strategy.position_size < 0 and close > sl_price), qty=strategy.position_size, comment="EXIT @ "+ tostring(close))
// 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.close("BUY", when=strategy.position_size > 0, qty=strategy.position_size, comment="EXIT @ "+ tostring(close))
strategy.close("SELL", when=strategy.position_size < 0, qty=strategy.position_size, comment="EXIT @ "+ 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)
// plot KC
[mKCp,uKCp,lKCp] = getKC(0)
p_uKC = plot(show_kc_switch ? uKCp : na, color=color.red)
p_lKC = plot(show_kc_switch ? lKCp : na, color=color.red)
// plot 8 ema
plot(show_8ema_switch?ema_8:na,color=color.blue)
// plot EMAs
plot(show_emas_switch ? ema_8 : na, color=color.green)
plot(show_emas_switch ? ema_21 : na, color=color.lime)
plot(show_emas_switch ? ema_34 : na, color=color.maroon)
plot(show_emas_switch ? ema_55 : na, color=color.orange)
plot(show_emas_switch ? ema_89 : na, color=color.purple) |
KPL Swing Strategy | https://www.tradingview.com/script/4mz6xvnK/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 723 | 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("KPL Swing Strategy", overlay=true)
no = input(20, title="Length")
res = highest(high, no)
sup = lowest(low, no)
avd = iff(close > res[1], 1, iff(close < sup[1], -1, 0))
avn = valuewhen(avd != 0, avd, 0)
tsl = iff(avn == 1, sup, res)
sl = iff(close > tsl, highest(lowest(low, no / 2), no / 2), lowest(highest(high, no / 2), no / 2))
Buy = crossover(close, tsl)
Sell = crossover(tsl, close)
Barcolor=input(true,title="Barcolor")
Bgcolor=input(true,title="Bgcolor")
colors=iff(close>tsl,color.green,iff(tsl<close,color.yellow,color.red))
barcolor(Barcolor ? colors:na)
bgcolor(Bgcolor ? colors:na)
plot(tsl,color=colors)
plot(sl,color=color.white,title="Stoploss")
if crossover(close, tsl)
strategy.entry("Long", strategy.long, comment="Long")
if crossunder(close,tsl)
strategy.entry("Short", strategy.short, comment="Short")
|
Trend Trader Strategy with MACD | https://www.tradingview.com/script/dUNRiEBG-Trend-Trader-Strategy-with-MACD/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 1,262 | 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("Trend Trader Strategy with MACD", overlay=true)
// === Trend Trader Strategy ===
Length = input(21),
Multiplier = input(3, minval=1)
MacdControl = input(true, title="Control 'MACD Histogram is positive?' when Buy condition")
avgTR = wma(atr(1), Length)
highestC = highest(Length)
lowestC = lowest(Length)
hiLimit = highestC[1]-(avgTR[1] * Multiplier)
loLimit = lowestC[1]+(avgTR[1] * Multiplier)
ret = iff(close > hiLimit and close > loLimit, hiLimit,
iff(close < loLimit and close < hiLimit, loLimit, nz(ret[1], 0)))
pos = iff(close > ret, 1,
iff(close < ret, -1, nz(pos[1], 0)))
barcolor(pos == -1 ? red: pos == 1 ? green : blue )
plot(ret, color= blue , title="Trend Trader 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 == -1)
|
Moving average system which waits for a better entry | https://www.tradingview.com/script/qEr212fp/ | dongyun | https://www.tradingview.com/u/dongyun/ | 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/
// © dongyun
//@version=4
strategy("等待一个更好的入场机会", overlay=true)
period = input(20,'')
maxwait = input(3,'')
threshold = input(0.01,'')
signal = 0
trend = 0.0
newtrend = 0.0
wait = 0.0
initialentry = 0.0
trend := sma(close,period)
signal := nz(signal[1])
if trend > nz(trend[1])
signal := 1
else
if trend < nz(trend[1])
signal := -1
wait := nz(wait[1])
initialentry := nz(initialentry[1])
if signal != signal[1]
if strategy.position_size > 0
strategy.close('long',comment='trend sell')
signal := -1
else
if strategy.position_size < 0
strategy.close('short',comment='trend buy')
signal := 1
wait := 0
initialentry := close
else
if signal != 0 and strategy.position_size == 0
wait := wait + 1
// test for better entry
if strategy.position_size == 0
if wait >= maxwait
if signal > 0
strategy.entry('long',strategy.long, comment='maxtime Long')
else
if signal < 0
strategy.entry('short',strategy.short, comment='maxtime Short')
else
if signal > 0 and close < initialentry - threshold
strategy.entry('long',strategy.long, comment='delayed Long')
else
if signal < 0 and close > initialentry + threshold
strategy.entry('short',strategy.short, comment='delayed short')
|
EMA Strategy v_1 by.JanS. | https://www.tradingview.com/script/wXsdP2Lw/ | jstraderjs | https://www.tradingview.com/u/jstraderjs/ | 33 | 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/
// © UmurS
//@version=1
strategy("EMA Strategy v_1 by.JanS.", overlay=true)
// === EMA Strategy v_1 ===
// Input options
EMA_5 = input(title="EMA 5" , type=integer, defval=5)
EMA_10 = input(title="EMA 10", type=integer, defval=10)
// Calculate values
Alert_EMA_5 = ema(close, EMA_5)
Alert_EMA_10 = ema(close, EMA_10)
// Create Buy/Sell Arrows
// plotshape(Buy, color=green, style=shape.arrowup, text="Buy", location=location.bottom)
// plotshape(Sell, color=red, style=shape.arrowdown, text="Sell", location=location.top)
// Show on Chart
plot(Alert_EMA_5, color = white, linewidth=3)
plot(Alert_EMA_10, color = lime, linewidth=3)
// Create alert conditions
alertcondition(condition=crossover(Alert_EMA_5, Alert_EMA_10),
title="EMA 5 Cross Above",
message="EMA 5 crossed over EMA 10."
)
alertcondition(condition=crossunder(Alert_EMA_5, Alert_EMA_10),
title="EMA 10 Cross Above",
message="EMA 10 crossed over EMA 5."
)
// EMA trend bar color
TrendingUp() => Alert_EMA_5 > Alert_EMA_10
TrendingDown() => Alert_EMA_5 < Alert_EMA_10
barcolor(TrendingUp() ? green : TrendingDown() ? red : blue)
// EMA cross background color alert to chart (Tall Candle)
Uptrend() => TrendingUp() and TrendingDown()[1]
Downtrend() => TrendingDown() and TrendingUp()[1]
bgcolor(Uptrend() ? green : Downtrend() ? red : na,transp=50)
// Buy and sell alert (Arrow bottom of Chart, using variables from above)
Buy = Uptrend() and close > close[1]
Sell = Downtrend() and close < close[1]
plotshape(Buy, color=white, style=shape.triangleup, text="Buy", location=location.bottom)
plotshape(Sell, color=white, style=shape.triangledown, text="Sell", location=location.bottom)
|
Laguerre RSI by KivancOzbilgic STRATEGY | https://www.tradingview.com/script/vWG3tMJh-Laguerre-RSI-by-KivancOzbilgic-STRATEGY/ | mertriver1 | https://www.tradingview.com/u/mertriver1/ | 339 | 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/
// © mertriver1
// Developer: John EHLERS
//@version=3
// Author:Kıvanç Özbilgiç
strategy("Laguerre RSI", shorttitle="LaRSI", overlay=false)
src = input(title="Source", defval=close)
alpha = input(title="Alpha", type=float, minval=0, maxval=1, step=0.1, defval=0.2)
colorchange = input(title="Change Color ?", type=bool, defval=false)
Date1 = input(true, title = "=== Date Backtesting ===")
FromDay1 = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromMonth1 = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromYear1 = input(defval = 2020, title = "From Year", minval = 2017)
ToDay1 = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToMonth1 = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToYear1 = input(defval = 9999, title = "To Year", minval = 2017)
start1 = timestamp(FromYear1, FromMonth1, FromDay1, 00, 00)
finish1 = timestamp(ToYear1, ToMonth1, ToDay1, 23, 59)
window1() => time >= start1 and time <= finish1 ? true : false
gamma=1-alpha
L0 = 0.0
L0 := (1-gamma) * src + gamma * nz(L0[1])
L1 = 0.0
L1 := -gamma * L0 + nz(L0[1]) + gamma * nz(L1[1])
L2 = 0.0
L2 := -gamma * L1 + nz(L1[1]) + gamma * nz(L2[1])
L3 = 0.0
L3 := -gamma * L2 + nz(L2[1]) + gamma * nz(L3[1])
cu= (L0>L1 ? L0-L1 : 0) + (L1>L2 ? L1-L2 : 0) + (L2>L3 ? L2-L3 : 0)
cd= (L0<L1 ? L1-L0 : 0) + (L1<L2 ? L2-L1 : 0) + (L2<L3 ? L3-L2 : 0)
temp= cu+cd==0 ? -1 : cu+cd
LaRSI=temp==-1 ? 0 : cu/temp
Color = colorchange ? (LaRSI > LaRSI[1] ? green : red) : blue
plot(100*LaRSI, title="LaRSI", linewidth=2, color=Color, transp=0)
plot(20,linewidth=1, color=maroon, transp=0)
plot(80,linewidth=1, color=maroon, transp=0)
strategy.entry("Long", true, when = window1() and crossover(cu, cd))
strategy.entry("Short", false, when = window1() and crossunder(cu, cd)) |
Wilder’s Moving Average Strategy | https://www.tradingview.com/script/wXtQeoOg/ | 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("Wilder’s Moving Average Strategy", overlay=true)
malength = input(36, "length", minval=1)
longd = false
shortd = false
lineColor = color.yellow
wild = 0.0
wild := nz(wild[1]) + (close -nz(wild[1]))/malength
longd := wild > wild[1]
shortd := wild < wild[1]
lineColor := longd ? color.green : shortd ? color.red : color.yellow
plot(wild, color=lineColor, linewidth=2, title="WILD")
if longd
strategy.entry("long", strategy.long, when = strategy.position_size <= 0)
else
if shortd
strategy.entry("short", strategy.short, when = strategy.position_size >= 0) |
Moving Averages Testing | https://www.tradingview.com/script/KZF9Qgnn-Moving-Averages-Testing/ | ben_zen | https://www.tradingview.com/u/ben_zen/ | 53 | 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/
// © gliese581d
//@version=4
strategy(title="Moving Averages Testing", overlay=true, precision=2, calc_on_every_tick=false, max_bars_back=5000, pyramiding=2,
default_qty_type=strategy.percent_of_equity, default_qty_value=50, commission_type=strategy.commission.percent, initial_capital=10000)
//SETTINGS
longs_on = input(title="Long Trades enabled", defval=true)
shorts_on = input(title="Short Trades enabled", defval=true)
long_cond = input(title="Buy/Long Crossover Condition", defval="price x MA1", options=["price x MA1", "price x MA2", "MA1 x MA2"])
short_cond = input(title="Sell/Short Crossunder Condition", defval="price x MA2", options=["price x MA1", "price x MA2", "MA1 x MA2"])
ma1_type = input(title="Moving Average 1 Type", defval="SMA", options=["SMA", "EMA"])
ma1_len = input(defval=20, title="Moving Average 1 Len", type=input.integer, minval=1, maxval=1000, step=1)
ma2_type = input(title="Moving Average 2 Type", defval="SMA", options=["SMA", "EMA"])
ma2_len = input(defval=30, title="Moving Average 2 Len", type=input.integer, minval=1, maxval=1000, step=1)
//MOVING AVERAGES
ma_1 = ma1_type == "EMA" ? ema(close, ma1_len) : sma(close, ma1_len)
ma_2 = ma2_type == "EMA" ? ema(close, ma2_len) : sma(close, ma2_len)
//STRATEGY
//trade entries
long_entry = long_cond == "price x MA1" ? crossover(close, ma_1) : long_cond == "price x MA2" ? crossover(close, ma_2) : long_cond == "MA1 x MA2" ? crossover(ma_1, ma_2) : false
short_entry = short_cond == "price x MA1" ? crossunder(close, ma_1) : short_cond == "price x MA2" ? crossunder(close, ma_2) : short_cond == "MA1 x MA2" ? crossunder(ma_1, ma_2) : false
start_month = input(defval=4, title="Strategy Start Month", type=input.integer, minval=1, maxval=12, step=1)
start_year = input(defval=2018, title="Strategy Start Year", type=input.integer, minval=2000, maxval=2025, step=1)
end_month = input(defval=12, title="Strategy End Month", type=input.integer, minval=1, maxval=12, step=1)
end_year = input(defval=2020, title="Strategy End Year", type=input.integer, minval=2000, maxval=2025, step=1)
in_time = time >= timestamp(start_year, start_month, 0, 0, 0) and time <= timestamp(end_year, end_month, 0, 0, 0)
strategy.entry("Long", strategy.long, when=longs_on and in_time and long_entry)
strategy.close("Long", when=longs_on and not shorts_on and short_entry)
strategy.entry("Short", strategy.short, when=shorts_on and in_time and short_entry)
strategy.close("Short", when=shorts_on and not longs_on and long_entry)
//PLOTTING
//color background
last_entry_was_long = nz(barssince(long_entry)[1], 5000) < nz(barssince(short_entry)[1], 5000)
bgcol = (longs_on and last_entry_was_long) ? color.green : (shorts_on and not last_entry_was_long) ? color.red : na
bgcolor(color=bgcol, transp=90)
plot((long_cond == "price x MA1" or long_cond == "MA1 x MA2") or (short_cond == "price x MA1" or short_cond == "MA1 x MA2") ? ma_1 : na, color=color.blue)
plot((long_cond == "price x MA2" or long_cond == "MA1 x MA2") or (short_cond == "price x MA2" or short_cond == "MA1 x MA2") ? ma_2 : na, color=color.black)
plotshape(long_entry, style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(short_entry, style=shape.triangledown, location=location.abovebar, color=color.red) |
Break out strategy 0 | https://www.tradingview.com/script/0zSfR6CP/ | Cbgbm788 | https://www.tradingview.com/u/Cbgbm788/ | 56 | 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/
// © Cbgbm788
//@version=4
strategy("Break out strategy 0", shorttitle="BOS0", pyramiding = 1, overlay=true)
//input
HLPeriod = input(20, title="HighLow Period", type=input.integer)
SL = input(2, title="Stop Loss(%)", type=input.integer)
ExpBars = input(5, title="Max holding period", type=input.integer)
//sub function
var _entry_barindex = 0
set_exit_barindex() => _bar_index = bar_index + ExpBars
//Highest Lowest
HH = security(syminfo.tickerid, timeframe.period, offset(highest(HLPeriod),2))
LL = security(syminfo.tickerid, timeframe.period, offset(lowest(HLPeriod),2))
//entry
longCondition = (strategy.position_size<=0?true:false) and crossover(close, HH[1])
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
_entry_barindex := set_exit_barindex()
shortCondition = (strategy.position_size>=0?true:false) and crossunder(close, LL[1])
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
_entry_barindex := set_exit_barindex()
//stop loss
strategy.exit("exit", loss = SL)
//cancel
if(bar_index==_entry_barindex)
strategy.close_all(true, "Exp Bars")
_entry_barindex := 0
//for debug
plot(HH, style=plot.style_stepline)
plot(LL, style=plot.style_stepline) |
Pivot Point SuperTrend [Backtest] | https://www.tradingview.com/script/DwdC6FT4-Pivot-Point-SuperTrend-Backtest/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 4,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/
// © LonesomeTheBlue
//@version=4
strategy("Pivot Point SuperTrend [Backtest]", overlay = true)
prd = input(defval = 2, title="Pivot Point Period", minval = 1, maxval = 50)
Factor=input(defval = 3, title = "ATR Factor", minval = 1, step = 0.1)
Pd=input(defval = 10, title = "ATR Period", minval=1)
minrateu = input(defval = 1.0, title="Min profit Rate if Center Line Used", minval = 0)
usecenter = input(defval = false, title="Use Center Line to Close Entry for 50%")
showpivot = input(defval = false, title="Show Pivot Points")
showcl = input(defval = false, title="Show PP Center Line")
onlylong = input(defval = false, title="Enter Only Long Position")
float minrate = minrateu / 100
float ph = na
float pl = na
ph := pivothigh(prd, prd)
pl := pivotlow(prd, prd)
plotshape(ph and showpivot, text="H", style=shape.labeldown, color=na, textcolor=color.red, location=location.abovebar, offset = -prd)
plotshape(pl and showpivot, text="L", style=shape.labeldown, color=na, textcolor=color.lime, location=location.belowbar, offset = -prd)
float center = na
center := center[1]
float lastpp = ph ? ph : pl ? pl : na
if lastpp
if na(center)
center := lastpp
else
center := (center * 2 + lastpp) / 3
Up = center - (Factor * atr(Pd))
Dn = center + (Factor * atr(Pd))
float TUp = na
float TDown = na
Trend = 0
TUp := close[1] > TUp[1] ? max(Up, TUp[1]) : Up
TDown := close[1] < TDown[1] ? min(Dn, TDown[1]) : Dn
Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1)
Trailingsl = Trend == 1 ? TUp : TDown
linecolor = Trend == 1 and nz(Trend[1]) == 1 ? color.lime : Trend == -1 and nz(Trend[1]) == -1 ? color.red : na
plot(Trailingsl, color = linecolor , linewidth = 2, title = "PP SuperTrend")
plot(showcl ? center : na, color = showcl ? center < hl2 ? color.blue : color.red : na)
bsignal = Trend == 1 and Trend[1] == -1
ssignal = Trend == -1 and Trend[1] == 1
halfexited = false
halfexited := nz(halfexited[1], false)
if change(Trend)
strategy.close_all()
if bsignal
strategy.entry("Buy", true, comment = "Buy")
if ssignal and not onlylong
strategy.entry("Sell", false, comment = "Sell")
cpsize = change(strategy.position_size)
if change(strategy.position_size)
if cpsize > 0 and strategy.position_size > 0 or cpsize< 0 and strategy.position_size < 0
halfexited := false
if strategy.position_size > 0 and center > hl2 and usecenter and not halfexited and close > strategy.position_avg_price * (1 + minrate)
strategy.close("Buy", qty_percent = 50, comment = "close buy for 50%")
halfexited := true
if strategy.position_size < 0 and center < hl2 and usecenter and not halfexited and close < strategy.position_avg_price * (1 + minrate)
strategy.close("Sell", qty_percent = 50, comment = "close sell for 50%")
halfexited := true
|
cATRpillar Strategy | https://www.tradingview.com/script/ulkw6PiT-cATRpillar-Strategy/ | Obi-wanClintobe | https://www.tradingview.com/u/Obi-wanClintobe/ | 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/
// © cwagoner78
//@version=4
strategy("cATRpillar", overlay=true, default_qty_value=100000, default_qty_type=strategy.percent_of_equity, initial_capital=10000, currency=currency.USD)
//------------
//inputs
lookback = input(title="Periods", type=input.integer, defval=4)
atrMult = input(title="Range Multiplier", type=input.float, defval=.1)
takeProfit = input(title="Take Profit", type=input.float, defval=300)
stopLoss = input(title="Stop Loss", type=input.float, defval=100)
lots = input(title="Lots to Trade", type=input.float, defval=1)
//------------
//indicators
atr=atr(lookback)*atrMult
sma=sma(close, lookback)
ema=ema(close,lookback*2)
rangeLo=sma-atr
rangeHi=sma+atr
//------------
//draw objects
p0 =plot(close, title="Close", color=#26A69A, linewidth=0, transp=80,style=plot.style_stepline)
p1 =plot(rangeHi, title="High", color=color.fuchsia, linewidth=0, transp=80,style=plot.style_stepline)
p2 =plot(rangeLo, title="Low", color=color.lime, linewidth=0, transp=80,style=plot.style_stepline)
p3 =plot(ema, title="EMA", color=color.white, linewidth=0, transp=80, style=plot.style_stepline)
fill(p1, p0, color=color.fuchsia)
fill(p0, p2, color=color.lime)
//------------
//Trading
atrShort=open[1] > rangeHi and open < rangeLo
atrLong=open[1] < rangeLo and open > rangeHi
exitLong=open>rangeLo
exitShort=open<rangeHi
//Long
longCondition=atrLong and open>ema+atr
strategy.entry(id="cATRpillar-Buy", long=true, when=longCondition)
longCloseCondition=exitLong
strategy.exit(id="cATRpillar-Exit", qty=lots, profit=takeProfit, loss=stopLoss)
//Short
shortCondition=atrShort and open<ema-atr
strategy.entry(id="cATRpillar-Sell", long=false, when=shortCondition)
shortCloseCondition=exitShort
strategy.exit(id="cATRpillar-Exit", qty=lots, profit=takeProfit, loss=stopLoss)
plotshape(shortCondition, title= "Short", location=location.belowbar, color=color.fuchsia, transp=80, style=shape.triangledown, size=size.tiny)
plotshape(longCondition, title= "Long", location=location.abovebar, color=color.lime, transp=80, style=shape.triangleup, size=size.tiny)
//------------
|
Gann High Low Strategy | https://www.tradingview.com/script/4B9Gvzkb/ | dongyun | https://www.tradingview.com/u/dongyun/ | 170 | 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("Gann High Low Strategy", overlay=true)
HPeriod = input(16,"HIGH Period")
LPeriod = input(48,"LOW Period")
hsma = 0.0
lsma = 0.0
hsma := sma(high,HPeriod)
lsma := sma(low,LPeriod)
HLd = iff(close>nz(hsma[1]),1,iff(close<nz(lsma[1]),-1,0))
HLv = valuewhen(HLd!=0,HLd,0)
HiLo = iff(HLv==-1,hsma,lsma)
HLcolor = HLv == -1 ? color.maroon : color.blue
plot(HiLo, linewidth=2, color=HLcolor)
if HLv == -1
strategy.entry("short", strategy.short)
else
if HLv == 1
strategy.entry("long", strategy.long) |
Oath | https://www.tradingview.com/script/RciffGJK-Oath/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 96 | 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("Oath", overlay=true)
// 21 EMA
emalength = input(21, title="Short EMA")
emashort = ema(close, emalength)
// 55 EMA
emalength2 = input(55, title="Long EMA")
ema = ema(close, emalength2)
//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)
//cciOS = (ccivalue <= ccioversold and ccivalue > ccioversold2)
//cciOB2 = (ccivalue >= ccioverbought2 and ccivalue < ccioverbought3)
//cciOS2 = (ccivalue <= ccioversold and ccivalue > ccioversold3)
//cciOB3 = (ccivalue >= ccioverbought3)
//cciOS3 = (ccivalue <= ccioversold3)
//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=false)
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
//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("Oath1", strategy.long, ordersize)
strategy.exit( "Oath1 Close", from_entry="Oath1" , 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("Oath2", strategy.long, ordersize)
strategy.exit( "Oath2 Close", from_entry="Oath2" , 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("Oath3", strategy.long, ordersize)
strategy.exit( "Oath3 Close", from_entry="Oath3" , 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("Oath1.s", strategy.short, ordersize)
strategy.exit( "Oath1 Close", from_entry="Oath1.s" , 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("Oath2.s", strategy.short, ordersize)
strategy.exit( "Oath2 Close", from_entry="Oath2.s" , 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("Oath3.s", strategy.short, ordersize)
strategy.exit( "Oath3 Close", from_entry="Oath3.s" , profit=statictargetvalue,stop=downstoploss[y3])
plotshape(uptrend and upsignal and degree, location=location.belowbar, color=color.green, transp=0, style=shape.triangleup, size=size.tiny, text="Oath up")
plotshape(downtrend and downsignal and degree, location=location.abovebar, color=color.red, transp=0, style=shape.triangledown, size=size.tiny, text="Oath down")
plotshape(uptrend and upsignal2 and degree2, location=location.belowbar, color=color.green, transp=0, style=shape.triangleup, size=size.tiny, text="Oath up+")
plotshape(downtrend and downsignal2 and degree2, location=location.abovebar, color=color.red, transp=0, style=shape.triangledown, size=size.tiny, text="Oath down+")
plotshape(uptrend and upsignal3 and degree3, location=location.belowbar, color=color.green, transp=0, style=shape.triangleup, size=size.tiny, text="Oath up++")
plotshape(downtrend and downsignal3 and degree3, location=location.abovebar, color=color.red, transp=0, style=shape.triangledown, size=size.tiny, text="Oath down++")
|
Dazzling Bolts | https://www.tradingview.com/script/sm8kqwsV-Dazzling-Bolts/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 87 | 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("Dazzling Bolts", overlay=true)
//max_bars_back=3000
// 13 SMMA
len = input(10, minval=1, title="SMMA Period")
src = input(close, title="Source")
smma = 0.0
smma := na(smma[1]) ? sma(src, len) : (smma[1] * (len - 1) + src) / len
// 55 EMA
emalength = input(55, title="EMA Period")
ema = ema(close, emalength)
// 100 SMA
smalength = input(110, title="SMA Period")
sma = sma(close, smalength)
emaforce = input(title="Force trend with medium EMA", type=input.bool, defval=true)
offsetemavalue = input(defval = 6)
bullbounce = smma>ema and ema>sma and low[5]>ema and low[2]<ema and close[1]>ema and (ema[offsetemavalue]>sma or (not emaforce))
bearbounce = smma<ema and ema<sma and high[5]<ema and high[2]>ema and close[1]<ema and (ema[offsetemavalue]<sma or (not emaforce))
plotshape(bullbounce, title= "Purple", location=location.belowbar, color=#ff33cc, transp=0, style=shape.triangleup, size=size.tiny, text="Bolts")
plotshape(bearbounce, title= "Purple", location=location.abovebar, color=#ff33cc, transp=0, style=shape.triangledown, size=size.tiny, text="Bolts")
ordersize=floor(strategy.initial_capital/close)
longs = input(title="Test longs", type=input.bool, defval=true)
shorts = input(title="Test shorts", type=input.bool, defval=true)
atrlength = input(title="ATR length", defval=12)
atrm = input(title="ATR muliplier",type=input.float, defval=2)
atr = atr(atrlength)
target = close + atr*atrm
antitarget = close - (atr*atrm)
//limits and stop do not move, no need to count bars from since
bullbuy = bullbounce and longs and strategy.opentrades==0
bb = barssince(bullbuy)
bearsell = bearbounce and shorts and strategy.opentrades==0
bs = barssince(bearsell)
if (bullbuy)
strategy.entry("Boltsup", strategy.long, ordersize)
strategy.exit ("Bolts.close", from_entry="Boltsup", limit=target, stop=antitarget)
if (crossover(smma, sma))
strategy.close("Boltsup", qty_percent = 100, comment = "Bolts.crossover")
if (bearsell)
strategy.entry("Boltsdown", strategy.short, ordersize)
strategy.exit("Bolts.close", from_entry="Boltsdown", limit=antitarget, stop=target)
if (crossunder(smma, sma))
strategy.close("Boltsdown", qty_percent = 100, comment = "Bolts.crossover")
if (bb<5)
bulltarget = line.new(bar_index[bb], target[bb], bar_index[0], target[bb], color=color.blue, width=2)
bullclose = line.new(bar_index[bb], close[bb], bar_index[0], close[bb], color=color.blue, width=2)
bullstop = line.new(bar_index[bb], antitarget[bb], bar_index[0], antitarget[bb], color=color.blue, width=2)
if (bs<5)
bulltarget = line.new(bar_index[bs], antitarget[bs], bar_index[0], antitarget[bs], color=color.purple, width=2)
bullclose = line.new(bar_index[bs], close[bs], bar_index[0], close[bs], color=color.purple, width=2)
bullstop = line.new(bar_index[bs], target[bs], bar_index[0], target[bs], color=color.purple, width=2)
|
Fibonacci + RSI - Strategy | https://www.tradingview.com/script/Ouv7XVfc-Fibonacci-RSI-Strategy/ | MohamedYAbdelaziz | https://www.tradingview.com/u/MohamedYAbdelaziz/ | 2,404 | 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/
// © MohamedYAbdelaziz
// Intraday Trading
// Best used for Short Timeframes [1-30 Minutes]
// If you have any modifications please tell me to update it
//@version=4
strategy(title="Fibonacci + RSI - Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, currency=currency.USD)
// Inputs
timeFilter = year >= 2000
// Stop Loss %
loss_percent = input(title="Stop Loss (%)", minval=0.0, step=0.1, defval=2) * 0.001
// RSI Inputs
len = input(title="[RSI] Length", minval=0, step=1, defval=14)
overSold = input(title="[RSI] Over Sold %", defval=30)
overBought = input(title="[RSI] Over Bought %", defval=70)
// Fibonacci Levels
length = input(title="[Fibonacci] Length", defval=200, minval=1)
src = input(hlc3, title="[Fibonacci] Source")
mult = input(title="[Fibonacci] Multiplier", defval=3.0, minval=0.001, maxval=50)
level = input(title="[Fibonacci] Level", defval=764)
// Calculate Fibonacci
basis = vwma(src, length)
dev = mult * stdev(src, length)
fu764= basis + (0.001*level*dev)
fu1= basis + (1*dev)
fd764= basis - (0.001*level*dev)
fd1= basis - (1*dev)
// Calculate RSI
vrsi = rsi(close, len)
// Calculate the Targets
targetUp = fd764
targetDown = fu764
// Actual Targets
bought = strategy.position_size[0] > strategy.position_size[1]
exit_long = valuewhen(bought, targetUp, 0)
sold = strategy.position_size[0] < strategy.position_size[1]
exit_short = valuewhen(sold, targetDown, 0)
// Calculate Stop Losses
stop_long = strategy.position_avg_price * (1 - loss_percent)
stop_short = strategy.position_avg_price * (1 + loss_percent)
// Conditions to Open Trades
openLong = low < fd1 and crossover(vrsi[1], overSold)
openShort = high > fu1 and crossunder(vrsi[1], overBought)
// Conditions to Close Trades
closeLong = high > exit_long
closeShort = low < exit_short
// Plots
plot(basis, color=color.blue, linewidth=2, title="[Fibonacci Level] Basis")
plot(fu764, color=color.white, linewidth=1, title="[Fibonacci Level] Short Target")
plot(fu1, color=color.red, linewidth=2, title="1", title="[Fibonacci Level] Top")
plot(fd764, color=color.white, linewidth=1, title="[Fibonacci Level] Long Target")
plot(fd1, color=color.green, linewidth=2, title="1", title="[Fibonacci Level] Bottom")
// Strategy Orders
if timeFilter
// Entry Orders
strategy.entry(id="Long", long=true, when=openLong and high < targetUp, limit=close)
strategy.entry(id="Short", long=false, when=openShort and low > targetDown, limit=close)
// Exit Orders
strategy.exit(id="Long", when=closeLong and strategy.position_size > 0, limit=exit_long, stop=stop_long)
strategy.exit(id="Short", when=closeShort and strategy.position_size < 0, limit=exit_short, stop=stop_short) |
KD compare strategy (交易策略對照組) | https://www.tradingview.com/script/KkJ2UKGR/ | Tonyder | https://www.tradingview.com/u/Tonyder/ | 68 | 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/
// © Tonyder
//@version=4
strategy("KD base strategy", overlay=true, pyramiding=1000, process_orders_on_close=true, precision=6, max_bars_back=720)
//strategy("KD base strategy", overlay=true, pyramiding=1000, precision=6, max_bars_back=720)
max=input(defval=20, title="庫存上限(share)", type=input.integer)
min=input(defval=-20, title="庫存下限(share)", type=input.integer)
period=input(defval=9, title="KD 週期(KD period)", type=input.integer, minval=2)
diff=input(defval=0.1, title="KD 週期(KD period)", type=input.float, minval=0.1)
k=0.0
rsv=0.0
dir=0
sum=0.0
share2=0.0
first=0
up=0.0
bottom=0.0
k80=0.0
k50=0.0
k20=0.0
k801=0.0
k501=0.0
k201=0.0
show=0
show:=0
rate=0.0
last=0.0
inc=false
dec=false
inc:=false
dec:=false
clean=false
clean:=false
share=strategy.position_size
rsv:=stoch(close, high, low, period)
up:=highest(high,period)
bottom:=lowest(low,period)
if bar_index <= period
k:=rsv
dir:=0
sum:=0
share2:=0
last:=close
else
k:=k[1]*2/3 + rsv/3
dir := dir[1]
sum := sum[1]
share2:=share2[1]
rate:= rate[1]
last:= last[1]
// filter
yearbegin=input(defval=1978, title="起始年 (begin year)", type=input.integer, minval=0)
monthbegin=input(defval=1, title="起始月 (begin month)", type=input.integer, minval=0)
dayofmonthbegin=input(defval=1, title="起始日 (begin day)", type=input.integer, minval=0)
condition99=(year >= yearbegin) and (month >= monthbegin) and (dayofmonth > dayofmonthbegin)
// rsv = 100 * (close - lowest(low, period)) / (highest(high, period) - lowest(low, period))
// k=k[1]*2/3 + rsv/3
// 3k=k[1]*2 + rsv
// 3k-k[1]*2= 100 * (close - lowest(low, period)) / (highest(high, period) - lowest(low, period))
// (3k-k[1]*2)/100*(highest(high, period) - lowest(low, period)) + lowest(low, period) = close
// let k = 80, close = (3*80-k[1]*2)/100*(highest(high, period) - lowest(low, period)) + lowest(low, period)
k80:=(3*80-k[1]*2)/100*(highest(high, period) - lowest(low, period)) + lowest(low, period)
k50:=(3*50-k[1]*2)/100*(highest(high, period) - lowest(low, period)) + lowest(low, period)
k20:=(3*20-k[1]*2)/100*(highest(high, period) - lowest(low, period)) + lowest(low, period)
// tomorrow k
k801:=(3*80-k*2)/100*(highest(high, period-1) - lowest(low, period-1)) + lowest(low, period-1)
k501:=(3*50-k*2)/100*(highest(high, period-1) - lowest(low, period-1)) + lowest(low, period-1)
k201:=(3*20-k*2)/100*(highest(high, period-1) - lowest(low, period-1)) + lowest(low, period-1)
if (dir == 1 and low < k50 and close < close[1] and open > close)
// rule1, strong target, buy at low price
sum := sum + 1
else if (dir == -1 and high > k50 and close > close[1] and open < close)
// rule2, weak target, sell at high price
sum := sum - 1
else if (dir == 1 and k[1] > 80 and k < 80 and share > 3)
// rule5, end the positive order
sum := 1
else if (dir == -1 and k[1] < 20 and k > 20 and share < -3)
// rule6, end the engitive order
sum := -1
else if (dir == 1 and high > k50 and close > close[1] and rate < -diff/100 and share > 2)
// rule7, reduce the order when the rate is poor
sum := sum - 1
else if (dir == -1 and low < k50 and close < close[1] and rate > diff/100 and share < -2)
// rule8, reduce the order when the rate is poor
sum := sum + 1
// become to strong
if (k >= 80)
dir := 1
// become to weak
if (k <= 20)
dir := -1
// rule 3, strong become to weak, clean when k < 20
if (dir == 1 and share < 0 and close > last and k < 20)
clean := true
// rule 4, weak become to strong, clean when k > 80
if (dir == -1 and share > 0 and close < last and k > 80)
clean := true
// rule 9, the first negtive order
if (dir == 1 and k > 80 and rate > diff/100 and share == 0)
inc:= true
sum := 1
// rule 10, the first negtive order
if (dir == -1 and k < 20 and rate < -diff/100 and share == 0)
dec:= true
sum := -1
if sum > 0
share2 := sum
else if sum < 0
share2 := sum
else
share2 := 0
if share2 > max
share2 := max
if share2 < min
share2 := min
if (k > 80 and k[1] < 80)
rate:= high/last - 1
last:= high
if (k < 20 and k[1] > 20)
rate:= low/last - 1
last:= low
if (dir > 0 and low < k50 and low[1] > k50)
rate:= low/last - 1
last:= low
if (dir < 0 and high > k50 and high[1] <k50)
rate:= high/last - 1
last:= high
strategy.close_all(when=clean and condition99, comment="stop")
strategy.order(id='buy', long=true, qty=share2-share, limit=k501, when=share2 > share and condition99)
strategy.order(id="sell", long=false, qty=share-share2, limit=k501, when=share2 < share and condition99)
strategy.order(id='increase', long=true, qty=1, when=share2 != share and inc and condition99)
strategy.order(id="decrease", long=false, qty=1, when=share2 != share and dec and condition99)
plot(share, "持股(share)",transp=100)
//plot(share2, "持股(share)",transp=100)
plot(dir, "方向(direction)",transp=100)
plot(k80, "Strong (轉強)", color.red)
plot(k50, "Middle (中線)", color.white)
plot(k20, "Weak (轉弱)", color.green)
k_color=color.black
if k80 != k801[1]
k_color:=color.red
plot(k801, "S+1", k_color, transp=100)
k_color:=color.black
if k50 != k501[1]
k_color:=color.white
plot(k501, "M+1", k_color, transp=100)
k_color:=color.black
if k20 != k201[1]
k_color:=color.green
plot(k201, title="W+1", color=k_color, transp=100)
plot(k, "k",transp=100)
// Colour background
plotColour = rate > 0 ? color.red :
rate < 0 ? color.green :
color.yellow
plot(series=rate*100, title="rate",color=plotColour, style=plot.style_histogram, linewidth=1, transp=100)
//plot(last, "last",transp=100)
|
Simple Momentum Strategy Based on SMA, EMA and Volume | https://www.tradingview.com/script/88K4Aekc-Simple-Momentum-Strategy-Based-on-SMA-EMA-and-Volume/ | slip_stream | https://www.tradingview.com/u/slip_stream/ | 62 | 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/
// © slip_stream
//@version=4
// Simple strategy for riding the momentum and optimising the timings of truer/longer price moves upwards for an long posistions on a daily basis (can be used, but with less effect
// on other time frames. Volume settings would have to be adjusted by the user accordingly. (short positions are not used).
// This strategy has default settings of a short(er) SMA of 10, a long(er) EMA of 20, and Volume trigger of 10 units and above. All these settings can be changed by the user
// using the GUI settings and not having to change the script.
// The strategy will only open a long position when there is a clear indication that price momentum is upwards through the SMA moving and remaining above the EMA (mandatory) and price period indicators
// of either 1) a standard 3 bar movement upwards, 2) a standard but "aggressive" 3 or 4 bar play where the low of the middle resting bars can be equal to or higher than (i.e. not
// the more standard low of about half) of the opening of the ignition bar. The "aggression" of the 3/4 bar play was done in order to counteract the conservatisme of having a mandatory
// SMA remaining higher than the EMA (this would have to be changed in the script by the user if they want to optimise to their own specifications. However, be warned, all programmatic
// settings for the maximum acceptable low of the middle resting bars runs a risk of ignoring good entry points due to the low being minutely e.g. 0.01%, lower than the user defined setting)
strategy(title = "Simple Momentum Strategy Based on SMA, EMA and Volume", overlay = true, pyramiding = 1, initial_capital = 100000, currency = currency.USD)
// Obtain inputs
sma_length = input(defval = 10, minval=1, type = input.integer, title = "SMA (small length)")
ema_length = input(defval = 20,minval=1, type = input.integer, title = "EMA (large length)")
volume_trigger = input(defval = 10, title = "Volume Trigger", type = input.integer)
sma_line = sma(close, sma_length)
ema_line = ema(close, ema_length)
// plot SMA and EMA lines with a cross for when they intersect
plot(sma_line, color = #8b0000, title = "SMA")
plot(ema_line, color = #e3d024, title = "EMA")
plot(cross(sma_line, ema_line) ? sma_line : na, style = plot.style_cross, linewidth = 4, color = color.white)
// Create variables
// variables to check if trade should be entered
//three consecutive bar bar moves upwards and volume of at least one bar is more than 10
enter_trade_3_bar_up = sma_line > ema_line and close[1] >= close [2] and close[3] >= close[4] and close[2] >= close[3] and (volume[1] >= volume_trigger or volume[2] >= volume_trigger or volume[3] >= volume_trigger)
// aggressive three bar play that ensures the low of the middle bar is equal to or greater than the open of the instigator bar. Volume is not taken into consideration (i.e. aggressive/risky)
enter_3_bar_play = sma_line > ema_line and close[1] > close[3] and low[2] >= open[3]
// aggressive four bar play similar to the 3 bar play above
enter_4_bar_play = sma_line > ema_line and close[1] > close[4] and low[2] >= open[4]
trade_entry_criteria = enter_trade_3_bar_up or enter_3_bar_play or enter_4_bar_play // has one of the trade entry criterias returned true?
// exit criteria for the trade: when the sma line goes under the ema line
trade_exit_criteria = crossunder (sma_line, ema_line)
if (year >= 2019)
strategy.entry(id = "long", long = true, qty = 1, when = trade_entry_criteria)
strategy.close(id = "long", when = trade_exit_criteria, qty = 1)
// for when you want to brute force close all open positions: strategy.close_all (when = trade_exit_criteria) |
RSI V Pattern strategy | https://www.tradingview.com/script/NXbsqL9n-RSI-V-Pattern-strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 359 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
//strategy("RSI V Pattern", overlay=true)
strategy(title="RSI V Pattern", overlay=false, pyramiding=3, default_qty_type=strategy.percent_of_equity , default_qty_value=10, initial_capital=10000, currency=currency.USD,process_orders_on_close=true)
//Strategy Rules
//ema20 is above ema50 --- candles are colored green on the chart
//RSI value sharply coming up which makes a V shape , colored in yellow on the chart
//RSI V pattern should occur from below 30
len = input(title="RSI Period", minval=1, defval=5)
buyRsiEntry = input(title="Buy at RSI ", minval=5, defval=30, maxval=60)
stopLoss = input(title="Stop Loss %", minval=1, defval=8)
myRsi = rsi(close,len)
longEmaVal=ema(close,50)
shortEmaVal=ema(close,20)
//plot emas
//plot(longEmaVal, title="Long EMA" ,linewidth=2, color=color.orange, trackprice=true)
//plot(shortEmaVal, title="Short EMA" ,linewidth=2, color=color.green, trackprice=true)
isEma20AboveEma50=ema(close,20)>ema(close,50) ? true : false
//V Pattern
longCondition = ema(close,20)>ema(close,50) and (low[1]<low[2] and low[1]<low[3]) and (myRsi>myRsi[1] and myRsi>myRsi[2] ) and crossover(myRsi,buyRsiEntry) // ( and myRsi<60)
patternText=" V "
//W Pattern
//longCondition = isEma20AboveEma50 and ( low[1]<low[4] and (low[1]<low[2] or low[1]<low[3])) and (myRsi[1]<65 and myRsi[3]<65 and myRsi[2]>myRsi[3] and myRsi[2]>myRsi[1] and myRsi[1]>=myRsi[3] and myRsi>myRsi[1] and myRsi>30)
//longCondition = isEma20AboveEma50 and ( low[1]<low[4] or low[1]<low[3] ) and (myRsi[2]>myRsi[3] and myRsi[2]>myRsi[1] and myRsi[1]>=myRsi[3] ) and myRsi>=30 and myRsi<60
// myRsi[1]=myRsi[3] exact W pattern
// myRsi[1]>myRsi[3] ugly W pattern
//patternText=" W "
//and crossover(myRsi,30)
//(myRsi<60 and myRsi>30) and myRsi>myRsi[1] and (myRsi[1]<myRsi[2] or myRsi[1]<myRsi[3]) and (myRsi[2]<30) and (myRsi[3]<30 and myRsi[4]>=30)
//barcolor(shortEmaVal>longEmaVal?color.green:color.purple)
//longCondition = crossover(sma(close, 14), sma(close, 28))
barcolor(longCondition?color.yellow:na)
strategy.entry("RSI_V_LE", strategy.long, when=longCondition )
//stoploss value at 10%
stopLossValue=strategy.position_avg_price - (strategy.position_avg_price*stopLoss/100)
//stopLossValue=valuewhen(longCondition,low,3)
//takeprofit at RSI highest reading
//at RSI75 move the stopLoss to entry price
moveStopLossUp=strategy.position_size>0 and crossunder(myRsi,70)
barcolor(moveStopLossUp?color.blue:na)
stopLossValue:=crossover(myRsi,70) ? strategy.position_avg_price:stopLossValue
//stopLossValue:=moveStopLossUp?strategy.position_avg_price:stopLossValue
rsiPlotColor=longCondition ?color.yellow:color.purple
rsiPlotColor:= moveStopLossUp ?color.blue:rsiPlotColor
plot(myRsi, title="RSI", linewidth=2, color=rsiPlotColor)
//longCondition?color.yellow:#8D1699)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevel = hline(75, title="Overbought", linestyle=hline.style_dotted)
osLevel = hline(25, title="Oversold", linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=#9915FF, transp=90)
plotshape(
longCondition ? myRsi[1] : na,
offset=-1,
title="V Pattern",
text=patternText,
style=shape.labelup,
location=location.absolute,
color=color.purple,
textcolor=color.yellow,
transp=0
)
//when RSI crossing down 70 , close 1/2 position and move stop loss to average entry price
strategy.close("RSI_V_LE", qty=strategy.position_size*1/2, when=strategy.position_size>0 and crossunder(myRsi,70))
//when RSI reaches high reading 90 and crossing down close 3/4 position
strategy.close("RSI_V_LE", qty=strategy.position_size*3/4, when=strategy.position_size>0 and crossunder(myRsi,90))
//close everything when Rsi goes down below to 10 or stoploss hit
//just keeping RSI cross below 10 , can work as stop loss , which also keeps you long in the trade ... however sharp declines could make large loss
//so I combine RSI goes below 10 OR stoploss hit , whichever comes first - whole position closed
longCloseCondition=close<stopLossValue
//crossunder(myRsi,10) or close<stopLossValue
strategy.close("RSI_V_LE", qty=strategy.position_size,when=longCloseCondition )
|
Volume Weighted Bollinger Bands Strategy | https://www.tradingview.com/script/BzGOHJs7-Volume-Weighted-Bollinger-Bands-Strategy/ | Ankit_1618 | https://www.tradingview.com/u/Ankit_1618/ | 181 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Ankit_1618
//@version=4
strategy("Volume Weighted Bollinger Bands Strategy", overlay=true)
src = input(close, title="Source")
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
ema8 = ema(src, 8)
ema21 = ema(src, 21)
ema55 = ema(src, 55)
ema233 = ema(src, 233)
_vwap = vwap
average_weighting = (ema8 + ema21 + ema55 + ema233 + _vwap) / 5
basis = sma(average_weighting, length)
dev = mult * stdev(average_weighting, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=#872323, offset = offset)
p1 = plot(upper, "Upper", color=color.teal, offset = offset)
p2 = plot(lower, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)
condition_long = close > upper and close[1] > upper
condition_short = close< lower and close[1] < lower
if (condition_long)
strategy.entry("Long", strategy.long)
if (condition_short)
strategy.entry("Short", strategy.short)
strategy.close("Long", when = condition_short )
strategy.close("Short", when = condition_long )
|
Highest High and Lowest Low Channel Strategy | https://www.tradingview.com/script/1SMJivyk/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 1,210 | 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/
// © ceyhun
//@version=5
strategy('Highest High and Lowest Low Channel Strategy', overlay=true)
length = input(20)
reverse = input(false, title='Trade reverse')
hh = ta.highest(high, length)
ll = ta.lowest(low, length)
pos = 0.0
iff_1 = close < ll[1] ? -1 : nz(pos[1], 0)
pos := close > hh[1] ? 1 : iff_1
iff_2 = reverse and pos == -1 ? 1 : pos
possig = reverse and pos == 1 ? -1 : iff_2
if possig == 1
strategy.entry('Long', strategy.long)
if possig == -1
strategy.entry('Short', strategy.short)
barcolor(possig == -1 ? color.red : possig == 1 ? color.green : color.blue)
plot(hh[1], color=color.new(color.green, 0), title='HH', linewidth=2)
plot(ll[1], color=color.new(color.red, 0), title='LL', linewidth=2)
|
Twin Range Filter Algo | https://www.tradingview.com/script/ZsiaNicR-Twin-Range-Filter-Algo/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 696 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © colinmck, greenmask9
//@version=4
strategy(title="Twin Range Filter Algo v.3", shorttitle = "Twin Range Strategy", overlay=true)
source = input(defval=close, title="Source")
// Smooth Average Range
per1 = input(defval=27, minval=1, title="Fast period", group ="Twin Range Filter @colinmck")
mult1 = input(defval=1.6, minval=0.1, title="Fast range", group ="Twin Range Filter @colinmck")
per2 = input(defval=55, minval=1, title="Slow period", group ="Twin Range Filter @colinmck")
mult2 = input(defval=2, minval=0.1, title="Slow range", group ="Twin Range Filter @colinmck")
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ema(abs(x - x[1]), t)
smoothrng = ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(source, per1, mult1)
smrng2 = smoothrng(source, per2, mult2)
smrng = (smrng1 + smrng2) / 2
// Range Filter
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(source, smrng)
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
hband = filt + smrng
lband = filt - smrng
longCond = bool(na)
shortCond = bool(na)
longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0
shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
long = longCond and CondIni[1] == -1
short = shortCond and CondIni[1] == 1
// Plotting
// Strategy
// From this part on, programmer is greenmaks9
//
Separator = input(title="Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")
disabler = input(title="Disable @greenmask9's ATR conditions", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")
//second
l2 = input(title="ATR1", defval=32, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")
s2 = input(title="Smoothing", defval="SMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")
atr2(source, l2) =>
if s2 == "SMA"
sma(source, l2)
else
if s2 == "RMA"
rma(source, l2)
else
if s2 == "EMA"
ema(source, l2)
else
wma(source, l2)
//third
l3 = input(title="ATR2", defval=64, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")
s3 = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")
atr3(source, l3) =>
if s3 == "RMA"
rma(source, l3)
else
if s3 == "SMA"
sma(source, l3)
else
if s3 == "EMA"
ema(source, l3)
else
wma(source, l3)
atr20=atr2(tr(true), l2)
atr30=atr3(tr(true), l3)
ordersize=floor(strategy.initial_capital/close)
maxcandles_till_close = input(title="Time-based Close", type=input.integer, defval=17, group = "Alternative Exit")
i_time = input(true, "Enable Time Base Close", group = "Alternative Exit" )
//stop
varip stop_long = 0.0, varip entry = 0.0, varip stop_short = 0.0
i_sl_type = input("Low - (close - lowest low[len]) * %", options = ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber"], title="Calculation (Long)", group = "Stop-loss", tooltip = "This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks is always substracted (added) after the initial calculation. ")
i_sl_atr = input(10, "Calculation Length", group = "Stop-loss")
i_sl_perc = input(80, "Percentage", group = "Stop-loss", type = input.float) / 100
i_sl_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * syminfo.mintick
i_stoploss = input(true, "Enable Stop-loss", group = "Stop-loss")
f_stop_long (calculation, length, mult, ticks) =>
stop_0 = calculation == "Low - (ATR[len] * %)" ? low - (atr(length) * mult) - ticks :
calculation == "Low - (close - lowest low[len]) * %" ? low - (close - (lowest(low, length))) * mult - ticks :
calculation == "Low - (close - average low[len]) * %" ? low - (close - sma(low, length)) * mult - ticks :
calculation == "Close - (ATR[len] * %)" ? close - (atr(length) * mult) - ticks :
low - ticks
f_stop_short (calculation, length, mult, ticks) =>
stop_0 = calculation == "Low - (ATR[len] * %)" ? high + (atr(length) * mult) + ticks :
calculation == "Low - (close - lowest low[len]) * %" ? high + abs(close - lowest(high, length)) * mult + ticks :
calculation == "Low - (close - average low[len]) * %" ? high + abs(close - sma(high, length)) * mult + ticks :
calculation == "Close - (ATR[len] * %)" ? close + (atr(length) * mult) + ticks :
high + ticks
//target
varip target_long = 0.0, varip target_short = 0.0
i_tr_type = input("Close + (ATR[len] * %)", options = ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %", "Close + abs(close - average high[len]) * %", "High + TicksNumber", "Close + TicksNumber"], title="Calculation (Long)", group = "Target", tooltip = "Raw number of ticks is always added to the target.")
i_tr_atr = input(10, "Calculation Length", group = "Target")
i_tr_perc = input(500, "Percentage", group = "Target", type = input.float) / 100
i_tr_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Target") * syminfo.mintick
i_target = input(true, "Enable Target", group = "Target")
f_target_long (calculation, length, mult, ticks) =>
stop_0 = calculation == "High + (ATR[len] * %)" ? high + (atr(length) * mult) + ticks :
calculation == "Close + (ATR[len] * %)" ? close + (atr(length) * mult) + ticks :
calculation == "Close + abs(close - highest high[len]) * %" ? close + abs(close - (highest(high, length))) * mult + ticks :
calculation == "Close + abs(close - average high[len]) * %" ? close + abs(close - sma(high, length)) * mult + ticks :
calculation == "High + TicksNumber" ? high + ticks :
close + ticks
f_target_short (calculation, length, mult, ticks) =>
stop_0 = calculation == "High + (ATR[len] * %)" ? low - (atr(length) * mult) - ticks :
calculation == "Close + (ATR[len] * %)" ? close - (atr(length) * mult) - ticks :
calculation == "Close + abs(close - highest high[len]) * %" ? close - abs(close - (lowest(low, length))) * mult - ticks :
calculation == "Close + abs(close - average high[len]) * %" ? close - abs(close - sma(low, length)) * mult - ticks :
calculation == "High + TicksNumber" ? low - ticks :
close - ticks
if (strategy.position_size >= 0 or strategy.position_size[1] != strategy.position_size)
stop_short := i_stoploss ? f_stop_short(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na
target_short := i_target ? f_target_short(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na
if (strategy.position_size <= 0 or strategy.position_size[1] != strategy.position_size)
stop_long := i_stoploss ? f_stop_long(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na
target_long := i_target ? f_target_long(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : na
if (strategy.position_size == 0 or strategy.position_size[1] != strategy.position_size)
entry := open
bull = long and (atr20<atr30 or disabler)
bear = short and (atr20<atr30 or disabler)
bullclock = barssince(bull)
bearclock = barssince(bear)
if (bull)
strategy.entry("Twin Long", strategy.long, ordersize)
strategy.exit("Exit", from_entry = "Twin Long", limit = target_long, stop = stop_long)
if (bear)
strategy.entry("Twin Short", strategy.short, ordersize)
strategy.exit("Exit", from_entry = "Twin Short", limit = target_short, stop = stop_short)
i_message_long = input("Long entry default message: x", "Long Entry Alert Message", group = "Alert")
i_long_alert = input(true,"Enable Long Alert", group = "Alert")
i_message_short = input("Long entry default message: x", "Short Entry Alert Message", group = "Alert")
i_short_alert = input(true,"Enable Short Alert", group = "Alert")
if (bull and strategy.position_size[1] == 0 and i_long_alert)
alert(i_message_long, alert.freq_once_per_bar_close)
if (bear and strategy.position_size[1] == 0 and i_short_alert)
alert(i_message_short, alert.freq_once_per_bar_close)
//time stoploss
if (i_time)
strategy.close("Twin Long", when = bullclock == maxcandles_till_close, comment = "Time")
strategy.close("Twin Short", when = bearclock == maxcandles_till_close, comment = "Time")
c_fill_stop = color.new(color.red, 90)
c_fill_target = color.new(color.green, 90)
p_longstop = plot(strategy.position_size > 0 and i_stoploss ? stop_long : na, linewidth = 2, color = color.red, style = plot.style_linebr)
p_shortstop = plot(strategy.position_size < 0 and i_stoploss ? stop_short : na, linewidth = 2, color = color.red, style = plot.style_linebr)
p_entry = plot(strategy.position_size != 0 ? entry : na, linewidth = 2, color = color.blue, style = plot.style_linebr)
p_longtarget = plot(strategy.position_size > 0 and i_target ? target_long : na, linewidth = 2, color = color.green, style = plot.style_linebr)
p_shorttarget = plot(strategy.position_size < 0 and i_target ? target_short : na, linewidth = 2, color = color.green, style = plot.style_linebr)
fill(p_entry, p_longstop, c_fill_stop)
fill(p_entry, p_shortstop, c_fill_stop)
fill(p_entry, p_longtarget, c_fill_target)
fill(p_entry, p_shorttarget, c_fill_target) |
CCU MFI + RSI + STOCH RSI | https://www.tradingview.com/script/pVHd5BHO-CCU-MFI-RSI-STOCH-RSI/ | Bangsoul | https://www.tradingview.com/u/Bangsoul/ | 578 | 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/
// Crypto Crew University strategy:
// Indicators: MFI, RSI, STOCH RSI
// Entry criteria: long when the three are oversold, short otherwise.
// Exit criteria: Take profit at Fib levels (not demonstrated here)
// © BTA crypto
//@version=4
strategy("Crypto Crew University")
//inputs
source = hlc3
rsi_length = input(14, minval=1)
mfi_lenght = input(14, minval=1)
smoothK = input(3, minval=1)
smoothD = input(3, minval=1)
lengthRSI = input(14, minval=1)
lengthStoch = input(14, minval=1)
okay = "Okay"
good = "Good"
veryGood = "Very good"
tradingOpportunity = input(title="Opportunity", defval=veryGood, options=[okay, good, veryGood])
longThreshhold = tradingOpportunity==okay? 40 : tradingOpportunity==good ? 30 : tradingOpportunity==veryGood? 20 : 0
shortThreshhold = tradingOpportunity==okay? 60 : tradingOpportunity==good ? 70 : tradingOpportunity==veryGood? 80 : 0
//lines
mfi = mfi(source, mfi_lenght)
rsi = rsi(source, rsi_length)
rsi1 = rsi(close, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)
longSignal = mfi<longThreshhold and rsi<longThreshhold and k<longThreshhold and d<longThreshhold? 1:-1
shortSignal = mfi>shortThreshhold and rsi>shortThreshhold and k>shortThreshhold and d>shortThreshhold? 1:-1
if longSignal > 0
strategy.entry("Long", strategy.long)
strategy.exit(id="Long Stop Loss", stop=strategy.position_avg_price*0.8) //20% stop loss
if shortSignal > 0
strategy.entry("Short", strategy.short)
strategy.exit(id="Short Stop Loss", stop=strategy.position_avg_price*1.2) //20% stop loss
plot(k, color=color.blue)
plot(d, color=color.red)
plot(rsi, color=color.yellow)
plot(mfi, color=color.blue)
hline(longThreshhold, color=color.gray, linestyle=hline.style_dashed)
hline(shortThreshhold, color=color.gray, linestyle=hline.style_dashed)
|
BV's MACD SIGNAL TESTER | https://www.tradingview.com/script/wDkkY18a/ | BVTradingJournal | https://www.tradingview.com/u/BVTradingJournal/ | 94 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vuagnouxb
//@version=4
strategy("BV's MACD SIGNAL TESTER", overlay=true)
//------------------------------------------------------------------------
//---------- Confirmation Calculation ------------ INPUT
//------------------------------------------------------------------------
// 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
// 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)
// -- Trade entry signals
signalChoice = input(title = "Choose your signal", defval = "Continuation", options = ["Continuation", "Reversal", "Histogram", "MACD Line ZC", "Signal Line ZC"])
continuationSignalLong = signalChoice == "Continuation" ? crossover(macd, signal) and macd > 0 :
signalChoice == "Reversal" ? crossover(macd, signal) and macd < 0 :
signalChoice == "Histogram" ? crossover(hist, 0) :
signalChoice == "MACD Line ZC" ? crossover(macd, 0) :
signalChoice == "Signal Line ZC" ? crossover(signal, 0) :
false
continuationSignalShort = signalChoice == "Continuation" ? crossunder(macd, signal) and macd < 0 :
signalChoice == "Reversal" ? crossover(signal, macd) and macd > 0 :
signalChoice == "Histogram" ? crossunder(hist, 0) :
signalChoice == "MACD Line ZC" ? crossunder(macd, 0) :
signalChoice == "Signal Line ZC" ? crossunder(signal, 0) :
false
longCondition = continuationSignalLong
shortCondition = continuationSignalShort
//------------------------------------------------------------------------
//---------- ATR MONEY MANAGEMENT ------------
//------------------------------------------------------------------------
SLmultiplier = 1.5
TPmultiplier = 1
JPYPair = input(type = input.bool, title = "JPY Pair ?", defval = false)
pipAdjuster = JPYPair ? 1000 : 100000
ATR = atr(14) * pipAdjuster // 1000 for jpy pairs : 100000
SL = ATR * SLmultiplier
TP = ATR * TPmultiplier
//------------------------------------------------------------------------
//---------- TIME FILTER ------------
//------------------------------------------------------------------------
YearOfTesting = input(title = "How many years of testing ?" , type = input.integer, defval = 3)
_time = 2020 - YearOfTesting
timeFilter = (year > _time)
//------------------------------------------------------------------------
//--------- ENTRY FUNCTIONS ----------- INPUT
//------------------------------------------------------------------------
if (longCondition and timeFilter)
strategy.entry("Long", strategy.long)
if (shortCondition and timeFilter)
strategy.entry("Short", strategy.short)
//------------------------------------------------------------------------
//--------- EXIT FUNCTIONS -----------
//------------------------------------------------------------------------
strategy.exit("ATR", from_entry = "Long", profit = TP, loss = SL)
strategy.exit("ATR", from_entry = "Short", profit = TP, loss = SL) |
Backtest Custom HiLo Strategy | https://www.tradingview.com/script/MxIfRoF0-Backtest-Custom-HiLo-Strategy/ | luyikaibr | https://www.tradingview.com/u/luyikaibr/ | 139 | 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/
// © luyikaibr
//@version=4
strategy("Backtest Custom HiLo Strategy", "BTCHiLoS", overlay=true, precision=2,
process_orders_on_close=true,
pyramiding=1,
close_entries_rule="FIFO",
initial_capital=100000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100.0)
// Configure backtest start date with inputs
startDay = input(title="Start Day", type=input.integer,
defval=2, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2020, minval=1800, maxval=2100)
// Set backtest end date with inputs
endDay = input(title="End Day", type=input.integer,
defval=31, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=10, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2020, minval=1800, maxval=2100)
endHour = input(title="End Hour", type=input.integer,
defval=17, minval=0, maxval=23)
endMin = input(title="End Minute", type=input.integer,
defval=0, minval=0, maxval=59)
startAtOrigin = input(false, title="Start at Origin")
endNow = input(false, title="End Now")
len = input(34, title="Length", minval=0)
offset = input(0, title="Offset", minval=0)
hiloType = input(title="Type", defval="HiLo", options=["HiLo", "HiLo Activator"])
simpleHiLo = (hiloType == "HiLo")
maType = input(title="MA Type", defval="SMA", options=["SMA", "EMA"])
useEMA = (maType == "EMA")
opType = input(title="Operation Type", defval="Long", options=["Long", "Short", "Both"])
opShort = (opType != "Long")
opLong = (opType != "Short")
opBoth = (opType == "Both")
hima = (useEMA ? ema(high, len) : sma(high, len))
loma = (useEMA ? ema(low, len) : sma(low, len))
hihi = (simpleHiLo ? na: highest(high, len))
lolo = (simpleHiLo ? na: lowest(low, len))
hilo = close
hilo := if simpleHiLo
(close < loma[offset] ? hima : (close > hima[offset] ? loma : hilo[1]))
else
(close < loma[offset] ? hihi : (close > hima[offset] ? lolo : hilo[1]))
hlColor = color.red
hlColor := (close < loma[offset] ? color.red : (close > hima[offset] ? color.green : hlColor[1]))
buyArith = sign(close - hima[offset])
sellArith = sign(close - loma[offset])
buyCond = (close > hima[offset])
sellCond = (close < loma[offset])
buy = crossover(buyArith, 0.5)
sell = crossunder(sellArith, -0.5)
buyState = false
buyState := buy ? true : (sell ? false : buyState[1])
sellState = false
sellState := buy ? false : (sell ? true : sellState[1])
enterBuyState = buyState[0] and not buyState[1]
enterSellState = sellState[0] and not sellState[1]
plot(hilo, color=hlColor, linewidth=2, style=plot.style_cross, transp=0, title="HiLo")
plotshape(enterBuyState, title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, transp = 0, size = size.tiny)
plotshape(enterSellState, title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.maroon,textcolor = color.white, transp = 0, size = size.tiny)
// See if this bar's time happened on/after start date
startDate = timestamp(syminfo.timezone, startYear, startMonth, startDay, 0, 0)
afterStartDate = if startAtOrigin
true
else
(time >= startDate)
atStartDate = if startAtOrigin
false
else
(time >= startDate and time < (startDate + time_close[1]-time_close[2]))
// See if bar's close time is before end date
endTS = if endNow
timenow - 2*(time_close[1]-time_close[2]) // 86400
else
timestamp(syminfo.timezone, endYear, endMonth, endDay, endHour, endMin, 0)
beforeEndDate = (time < endTS)
// Only submit enter long orders
strategy.risk.allow_entry_in(opBoth ? strategy.direction.all : (opLong ? strategy.direction.long : strategy.direction.short))
// Submit entry orders, but only on/after start date
if (atStartDate and beforeEndDate and buyCond)
strategy.entry(id="EL", long=true)
if (atStartDate and beforeEndDate and sellCond)
strategy.entry(id="ES", long=false)
if (afterStartDate and beforeEndDate and enterBuyState)
strategy.entry(id="EL", long=true)
if (afterStartDate and beforeEndDate and enterSellState)
strategy.entry(id="ES", long=false)
// if (barstate.islast or not beforeEndDate)
if (not beforeEndDate and strategy.position_size != 0)
strategy.close_all(comment="End")
|
ATR Trailing Stoploss Strategy | https://www.tradingview.com/script/NsD6sRKu/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 574 | 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("ATR Trailing Stoploss Strategy ",overlay=true)
Atr=input(defval=5,title="Atr Period",minval=1,maxval=500)
Hhv=input(defval=10,title="HHV Period",minval=1,maxval=500)
Mult=input(defval=2.5,title="Multiplier",minval=0.1)
Barcolor=input(true,title="Barcolor")
Prev = highest(high-Mult*atr(Atr),Hhv),barssince(close>highest(high-Mult*atr(Atr),Hhv) and close>close[1])
TS = iff(cum(1)<16 ,close,iff( close > highest(high-Mult*atr(Atr),Hhv) and close>close[1],highest(high-Mult*atr(Atr),Hhv),Prev))
Color=iff(close>TS,color.green,iff(close<TS,color.red,color.black))
barcolor(Barcolor? Color:na)
plot(TS,color=Color,linewidth=3,title="ATR Trailing Stoploss")
Buy = crossover(close,TS)
Sell = crossunder(close,TS)
if Buy
strategy.entry("Buy", strategy.long, comment="Buy")
if Sell
strategy.entry("Sell", strategy.short, comment="Sell") |
EURUSD 5min london session strategy | https://www.tradingview.com/script/E6yr9CoN-EURUSD-5min-london-session-strategy/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 159 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy(title="Moving Average", shorttitle="MA", overlay=true)
timeinrange(res, sess) => time(res, sess) != 0
len = input(5, minval=1, title="Length")
src = input(high, title="Source")
offset = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out = sma(src, len)
plot(out, color=color.white, title="MA", offset=offset)
len2 = input(5, minval=1, title="Length")
src2 = input(low, title="Source")
offset2 = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out2 = sma(src2, len2)
plot(out2, color=color.white, title="MA", offset=offset2)
length = input( 5 )
overSold = input( 10 )
overBought = input( 80 )
price = input(close, title="Source RSI")
vrsi = rsi(price, length)
longcond= close > out and close > out2 and vrsi > overBought and timeinrange(timeframe.period, "0300-1100")
shortcont = close < out and close < out2 and vrsi < overSold and timeinrange(timeframe.period, "0300-1100")
tp=input(150,title="tp")
sl=input(80,title="sl")
strategy.entry("long",1,when=longcond)
//strategy.close("long",when= close < out2)
strategy.exit("long_exit","long",profit=tp,loss=sl)
strategy.entry("short",1,when=shortcont)
//strategy.close("short",when=close >out)
strategy.exit("short_exit","short",profit=tp,loss=sl)
maxOrder = input(6, title="max trades per day")
maxRisk = input(2,type=input.float, title="maxrisk per day")
strategy.risk.max_intraday_filled_orders(maxOrder)
strategy.risk.max_intraday_loss(maxRisk, strategy.percent_of_equity)
strategy.close_all(when =not timeinrange(timeframe.period, "0300-1100"))
|
Long only strategy VWAP with BB and Golden Cross EMA50/200 | https://www.tradingview.com/script/6pBOpP3o-Long-only-strategy-VWAP-with-BB-and-Golden-Cross-EMA50-200/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 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/
// © mohanee
//@version=4
strategy(title="VWAP and BB strategy [$$]", overlay=true,pyramiding=2, default_qty_value=1, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 6, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2020, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 8, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
DST = 1 //day light saving for usa
//--- Europe
London = iff(DST==0,"0000-0900","0100-1000")
//--- America
NewYork = iff(DST==0,"0400-1300","0500-1400")
//--- Pacific
Sydney = iff(DST==0,"1300-2200","1400-2300")
//--- Asia
Tokyo = iff(DST==0,"1500-2400","1600-0100")
//-- Time In Range
timeinrange(res, sess) => time(res, sess) != 0
london = timeinrange(timeframe.period, London)
newyork = timeinrange(timeframe.period, NewYork)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
is_price_dipped_bb(pds,source1) =>
t_bbDipped=false
for i=1 to pds
t_bbDipped:= (t_bbDipped or close[i]<source1) ? true : false
if t_bbDipped==true
break
else
continue
t_bbDipped
is_bb_per_dipped(pds,bbrSrc) =>
t_bbDipped=false
for i=1 to pds
t_bbDipped:= (t_bbDipped or bbrSrc[i]<=0) ? true : false
if t_bbDipped==true
break
else
continue
t_bbDipped
// variables BEGIN
shortEMA = input(50, title="fast EMA", minval=1)
longEMA = input(200, title="slow EMA", minval=1)
//BB
smaLength = input(7, title="BB SMA Length", minval=1)
bbsrc = input(close, title="BB Source")
strategyCalcOption = input(title="strategy to use", type=input.string, options=["BB", "BB_percentageB"], defval="BB")
//addOnDivergence = input(true,title="Add to existing on Divergence")
//exitOption = input(title="exit on RSI or BB", type=input.string, options=["RSI", "BB"], defval="BB")
//bbSource = input(title="BB source", type=input.string, options=["close", "vwap"], defval="close")
//vwap_res = input(title="VWAP Resolution", type=input.resolution, defval="session")
stopLoss = input(title="Stop Loss%", defval=1, minval=1)
//variables END
longEMAval= ema(close, longEMA)
shortEMAval= ema(close, shortEMA)
ema200val = ema(close, 200)
vwapVal=vwap(close)
// Drawings
//plot emas
plot(shortEMAval, color = color.green, linewidth = 1, transp=0)
plot(longEMAval, color = color.orange, linewidth = 1, transp=0)
plot(ema200val, color = color.purple, linewidth = 2, style=plot.style_line ,transp=0)
//bollinger calculation
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = sma(bbsrc, smaLength)
dev = mult * stdev(bbsrc, smaLength)
upperBand = basis + dev
lowerBand = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
bbr = (bbsrc - lowerBand)/(upperBand - lowerBand)
//bollinger calculation
//plot bb
//plot(basis, "Basis", color=#872323, offset = offset)
p1 = plot(upperBand, "Upper", color=color.teal, offset = offset)
p2 = plot(lowerBand, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)
plot(vwapVal, color = color.purple, linewidth = 2, transp=0)
// Colour background
//barcolor(shortEMAval>longEMAval and close<=lowerBand ? color.yellow: na)
//longCondition= shortEMAval > longEMAval and close>open and close>vwapVal
longCondition= ( shortEMAval > longEMAval and close>open and close>vwapVal and close<upperBand ) //and time_cond // and close>=vwapVal
//Entry
strategy.entry(id="long", comment="VB LE" , long=true, when= longCondition and ( strategyCalcOption=="BB"? is_price_dipped_bb(10,lowerBand) : is_bb_per_dipped(10,bbr) ) and strategy.position_size<1 ) //is_price_dipped_bb(10,lowerBand)) //and strategy.position_size<1 is_bb_per_dipped(15,bbr)
//add to the existing position
strategy.entry(id="long", comment="Add" , long=true, when=strategy.position_size>=1 and close<strategy.position_avg_price and close>vwapVal) //and time_cond)
barcolor(strategy.position_size>=1 ? color.blue: na)
strategy.close(id="long", comment="TP Exit", when=crossover(close,upperBand) )
//stoploss
stopLossVal = strategy.position_avg_price * (1-(stopLoss*0.01) )
//strategy.close(id="long", comment="SL Exit", when= close < stopLossVal)
//strategy.risk.max_intraday_loss(stopLoss, strategy.percent_of_equity) |
VWMA_withATRstops_strategy | https://www.tradingview.com/script/HY2GjJIc-VWMA-withATRstops-strategy/ | ediks123 | https://www.tradingview.com/u/ediks123/ | 522 | 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("", overlay=true)
strategy(title="VWMA_withATRstops_strategy V2", overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
float xATRTrailingStop=na
int pos=na
vwmalength = input(33, title="VWMA Length", minval=1, maxval=365)
//vwmalength2 = input(9, title="VWAM Short Term Length", minval=1, maxval=365)
nATRPeriod = input(33, title="ATR length", minval=1, maxval=365)
nATRMultip = input(3.5, title="ATR Multiplier")
rsiofVwmaLength=input(14, title="RSI of VWMA Length")
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(5,title="Stop Loss",minval=1)
vwmaVal=vwma(close, vwmalength)
//vwmaVal2=vwma(close, vwmalength2)
//maVal=sma(close, vwmalength)
plot(vwmaVal, color=color.orange, linewidth=2, title="VWMA")
//plot(vwmaVal2, color=color.blue, title="VWMA Short Term")
//plot(maVal, color=color.blue, title="MA")
//rsi of vwma Longterm
rsiofVwmaVal=rsi(vwmaVal,rsiofVwmaLength)
xATR = atr(nATRPeriod)
nLoss = nATRMultip * xATR
xATRTrailingStop:= iff(close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), close - nLoss), iff(close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), close + nLoss), iff(close > nz(xATRTrailingStop[1], 0), close - nLoss, close + nLoss)))
pos:= iff(close[1] < nz(xATRTrailingStop[1], 0) and close > nz(xATRTrailingStop[1], 0), 1, iff(close[1] > nz(xATRTrailingStop[1], 0) and close < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0)))
color1 = pos == -1 ? color.red: pos == 1 ? color.green : color.blue
//plot(xATRTrailingStop, color=color1, title="ATR Trailing Stop")
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//Long Entry
//strategy.entry(id="VWMA LE", long=true, qty=qty1, when= close >vwmaVal and open>vwmaVal and close>open and close > xATRTrailingStop and xATRTrailingStop> vwmaVal)
strategy.entry(id="VWMA LE", long=true, qty=qty1, when= rsiofVwmaVal>=30 and close>open and close>vwmaVal and pos == 1 ) ///pos == 1 means ATRStop line is green
//vwmaVal2>vwmaVal and
plot(strategy.position_size>=1 ? xATRTrailingStop : na, color=color1, style=plot.style_linebr, title="ATR Trailing Stop")
bgcolor(strategy.position_size>=1 ? color.blue : na )
//Exit
strategy.close(id="VWMA LE", when= strategy.position_size>=1 and crossunder(close, xATRTrailingStop) )
//strategy.close(id="VWMA LE", when= strategy.position_size>=1 and close<vwmaVal and open<vwmaVal and close<open ) |
Linear trend | https://www.tradingview.com/script/C7OvNbAU-Linear-trend/ | RafaelZioni | https://www.tradingview.com/u/RafaelZioni/ | 760 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RafaelZioni
//@version=4
strategy(title = "Linear trend", overlay = true)
//
c = input(close)
len = input(200, minval=1),off= 0,dev= input(4, "Deviation")
lreg = linreg(c, len, off), lreg_x =linreg(c, len, off+1)
b = bar_index, s = lreg - lreg_x,intr = lreg - b*s
dS = 0.0
for i=0 to len-1
dS:= dS + pow(c[i]-(s*(b-i)+intr), 2)
de = sqrt(dS/(len))
up = (-de*dev) + lreg
down= (de*dev) + lreg
up_t = 0.0
up_t := c[1] > up_t[1] ? max(up, up_t[1]) : up
down_t = 0.0
down_t := c[1] < down_t[1] ? min(down, down_t[1]) : down
trend = 0
trend := c > down_t[1] ? 1: c < up_t[1] ? -1 : nz(trend[1], 1)
//
r_line = trend ==1 ? up_t : down_t
plot(r_line)
buy=crossover( c, r_line)
sell=crossunder(c, r_line)
plotshape(buy, style=shape.triangleup, size=size.normal, location=location.belowbar, color=color.lime)
plotshape(sell, style=shape.triangledown, size=size.normal, location=location.abovebar, color=color.red)
/////// Alerts /////
alertcondition(buy,title="buy")
alertcondition(sell,title="sell")
|
TrianglePoint strategy | https://www.tradingview.com/script/hWvuZJN1-TrianglePoint-strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 152 | 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="TrianglePoint strategy", overlay=true,pyramiding=2, default_qty_value=3, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)
// variables BEGIN
//find the index of highest high of n periods
index_HH(pds) =>
tHH =0.00
HH_index=1
for i=1 to pds
if high[i]>tHH
tHH:=high[i]
HH_index:=i
HH_index
//find the index of lowest low of n periods
index_LL(pds) =>
tLL = low[0]
LL_index=1
for i=1 to pds
if low[i]<tLL
tLL:=low[i]
LL_index:=i
LL_index
numPeriods=input(9,title="Number of Bars")
fastEMA = input(13, title="fast EMA", minval=1)
slowEMA = input(65, title="slow EMA", minval=1)
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
changeBarColor = input(true, title="chage bar color")
//showAllTriangles = input(true, title="show All Triangles")
HH = highest(close,numPeriods)
LL = lowest(close,numPeriods)
tringlePoint = low > LL and high < HH
//HH = highest(high,numPeriods) ///close[1],numPeriod
//LL = lowest(low,numPeriods) //close[1],numPeriods
fastEMAval= ema(close, fastEMA)
slowEMAval= ema(close, slowEMA)
two100EMAval= ema(close, 200)
//plot emas
plot(fastEMAval, color = color.green, linewidth = 1, transp=0)
plot(slowEMAval, color = color.orange, linewidth = 1, transp=0)
plot(two100EMAval, color = color.purple, linewidth = 2, transp=0)
longCondition=fastEMAval>two100EMAval and tringlePoint //and close>two100EMAval
// On the last price bar, make a new trend line
HH_index=index_HH(numPeriods)
LL_index=index_LL(numPeriods)
if (longCondition and strategy.position_size<1 ) //and barstate.islast
line.new(x1=bar_index[LL_index ], y1=low[LL_index],
x2=bar_index, y2=close, color=color.red, width=2)
line.new(x1=bar_index[HH_index], y1=high[HH_index],
x2=bar_index, y2=close, color=color.green, width=2)
line.new(x1=bar_index[HH_index], y1=high[HH_index],
x2=bar_index[LL_index], y2=low[LL_index], color=color.blue, width=2)
//Entry
strategy.entry(id="TBT LE", comment="TBT LE" , long=true, stop=close[0]+0.10 ,when= longCondition and strategy.position_size<1 )
//Add
strategy.entry(id="TBT LE", comment="Add" , long=true, when= longCondition and strategy.position_size>=1 and close<strategy.position_avg_price)
//barcolor(strategy.position_size>=1 ? color.blue : na)
//Take profit
takeProfitVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1+(stopLoss*0.01) )) : 0.00
//strategy.close(id="TBT LE", comment="Profit Exit", qty=strategy.position_size/2, when=close>=takeProfitVal and close<open and close<fastEMAval) //crossunder(close,fastEMAval)
barcolor(strategy.position_size>=1 and changeBarColor==true ? (close>takeProfitVal? color.purple : color.blue): na)
//Exit
strategy.close(id="TBT LE", comment="TBT Exit", when=crossunder(fastEMAval,slowEMAval))
//stoploss
stopLossVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//stopLossVal= close> (strategy.position_avg_price * (1+(stopLoss*0.01) )) ? lowest(close,numPeriods) : (strategy.position_avg_price * (1-(stopLoss*0.01) ))
strategy.close(id="TBT LE", comment="SL Exit", when= close < stopLossVal) |
Automated - Fibs with Market orders | https://www.tradingview.com/script/69YQAwdS-Automated-Fibs-with-Market-orders/ | CryptoRox | https://www.tradingview.com/u/CryptoRox/ | 442 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CryptoRox
//@version=4
//Paste the line below in your alerts to run the built-in commands.
//{{strategy.order.alert_message}}
strategy("Automated - Fibs with Market orders", "Strategy", true, precision=8, pyramiding=1000, commission_type=strategy.commission.percent, commission_value=0.04)
//Settings
testing = input(false, "Live")
//Use epochconverter or something similar to get the current timestamp.
starttime = input(1600976975, "Start Timestamp") * 1000
//Wait XX seconds from that timestamp before the strategy starts looking for an entry.
seconds = input(60, "Start Delay") * 1000
testPeriod = testing ? time > starttime + seconds : 1
leverage = input(1, "Leverage")
tp = input(1.0, "Take Profit %") / leverage
dca = input(-1.0, "DCA when < %") / leverage *-1
fibEntry = input("1", "Entry Level", options=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])
//Strategy Calls
equity = strategy.equity
avg = strategy.position_avg_price
symbol = syminfo.tickerid
openTrades = strategy.opentrades
closedTrades = strategy.closedtrades
size = strategy.position_size
//Fibs
lentt = input(60, "Pivot Length")
h = highest(lentt)
h1 = dev(h, lentt) ? na : h
hpivot = fixnan(h1)
l = lowest(lentt)
l1 = dev(l, lentt) ? na : l
lpivot = fixnan(l1)
z = 400
p_offset= 2
transp = 60
a=(lowest(z)+highest(z))/2
b=lowest(z)
c=highest(z)
fib0 = (((hpivot - lpivot)) + lpivot)
fib1 = (((hpivot - lpivot)*.21) + lpivot)
fib2 = (((hpivot - lpivot)*.3) + lpivot)
fib3 = (((hpivot - lpivot)*.5) + lpivot)
fib4 = (((hpivot - lpivot)*.62) + lpivot)
fib5 = (((hpivot - lpivot)*.7) + lpivot)
fib6 = (((hpivot - lpivot)* 1.00) + lpivot)
fib7 = (((hpivot - lpivot)* 1.27) + lpivot)
fib8 = (((hpivot - lpivot)* 2) + lpivot)
fib9 = (((hpivot - lpivot)* -.27) + lpivot)
fib10 = (((hpivot - lpivot)* -1) + lpivot)
notna = nz(fib10[60])
entry = 0.0
if fibEntry == "1"
entry := fib10
if fibEntry == "2"
entry := fib9
if fibEntry == "3"
entry := fib0
if fibEntry == "4"
entry := fib1
if fibEntry == "5"
entry := fib2
if fibEntry == "6"
entry := fib3
if fibEntry == "7"
entry := fib4
if fibEntry == "8"
entry := fib5
if fibEntry == "9"
entry := fib6
if fibEntry == "10"
entry := fib7
profit = avg+avg*(tp/100)
pause = 0
pause := nz(pause[1])
paused = time < pause
fill = 0.0
fill := nz(fill[1])
count = 0.0
count := nz(fill[1])
filled = count > 0 ? entry > fill-fill/100*dca : 0
signal = testPeriod and notna and not paused and not filled ? 1 : 0
neworder = crossover(signal, signal[1])
moveorder = entry != entry[1] and signal and not neworder ? true : false
cancelorder = crossunder(signal, signal[1]) and not paused
filledorder = crossunder(low[1], entry[1]) and signal[1]
last_profit = 0.0
last_profit := nz(last_profit[1])
// if neworder and signal
// strategy.order("New", 1, 0.0001, alert_message='New Order|e=binancefuturestestnet s=btcusdt b=long q=0.0011 fp=' + tostring(entry))
// if moveorder
// strategy.order("Move", 1, 0.0001, alert_message='Move Order|e=binancefuturestestnet s=btcusdt b=long c=order|e=binancefuturestestnet s=btcusdt b=long q=0.0011 fp=' + tostring(entry))
if filledorder and size < 1
fill := entry
count := count+1
pause := time + 60000
p = close+close*(tp/100)
strategy.entry("Buy", 1, 1, alert_message='Long|e=binancefuturestestnet s=btcusdt b=long q=0.0011 t=market')
if filledorder and size >= 1
fill := entry
count := count+1
pause := time + 60000
strategy.entry("Buy", 1, 1, alert_message='Long|e=binancefuturestestnet s=btcusdt b=long q=0.0011 t=market')
// if cancelorder and not filledorder
// pause := time + 60000
// strategy.order("Cancel", 1, 0.0001, alert_message='Cancel Order|e=binancefuturestestnet s=btcusdt b=long c=order')
if filledorder
last_profit := profit
closeit = crossover(high, profit) and size >= 1
if closeit
strategy.entry("Close ALL", 0, 0, alert_message='Close Long|e=binancefuturestestnet s=btcusdt b=long c=position t=market')
count := 0
fill := 0.0
last_profit := 0.0
//Plots
// bottom = signal ? color.green : filled ? color.red : color.white
// plot(entry, "Entry", bottom) |
Golden Triangle Strategy | https://www.tradingview.com/script/YC0Fpmus-Golden-Triangle-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 569 | 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
//Golden Triangle strategy setup is a variation of the buy-the-dip strategy, by Charlotte Hudgin.
//You can find the detailed explanataion here by Thomas N. Bulkowski http://thepatternsite.com/GoldenTriangle.html
strategy(title="Golden Triangle Strategy", overlay=true,pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=10000, currency=currency.USD, max_bars_back=200)
// variables BEGIN
var triangleFound=false
var windupPrice=0.00
var stopLossVal=0.00
//find the index of highest high of n periods
findIndexForWhiteSpace(smaLength1, lookbackPds1) =>
prev_index=0
smaVal1=sma(close, smaLength1)
for i=1 to lookbackPds1
if low[i]<smaVal1[i] and close[i]>smaVal1[i]
prev_index:=i
break
if open[i] < smaVal1[1] and high[i]<smaVal1[i]
prev_index:=0
break
prev_index
//find the index of highest high of n periods
index_HH(pds) =>
tHH =0.00
HH_index=1
for i=1 to pds
if high[i]>tHH
tHH:=high[i]
HH_index:=i
HH_index
//find the index of lowest low of n periods
index_LL(pds) =>
tLL = low[0]
LL_index=1
for i=1 to pds
if low[i]<tLL
tLL:=low[i]
LL_index:=i
LL_index
smaLength=input(50,title="SMA Length")
lookBackPds=input(200,title="Look Back periods")
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss = input(title="Stop Loss%", defval=6, minval=1)
changeBarColor = input(true, title="chage bar color")
showAllTriangles = input(false, title="show Triangles even after Long position is taken")
//pivot points
pivotPeriod = input(defval = 5, title="Pivot Point Period", minval = 1, maxval = 50)
atrFactor=input(defval = 3, title = "ATR Factor", minval = 1, step = 0.1)
atrPeriod=input(defval = 50, title = "ATR Period", minval=1)
smaVal = sma(close, smaLength)
//plot sma
plot(smaVal, color = color.green, linewidth = 1, transp=0)
isPriceAbove50=true
for i=1 to 10
if not(high[i]>smaVal and low[i]>smaVal)
isPriceAbove50:=false
break
longCondition= isPriceAbove50 and high>smaVal and low<smaVal //check for current candle
lastIndex=findIndexForWhiteSpace(smaLength, lookBackPds)
// On the last price bar, make a new trend line
HH_index=index_HH(lastIndex)
//LL_index=index_LL(numPeriods)
drawCondition=showAllTriangles==true ? longCondition and lastIndex>1 : longCondition and lastIndex>1 and strategy.position_size<1
if (drawCondition ) //longCondition and lastIndex>1 ) //and strategy.position_size<1
//draw line from last touch point to pivot (Gighest High)
line.new(x1=bar_index[lastIndex], y1=low[lastIndex],
x2=bar_index[HH_index], y2=high[HH_index], color=color.red, width=2)
//draw line from Highest to current price touch point
line.new(x1=bar_index[HH_index], y1=high[HH_index],
x2=bar_index, y2=close, color=color.green, width=2)
//draw line from previous touch to current touch -- This is trianle base
line.new(x1=bar_index[lastIndex], y1=low[lastIndex],
x2=bar_index, y2=close, color=color.blue, width=2)
triangleFound:=true
windupPrice:=low[lastIndex] //+ ( abs(high[HH_index]-low[lastIndex])*0.61)
//mycomment:="High="+tostring(HH_index,"######")
//voulmeConfirmed= triangleFound and volume[0]>volume[1] and volume[0]>volume[2] and volume[0]>volume[3] and volume[0]>volume[4]
vwapVal=vwap
//pivot points calculation BEGIN
float pvtHigh = na
float pvtLow = na
pvtHigh := pivothigh(pivotPeriod, pivotPeriod)
pvtLow := pivotlow(pivotPeriod, pivotPeriod)
float center = na
center := center[1]
float lastpp = pvtHigh ? pvtHigh : pvtLow ? pvtLow : na
if lastpp
if na(center)
center := lastpp
else
center := (center * 2 + lastpp) / 3
Up = center - (atrFactor * atr(atrPeriod))
Dn = center + (atrFactor * atr(atrPeriod))
float TUp = na
float TDown = na
Trend = 0
TUp := close[1] > TUp[1] ? max(Up, TUp[1]) : Up
TDown := close[1] < TDown[1] ? min(Dn, TDown[1]) : Dn
Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1)
//Trailingsl = Trend ==s 1 ? TUp : TDown
//draw pivot points
Trailingstop = Trend == 1 ? TUp : TDown
tslColor = Trend == 1 and nz(Trend[1]) == 1 ? color.lime : Trend == -1 and nz(Trend[1]) == -1 ? color.red : na
plot(Trend==1 ? TUp:na, color = tslColor , linewidth = 2, title = "Pivot Trailing Stop")
//pivot points calculation END
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//Entry
//strategy.entry(id="GT LE", comment="GT LE SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"), long=true, qty=qty1 , when= triangleFound and crossover(close,vwapVal) ) //and strategy.position_size<1
strategy.entry(id="GT LE", comment="GT LE SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"), long=true, qty=qty1 , when= triangleFound and Trend == 1 and crossover(close,vwapVal) ) //and strategy.position_size<1
triangleFound:= strategy.position_size>=1 ? false :triangleFound
//stoploss
stopLossVal:= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//Add
//if (strategy.position_size>=1 and close>stopLossVal and close<TUp ) //longCondition and crossover(close, vwapVal)
// strategy.entry(id="GT LE", comment="Add", long=true, when= strategy.position_size>=1 and longCondition and close>vwapVal) //close<strategy.position_avg_price and crossover(close,smaVal))
// strategy.entry(id="GT LE", comment="Add new SL="+tostring(close*(1-(stopLoss*0.01)), "####.##"), long=true)
//stoploss
//stopLossVal:= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//barcolor(strategy.position_size>=1 ? color.blue : na)
//Take profit
takeProfitVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1+(2*0.01) )) : 0.00
//takeProfitVal= strategy.position_size>=1 ? windupPrice : 0.00
//barcolor(strategy.position_size>=1 and changeBarColor==true ? (close>takeProfitVal? color.purple : color.blue): na)
//draw initil stop loss
plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
bgcolor(strategy.position_size>=1?color.blue:na, transp=80)
//plot(close>strategy.position_avg_price ? TUp: stopLossVal>0 ? stopLossVal : na, color = color.green , linewidth = 2, title = "Pivot Trailing Stop")
//Exit
//strategy.close(id="GT LE", comment="GT Exit", when=close>=takeProfitVal)
//strategy.close(id="GT LE", comment="GT Exit", when=close>takeProfitVal and crossunder(close,smaVal)) --- original
//strategy.close(id="GT LE", comment="GTVW Exit points="+tostring(close-strategy.position_avg_price,"###.##"), when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal) ) //close<vwapVal and close<smaVal)
strategy.close(id="GT LE", comment="GTVW Exit points="+tostring(close-strategy.position_avg_price,"###.##"), when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal)) // and crossunder(vwapVal,smaVal)
//strategy.close(id="GT LE", comment="GTVW Exit points="+tostring(close-strategy.position_avg_price,"###.##"), when= vwapVal < TUp ) // and crossunder(vwapVal,smaVal)
//strategy.close(id="GT LE", comment="GTVW Exit points="+tostring(close-strategy.position_avg_price,"###.##"), when=close>strategy.position_avg_price and crossunder(vwapVal,smaVal))
//strategy.close(id="GT LE", comment="SL Exit points="+tostring(close-strategy.position_avg_price,"###.##") , when= close< stopLossVal ) //windupPrice
strategy.close(id="GT LE", comment="SL Exit points="+tostring(close-strategy.position_avg_price,"###.##") , when=crossunder(close,stopLossVal) ) //windupPrice (strategy.position_avg_price - close ) > 10
|
Lagged Donchian Channel + EMA | https://www.tradingview.com/script/1952PBhO/ | Mysteriown | https://www.tradingview.com/u/Mysteriown/ | 197 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mysteriown
//@version=4
strategy("Lagged Donchian Channel + EMA", overlay = true)
//tradePeriod = time(timeframe.period,"0000-0000:1234567")?true:false
// ------------------------------------------ //
// ----------------- Inputs ----------------- //
// ------------------------------------------ //
period = input(24, title="Channel's periods")
Pema = input(200, title="EMA's periods ?")
ratio = input(3, title="Ratio TP", type=input.float)
loss = input(20, title="Risk Loss ($)")
lev = input(5, title="Leverage *...")
chan = input(title="Plot channel ?", type=input.bool, defval=false)
Bpos = input(title="Plot Bull positions ?", type=input.bool, defval=false)
bpos = input(title="Plot Bear positions ?", type=input.bool, defval=false)
labels = input(title="Plot labels of bets ?", type=input.bool, defval=true)
supp = input(title="Delete last labels ?", type=input.bool, defval=true)
// ------------------------------------------ //
// ---------- Canal, EMA and arrow ---------- //
// ------------------------------------------ //
pema = ema(close,Pema)
plot(pema, title="EMA", color=color.blue)
canalhaut = highest(period)[1]
canalbas = lowest(period)[1]
bear = close[1] > canalhaut[1] and close < open and high > pema
bull = close[1] < canalbas[1] and open < close and low < pema
canalhautplot = plot(chan? canalhaut:na, color=color.yellow)
canalbasplot = plot(chan? canalbas:na, color=color.yellow)
plotshape(bear, title='Bear', style=shape.triangledown, location=location.abovebar, color=color.red, offset=0)
plotshape(bull, title='Bull', style=shape.triangleup, location=location.belowbar, color=color.green, offset=0)
// ------------------------------------------ //
// ------------- Position Short ------------- //
// ------------------------------------------ //
SlShort = highest(3)
BidShort = close[1]
TpShort = BidShort-((SlShort-BidShort)*ratio)
deltaShort = (SlShort-BidShort)/BidShort
betShort = round(loss/(lev*deltaShort)*100)/100
cryptShort = round(betShort*lev/BidShort*1000)/1000
if bear[1] and labels //and low < low[1]
Lbear = label.new(bar_index, na, text="SHORT\n\nSL: " + tostring(SlShort) + "\n\nBid: " + tostring(BidShort) + "\n\nTP: " + tostring(TpShort) + "\n\nMise: " + tostring(betShort) + "\n\nCryptos: " + tostring(cryptShort), color=color.red, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
label.delete(supp ? Lbear[1] : na)
var bentry=0.0
var bsl=0.0
var btp=0.0
if bear[1] and low < low[1]
bentry:=BidShort
bsl:=SlShort
btp:=TpShort
pbentry = plot(bpos? bentry:na, color=color.orange)
plot(bpos? (bentry+btp)/2:na, color=color.gray)
pbsl = plot(bpos? bsl:na, color=color.red)
pbtp = plot(bpos? btp:na, color=color.green)
fill(pbentry,pbsl, color.red, transp=70)
fill(pbentry,pbtp, color.green, transp=70)
// ------------------------------------------ //
// ------------- Position Long -------------- //
// ------------------------------------------ //
SlLong = lowest(3)
BidLong = close[1]
TpLong = BidLong + ((BidLong - SlLong) * ratio)
deltaBull = (BidLong - SlLong)/BidLong
betLong = round(loss/(lev*deltaBull)*100)/100
cryptLong = round(betLong*lev/BidLong*1000)/1000
if bull[1] and labels //and high > high[1]
Lbull = label.new(bar_index, na, text="LONG\n\nSL: " + tostring(SlLong) + "\n\nBid: " + tostring(BidLong) + "\n\nTP: " + tostring(TpLong) + "\n\nMise: " + tostring(betLong) + "\n\nCryptos: " + tostring(cryptLong), color=color.green, textcolor=color.white, style=label.style_labelup, yloc=yloc.belowbar)
label.delete(supp ? Lbull[1] : na)
var Bentry=0.0
var Bsl=0.0
var Btp=0.0
if bull[1] and high > high[1]
Bentry:=BidLong
Bsl:=SlLong
Btp:=TpLong
pBentry = plot(Bpos?Bentry:na, color=color.orange)
plot(Bpos?(Bentry+Btp)/2:na, color=color.gray)
pBsl = plot(Bpos?Bsl:na, color=color.red)
pBtp = plot(Bpos?Btp:na, color=color.green)
fill(pBentry,pBsl, color.red, transp=70)
fill(pBentry,pBtp, color.green, transp=70)
// ------------------------------------------ //
// --------------- Strategie ---------------- //
// ------------------------------------------ //
Bear = bear[1] and low < low[1]
Bull = bull[1] and high > high[1]
if (Bear and strategy.opentrades==0)
strategy.order("short", false, 1, limit=BidShort)
strategy.exit("exit", "short", limit = TpShort, stop = SlShort)
strategy.cancel("short", when = high > SlShort or low < (BidShort+TpShort)/2)
strategy.close("short", when=bull)
if (Bull and strategy.opentrades==0)
strategy.order("long", true, 1, limit=BidLong)
strategy.exit("exit", "long", limit = TpLong, stop = SlLong)
strategy.cancel("long", when = low < SlLong or high > (BidLong+TpLong)/2)
strategy.close("long", when=bear)
|
ATR Trailing Stop Strategy by ceyhun | https://www.tradingview.com/script/cj3MJWNz/ | ceyhun | https://www.tradingview.com/u/ceyhun/ | 1,408 | 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("ATR Trailing Stop Strategy by ceyhun", overlay=true)
/////////notes////////////////////////////////////////
// This is based on the ATR trailing stop indicator //
// width addition of two levels of stops and //
// different interpretation. //
// This is a fast-reacting system and is better //
// suited for higher volatility markets //
//////////////////////////////////////////////////////
SC = input(close, "Source", input.source)
// Fast Trail //
AP1 = input(5, "Fast ATR period", input.integer) // ATR Period
AF1 = input(0.5, "Fast ATR multiplier", input.float) // ATR Factor
SL1 = AF1 * atr(AP1) // Stop Loss
Trail1 = 0.0
Trail1 := iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1), iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0), min(nz(Trail1[1], 0), SC + SL1), iff(SC > nz(Trail1[1], 0), SC - SL1, SC + SL1)))
// Slow Trail //
AP2 = input(10, "Slow ATR period", input.integer) // ATR Period
AF2 = input(3, "Slow ATR multiplier", input.float) // ATR Factor
SL2 = AF2 * atr(AP2) // Stop Loss
Trail2 = 0.0
Trail2 := iff(SC > nz(Trail2[1], 0) and SC[1] > nz(Trail2[1], 0), max(nz(Trail2[1], 0), SC - SL2), iff(SC < nz(Trail2[1], 0) and SC[1] < nz(Trail2[1], 0), min(nz(Trail2[1], 0), SC + SL2), iff(SC > nz(Trail2[1], 0), SC - SL2, SC + SL2)))
// Bar color for trade signal //
Green = Trail1 > Trail2 and close > Trail2 and low > Trail2
Blue = Trail1 > Trail2 and close > Trail2 and low < Trail2
Red = Trail2 > Trail1 and close < Trail2 and high < Trail2
Yellow = Trail2 > Trail1 and close < Trail2 and high > Trail2
// Signals //
Bull = barssince(Green) < barssince(Red)
Bear = barssince(Red) < barssince(Green)
Buy = crossover(Trail1, Trail2)
Sell = crossunder(Trail1, Trail2)
TS1 = plot(Trail1, "Fast Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.blue : color.yellow, linewidth=2, display=display.none)
TS2 = plot(Trail2, "Slow Trail", style=plot.style_line,color=Trail1 > Trail2 ? color.green : color.red, linewidth=2)
fill(TS1, TS2, Bull ? color.new(color.green,90) : color.new(color.red,90))
plotcolor = input(true, "Paint color on chart", input.bool)
bcl = iff(plotcolor == 1, Blue ? color.blue : Green ? color.lime : Yellow ? color.yellow : Red ? color.red : color.white, na)
barcolor(bcl)
if Buy
strategy.entry("Buy", strategy.long, comment="Buy")
if Sell
strategy.entry("Sell", strategy.short, comment="Sell")
|
EMA Crossover Strategy Example | https://www.tradingview.com/script/t8bUvS4q-EMA-Crossover-Strategy-Example/ | ParametricTrading | https://www.tradingview.com/u/ParametricTrading/ | 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/
//@version=4
strategy("EMA Crossover Strategy", overlay=true)
////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
// From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2020, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
////////////////////////////////////////////////////////////////////////////////
//CREATE USER-INPUT VARIABLES
periodShort = input(13, minval=1, title="Enter Period for Short Moving Average")
smoothingShort = input(title="Choose Smoothing Type for Short Moving Average", defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "LSMA"])
periodLong = input(48, minval=1, title="Enter Period for Long Moving Average")
smoothingLong = input(title="Choose Smoothing Type for Long Moving Average", defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "LSMA"])
periodExit = input(30, minval=1, title="Enter Period for Exit Moving Average")
smoothingExit = input(title="Choose Smoothing Type for Exit Moving Average", defval="EMA", options=["RMA", "SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "LSMA"])
src1 = close
pivot = (high + low + close) / 3
//MA CALCULATION FUNCTION
ma(smoothing, src, length) =>
if smoothing == "RMA"
rma(src, length)
else
if smoothing == "SMA"
sma(src, length)
else
if smoothing == "EMA"
ema(src, length)
else
if smoothing == "WMA"
wma(src, length)
else
if smoothing == "VWMA"
vwma(src, length)
else
if smoothing == "SMMA"
na(src[1]) ? sma(src, length) : (src[1] * (length - 1) + src) / length
else
if smoothing == "HullMA"
wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length)))
//ASSIGN A MOVING AVERAGE RESULT TO A VARIABLE
shortMA=ma(smoothingShort, pivot, periodShort)
longMA=ma(smoothingLong, pivot, periodLong)
exitMA=ma(smoothingExit, pivot, periodExit)
//PLOT THOSE VARIABLES
plot(shortMA, linewidth=4, color=color.yellow,title="The Short Moving Average")
plot(longMA, linewidth=4, color=color.blue,title="The Long Moving Average")
plot(exitMA, linewidth=1, color=color.red,title="The Exit CrossUnder Moving Average")
//BUY STRATEGY
buy = crossover(shortMA,longMA) ? true : na
exit = crossunder(close,exitMA) ? true : na
strategy.entry("long",true,when=buy and time_cond)
strategy.close("long",when=exit and time_cond)
if (not time_cond)
strategy.close_all()
|
Heikin Ashi + Price Action Crypto LONG Strategy | https://www.tradingview.com/script/FEJvYRkw-Heikin-Ashi-Price-Action-Crypto-LONG-Strategy/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 626 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy(title="random", shorttitle="random", overlay=true, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.1 )
UseHAcandles = input(true, title="Use Heikin Ashi Candles in Algo Calculations")
//
// === /INPUTS ===
// === BASE FUNCTIONS ===
haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close
haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open
haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high
haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low
long = haClose > haHigh[1] and haClose > haOpen and haHigh[1] > haHigh[2] //and close > high[3]
short = haClose < haOpen and haClose < haLow[1]
strategy.entry("long",1,when=long)
//strategy.entry("short",0,when=short)
strategy.close("long",when=short)
//strategy.close_all() |
© Investoz trendwarning | https://www.tradingview.com/script/gsN8bTja/ | Investoz | https://www.tradingview.com/u/Investoz/ | 85 | 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/
// © Investoz
// Indikatorn är byggd som ett utbildningsyfte och är därför ingen rekommendation för köp/sälj av aktier. Tanken är att skapa en visuell form i en graf
// som visar om det finns någon trend såväl positiv som negativ. En dialogruta med en varning talar om vilken trend som råder. I koden finns en möjlighet
// att ta position eller gå ur position om man vill skapa en startegi kring denna trendindikator. Rekommenderar dock starkt att inte enbart förlita sig på denna
// indikator som beslut för köp/sälj då resultaten blir negativa om man köper på psoitiv trend och säljer på negativ trend. Det måste kombineras med andra idéer
// och därför fungerar denna skript mer som ett komplement till sin egen strategi.
// Det är fritt fram för vem som helst att använda sig av denna indikator.
//@version=4
//Skapar en strategiskript med 1 % av eget kapital som ett exempel. Detta går att ändra i skriptets inställningar, välj egenskaper och sedan ändra orderstorlek
//till ett annat värde av % på eget kapital.
strategy("© Investoz Trend Warning", overlay=true, initial_capital=100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, pyramiding = 0, margin_long = 0.5)
//Lägger till inmatningar till skriptindikatorn. Användaren kan se och redigera inmatningar i objektdialogen efter eget val.
ema1 = input(21, minval=1, maxval=500, title="Lila linje")
valema1=input(true, title="Visa lila linje")
ema2 = input(34, minval=1, maxval=500, title="Blå linje")
valema2=input(true, title="Visa blå linje")
ema3 = input(55, minval=1, maxval=500, title="Grön linje")
valema3=input(true, title="Visa grön linje")
ema4 = input(89, minval=1, maxval=500, title="Gul linje")
valema4=input(true, title="Visa gul linje")
ema5 = input(141, minval=1, maxval=500, title="Orange linje")
valema5=input(true, title="Visa orange linje")
ema6 = input(230, minval=1, maxval=500, title="Röd linje")
valema6=input(true, title="Visa röd linje")
ema7 = input(371, minval=1, maxval=500, title="Röd linje")
valema7=input(true, title="Visa röd linje")
//Inmatningar för antal staplar
startbar = input(1, minval=1, title="First Bar")
Endbar = bar_index + 1
//Källa input, stängning. Användaren kan själv byta till vilken källa som önskas.
src = input(close, title="Source")
//Antal staplar sedan den längsta ema började och framåt.
tid=Endbar + startbar - 1
//EMA
aema1 = ema(src, ema1)
bema2 = ema(src, ema2)
cema3 = ema(src, ema3)
dema4 = ema(src, ema4)
eema5 = ema(src, ema5)
fema6 = ema(src, ema6)
gema7 = ema(src, ema7)
//Skriver ut linjer i diagrammet om förhållandet är sant, annars falskt.
h=plot(valema1 ? aema1 : na, title="Lila linje", style=plot.style_line, linewidth=1, color=#7b9b97)
i=plot(valema2 ? bema2 : na, title="Blå linje", style=plot.style_line, linewidth=1, color=#a2b6b3)
j=plot(valema3 ? cema3 : na, title="Grön linje", style=plot.style_line, linewidth=1, color=#d9e5e3)
k=plot(valema4 ? dema4 : na, title="Gul linje", style=plot.style_line, linewidth=1, color=#ff8383)
l=plot(valema5 ? eema5 : na, title="Orange linje", style=plot.style_line, linewidth=1, color=#dc6262)
m=plot(valema6 ? fema6 : na, title="Röd linje", style=plot.style_line, linewidth=1, color=#b71c1c)
n=plot(valema7 ? gema7 : na, title="Brun linje", style=plot.style_line, linewidth=1, color=color.maroon)
//Fyller bakgrunden mellan två linjer med en viss färg.
fill(h, i, color = color.new(#7b9b97,34))
fill(i, j, color = color.new(#a2b6b3,34))
fill(j, k, color = color.new(#d9e5e3,34))
fill(k, l, color = color.new(#ff8383,34))
fill(l, m, color = color.new(#dc6262,34))
fill(m, n, color = color.new(#b71c1c,34))
//Skapa en algoritm för positiv trend
PositivTrend = crossover(aema1,gema7)?1:0
TrendPositiv = ema(close,1) > aema1 and aema1 > bema2?1:0
//Skapa en algoritm för negativ trend
NegativTrend = crossunder(aema1,gema7)?1:0
TrendNegativ = ema(close,1) < aema1 and aema1 < bema2?1:0
//Skapar en textruta med varningstext för positiv trend
varningtextpositiv = "Positive Trend."+"\n" + "Take position"
if PositivTrend
varningpositiv=label.new(
bar_index,
low,
xloc=xloc.bar_index,
yloc=yloc.price,
color=#7b9b97,
textcolor=color.white,
text=varningtextpositiv,
style=label.style_label_down,
textalign=text.align_left)
//Skapar en textruta med varningstext för negativ trend
varningtextnegativ = "Negative Trend."+"\n" + "Cover the positions"
if NegativTrend
varningnegativ=label.new(
bar_index,
low,
xloc=xloc.bar_index,
yloc=yloc.price,
color=#b71c1c,
textcolor=color.white,
text=varningtextnegativ,
style=label.style_label_up,
textalign=text.align_left)
//Köp om positiv trend
if (PositivTrend)
strategy.entry("Take position", strategy.long, when = PositivTrend)
//Sälj om negativ trend
if (NegativTrend)
strategy.close("Take position", when = NegativTrend, comment="Close position")
//Beräkning av positiv trend
vspositiv(positiv)=>valuewhen(Endbar==startbar,positiv,0)
vepositiv(positiv)=>valuewhen(Endbar==Endbar,positiv,0)
positivmean(TrendPositiv)=>
csumpositiv = cum(TrendPositiv)
//Slut//
a = vepositiv(csumpositiv)
//Start//
b = vspositiv(csumpositiv)
//Slut - Start//
(a - b)/(tid)
positivmeanpositiv = positivmean(TrendPositiv)
//Beräkning av negativ trend
vsnegativ(negativ)=>valuewhen(Endbar==startbar,negativ,0)
venegativ(negativ)=>valuewhen(Endbar==Endbar,negativ,0)
negativmean(TrendNegativ)=>
csumnegativ = cum(TrendNegativ)
//Slut//
a = venegativ(csumnegativ)
//Start//
b = vsnegativ(csumnegativ)
//Slut - Start//
(a - b)/(tid)
negativmeannegativ = negativmean(TrendNegativ)
//Inmatning av text som ska in i texruta som visar antal staplar i trend
logga = "\n"+"© Investoz: Trend Warning"+ "\n"
streck = "==============================================="
totalastaplar = "\n" + "Total number of days: " + tostring(tid)+ " days "+"\n"+ streck + "\n"
totalpositiv = "Total number of days in positive trend "+" 📈 : " +tostring(positivmeanpositiv*tid, "##.##") +" days " + "\n"
totalnegativ = "\n" + "Total number of days in negative trend" + " 📉 : " +tostring(negativmeannegativ*tid, "##.##") +" days " +"\n"
//Textruta för antal staplar i trend
if barstate.ishistory
barcountlbl=label.new(
bar_index,
low,
xloc=xloc.bar_index,
yloc=yloc.price,
color=color.white,
textcolor=color.black,
text=streck+logga+streck+totalastaplar+totalpositiv+streck+totalnegativ+streck,
style=label.style_label_lower_left,
textalign=text.align_left)
label.delete(barcountlbl[1])
////////////////////////////////// |
[CM]EMA Trend Cross STRAT | https://www.tradingview.com/script/BWlt0SeT-CM-EMA-Trend-Cross-STRAT/ | ColinMccann18 | https://www.tradingview.com/u/ColinMccann18/ | 66 | 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/
// © ColinMccann18
//@version=4
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// --------------------------------------------------------------RULES------------------------------------------------------------------------------
// - VISUALLY REPRESENTS THE CROSSING OF 8,13,21,55 EMA'S FROM KROWNS PROGRAM
strategy(title="CM EMA Trend Cross STRAT", shorttitle="CM EMA Strat", overlay=true)
ema8 = ema(close,8)
ema13 = ema(close, 13)
ema21 = ema(close, 21)
ema55 = ema(close, 55)
//PLOT
plot(ema8, title="EMA 1",linewidth=2, color=#00eeff)
plot(ema13, title="EMA 2",linewidth=2, color=#fff900)
plot(ema21, title="EMA 3",linewidth=2, color=#42ff0f)
plot(ema55, title="EMA 4",linewidth=2, color=#8b49ff)
//LOGIC---------------------------------------------------------------------------------------------------------------------------------
emacrossover = crossover(ema21, ema55) and ema8 and ema13 > ema55
emacrossunder = crossunder(ema21, ema55) and ema8 and ema13 < ema55
//Long----------------------------------------------------------------------------------------------------------------------------------
longCondition = emacrossover
closelongCondition = emacrossunder
strategy.entry("Long", strategy.long, qty=na, when=longCondition)
strategy.close("Close Long", when=closelongCondition)
//Short----------------------------------------------------------------------------------------------------------------------------------
shortCondition = emacrossunder
closeshortCondition = emacrossover
strategy.entry("Short", strategy.short,qty=na, when=shortCondition)
strategy.close("Close Short", when=closeshortCondition)
|
Oscilator candles - momentum strategy | https://www.tradingview.com/script/Q338ZUxw-Oscilator-candles-momentum-strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 238 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Oscilator candles - strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
oscilatorType = input(title="Oscliator Type", defval="stoch", options=["rsi", "stoch", "cog", "macd", "tsi", "cci", "cmo", "mfi"])
length = input(100, step=10)
shortlength = input(3)
longlength = input(9)
showSupertrend = input(true)
AtrMAType = input(title="Moving Average Type", defval="rma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])
AtrLength = input(30)
AtrMult = input(4)
wicks = input(true)
colorByPreviousClose = input(true)
// tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
tradeDirection = strategy.direction.long
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Backtest Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "Backtest End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
f_getOscilatorValues(oscilatorType, length, shortlength, longlength)=>
oOpen = rsi(open, length)
oClose = rsi(close, length)
oHigh = rsi(high, length)
oLow = rsi(low, length)
if(oscilatorType == "tsi")
oOpen := tsi(open, shortlength, longlength)
oClose := tsi(close, shortlength, longlength)
oHigh := tsi(high, shortlength, longlength)
oLow := tsi(low, shortlength, longlength)
if(oscilatorType == "stoch")
oOpen := stoch(open, high, low, length)
oClose := stoch(close, high, low, length)
oHigh := stoch(high, high, low, length)
oLow := stoch(low, high, low, length)
if(oscilatorType == "cci")
oOpen := cci(open, length)
oClose := cci(close, length)
oHigh := cci(high, length)
oLow := cci(low, length)
if(oscilatorType == "cog")
oOpen := cog(open, length)
oClose := cog(close, length)
oHigh := cog(high, length)
oLow := cog(low, length)
if(oscilatorType == "cmo")
oOpen := cmo(open, length)
oClose := cmo(close, length)
oHigh := cmo(high, length)
oLow := cmo(low, length)
if(oscilatorType == "mfi")
oOpen := mfi(open, length)
oClose := mfi(close, length)
oHigh := mfi(high, length)
oLow := mfi(low, length)
if(oscilatorType == "macd")
[macdLineOpen, signalLineOpen, histLineOpen] = macd(open, shortlength, longlength, length)
[macdLineClose, signalLineClose, histLineClose] = macd(close, shortlength, longlength, length)
[macdLineHigh, signalLineHigh, histLineHigh] = macd(high, shortlength, longlength, length)
[macdLineLow, signalLineLow, histLineLow] = macd(low, shortlength, longlength, length)
oOpen := macdLineOpen
oClose := macdLineClose
oHigh := macdLineHigh
oLow := macdLineLow
[oOpen, oClose, oHigh, oLow]
f_getMovingAverage(source, MAType, length)=>
ma = sma(source, length)
if(MAType == "ema")
ma := ema(source,length)
if(MAType == "hma")
ma := hma(source,length)
if(MAType == "rma")
ma := rma(source,length)
if(MAType == "vwma")
ma := vwma(source,length)
if(MAType == "wma")
ma := wma(source,length)
ma
f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks)=>
truerange = max(oHigh, oClose[1]) - min(oLow, oClose[1])
averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength)
atr = averagetruerange * AtrMult
longStop = oClose - atr
longStopPrev = nz(longStop[1], longStop)
longStop := (wicks ? oLow[1] : oClose[1]) > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = oClose + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := (wicks ? oHigh[1] : oClose[1]) < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and (wicks ? oHigh : oClose) > shortStopPrev ? 1 : dir == 1 and (wicks ? oLow : oClose) < longStopPrev ? -1 : dir
trailingStop = dir == 1? longStop : shortStop
[dir, trailingStop]
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_off)
f_multiple_resolution(HTFMultiplier) =>
target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 7. * 24. * 60. :
timeframe.ismonthly ? 30.417 * 24. * 60. : na)
target_Res_In_Min <= 0.0417 ? "1S" :
target_Res_In_Min <= 0.167 ? "5S" :
target_Res_In_Min <= 0.376 ? "15S" :
target_Res_In_Min <= 0.751 ? "30S" :
target_Res_In_Min <= 1440 ? tostring(round(target_Res_In_Min)) :
tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"
[oOpen, oClose, oHigh, oLow] = f_getOscilatorValues(oscilatorType, length, shortlength, longlength)
[dir, trailingStop] = f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks)
candleColor = colorByPreviousClose ?
(oClose[1] < oClose ? color.green : oClose[1] > oClose ? color.red : color.silver) :
(oOpen < oClose ? color.green : oOpen > oClose ? color.red : color.silver)
plotcandle(oOpen, oHigh, oLow, oClose, 'Oscilator Candles', color = candleColor)
plot(showSupertrend?trailingStop:na, title="TrailingStop", style=plot.style_linebr, linewidth=1, color= dir == 1 ? color.green : color.red)
buyCondition = dir == 1
exitBuyConditin = dir == -1
sellCondition = dir == -1
exitSellCondition = dir == 1
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca", oca_type=strategy.oca.cancel)
strategy.entry("Sell", strategy.short, when=sellCondition and inDateRange, oca_name="oca", oca_type=strategy.oca.cancel)
strategy.close("Buy", when = exitBuyConditin)
strategy.close( "Sell", when = exitSellCondition) |
The Strategy - Ichimoku Kinko Hyo and more | https://www.tradingview.com/script/DqAYJNZk/ | ramsay09 | https://www.tradingview.com/u/ramsay09/ | 273 | 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/
//@version=5
strategy(title='The Strategy - Ichimoku Kinko Hyo and more', shorttitle='Strategy', overlay=true, initial_capital=10000, pyramiding=1, default_qty_type=strategy.fixed, default_qty_value=0.05, currency=currency.USD,
commission_type=strategy.commission.percent, commission_value=0.075, margin_long=0, margin_short=0)
//-------------------------------------------------------------------- inputs ---------------------------------------------------------------
general_info = input.bool(title='General Description', defval=false,
tooltip='This script offers you the opportunity to backtest many signals and filters to compare the results. Make yourself familiar with the signals and the options and become creative ...
At least you will be able to see what and on what circumstances works or not. Note the \'KISS\' principle and that \'context\' matters.
The key feature of technical analysis is that every market participant is an interface to the world or market-environment and all market relevant information is visible in the chart.
The default values are suitable for Bitcoin on ByBit (one tick = 0.5). Deselect \'Signal Labels\' at strategy properties -> Style to avoid signal label strings.')
entry_type = input.string('Both', title='Position Entry-Direction', options=['Both', 'Long', 'Short'],
tooltip='Long= long entries only, Short= short entries only, Both= long and short entries are possible.')
repaint = input.string('Allowed', title='Repainting', options=['Not allowed', 'Allowed'],
tooltip='If repainting "Not allowed" is selected, then signals from higher time frames have a lag of an additional bar from the higher time frame but you trade what you have backtested.
Otherwise singals can occure multiple times as long as the higher time frame bar is not closed but the first signal of these possible multiple signals is much earlier.')
panel = input.bool(true, title='Plot Info Panel', tooltip='Info panel for current unrealized profit or loss for the open position')
plot_avg_price = input.bool(true, title='Plot Position Avarage Price Line.',
tooltip='This plots the position avarage price line.')
one_side_pyr = input.bool(title='Pyramiding Mode', defval=false,
tooltip='If disabled: as long as the signal is valid a new trade can be opened on each bar (more filter sensitive). If not \'Both\' as direction is selected,
the opposite signal closes the current position. If enabled: a new trade is opened with every signal. Use Properties -> Pyramiding to increase the maximum amount of orders.')
htf_entr_opt_1 = input.string('Current', title='Time Frame - 1st ENTRY SIGNAL', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='entry signals:')
htf_entr_opt_2 = input.string('Current', title='Time Frame - 2nd ENTRY SIGNAL', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='entry signals:')
X_opt = input.string('Price X Kumo sig', title='--- 1st ENTRY SIGNAL ---', options=['---', 'Fractals trend lines sig (no tf filter)', 'Segments sig (no tf filter)',
'DMI ADX classic sig', 'DMI ADX mod sig', 'DMI ADX-slope sig', 'EMA1 x EMA2 sig', 'TRIX slope sig', 'ALMA slope sig', 'MACD(fast) slope sig', 'HMA slope sig',
'Grid - reentry sig (no tf filter)', 'Grid - counter trend sig (no tf filter)', 'Pin bar sig', 'Inside bar sig', 'Outside bar sig', 'Sandwich bar sig', 'Bar breakout 1 sig', 'Bar breakout 2 sig',
'Higher-low/lower-high bar sig', 'Entry on every bar-open sig', 'Fractals sig', 'Reverse fractal sig', 'SMA sig',
'RSI50 sig', 'Parabolic SAR sig', 'SuperTrend sig', 'Price X Kijun sig', 'Price X Kumo sig', 'Kumo flip sig',
'Chikou X price sig', 'Chikou X Kumo sig', 'Price X Tenkan sig', 'Tenkan X Kumo sig', 'Tenkan X Kijun sig', 'CB/CS sig (no tf filter)', 'IB/IS sig (no tf filter)', 'B1/S1 sig', 'B2/S2 sig'],
tooltip='Various entry signals. 1st ENTRY SIGNAL and 2nd ENTRY SIGNAL are OR connected.', group='entry signals:')
X_opt_2 = input.string('---', title='--- 2nd ENTRY SIGNAL --- (Enable Pyramiding Mode)', options=['---', 'Fractals trend lines sig (no tf filter)', 'Segments sig (no tf filter)',
'DMI ADX classic sig', 'DMI ADX mod sig', 'DMI ADX-slope sig', 'EMA1 x EMA2 sig', 'TRIX slope sig', 'ALMA slope sig', 'MACD(fast) slope sig', 'HMA slope sig',
'Grid - reentry sig (no tf filter)', 'Grid - counter trend sig (no tf filter)', 'Pin bar sig', 'Inside bar sig', 'Outside bar sig', 'Sandwich bar sig', 'Bar breakout 1 sig', 'Bar breakout 2 sig',
'Higher-low/lower-high bar sig', 'Entry on every bar-open sig', 'Fractals sig', 'Reverse fractal sig', 'SMA sig',
'RSI50 sig', 'Parabolic SAR sig', 'SuperTrend sig', 'Price X Kijun sig', 'Price X Kumo sig', 'Kumo flip sig',
'Chikou X price sig', 'Chikou X Kumo sig', 'Price X Tenkan sig', 'Tenkan X Kumo sig', 'Tenkan X Kijun sig', 'CB/CS sig (no tf filter)', 'IB/IS sig (no tf filter)', 'B1/S1 sig', 'B2/S2 sig'],
tooltip='Various entry signals. Signal 1 and signal 2 are OR connected. Works with pyramiding mode only', group='entry signals:')
htf_filt_opt_1 = input.string('Current', title='Time Frame - Entry Filter 1', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='The time frame for the 1st ENTRY SIGNAL filter. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Entry filters:')
htf_filt_opt_2 = input.string('Current', title='Time Frame - Entry Filter 2', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='The time frame for the 2st ENTRY SIGNAL filter. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Entry filters:')
entry_f_1 = input.string('---', title='Entry Filter 1', options=['---', 'Fractals trend lines filter (no tf filter)', 'Bar breakout 1 filter', 'Bar breakout 2 filter', 'SMA filter', 'MACD filter',
'EMA1 x EMA2 filter', 'RSI Stochastic filter', 'TRIX slope filter', 'ALMA slope filter','HMA slope filter',
'MACD(fast) slope filter', 'RSI50 filter', 'Segments filter (no tf filter)', 'Reverse fractal filter', 'Fractals filter',
'SuperTrend filter', 'Parabolic SAR filter', 'ADX Threshold filter', 'DMI filter', 'Price X Kumo filter', 'Price X Kijun filter', 'Kumo flip filter', 'Price filtered Kumo flip filter (no tf filter)',
'Chikou X price filter', 'Chikou X Kumo filter', 'Price X Tenkan filter', 'Tenkan X Kumo filter', 'Tenkan X Kijun filter', 'B1/S1 sig', 'B2/S2 sig', 'IB/IS sig (no tf filter)'], group='Entry filters:',
tooltip='Various entry filter signals. Entry filter 1 and Entry filter 2 are AND connected.')
entry_f_2 = input.string('---', title='Entry Filter 2', options=['---', 'Fractals trend lines filter (no tf filter)', 'Bar breakout 1 filter', 'Bar breakout 2 filter', 'SMA filter', 'MACD filter',
'EMA1 x EMA2 filter', 'RSI Stochastic filter', 'TRIX slope filter', 'ALMA slope filter','HMA slope filter',
'MACD(fast) slope filter', 'RSI50 filter', 'Segments filter (no tf filter)', 'Reverse fractal filter', 'Fractals filter',
'SuperTrend filter', 'Parabolic SAR filter', 'ADX Threshold filter', 'DMI filter', 'Price X Kumo filter', 'Price X Kijun filter', 'Kumo flip filter', 'Price filtered Kumo flip filter (no tf filter)',
'Chikou X price filter', 'Chikou X Kumo filter', 'Price X Tenkan filter', 'Tenkan X Kumo filter', 'Tenkan X Kijun filter', 'B1/S1 sig', 'B2/S2 sig', 'IB/IS sig (no tf filter)'], group='Entry filters:',
tooltip='Various entry filter signals. Filter 1 and filter 2 are AND connected.')
htf_exit_opt_1 = input.string('Current', title='Time Frame - Exit Filter 1', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='exit filters:')
htf_exit_opt_2 = input.string('Current', title='Time Frame - Exit Filter 2', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '12H', 'D', '3D', 'W', 'M'],
tooltip='Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='exit filters:')
exit_f_1 = input.string('---', title='Exit Filter 1', options=['---', 'Reverse bar exit', 'Reverse fractal exit', 'Bar breakout 2 exit', 'SMA exit', 'MACD exit', 'MACD(fast) slope exit', 'RSI50 exit',
'RSI Stochastic exit', 'TRIX slope exit',
'HMA slope exit', 'EMA1 x EMA2 exit', 'Fractals exit', 'SuperTrend exit', 'Parabolic SAR exit', 'ADX Threshold exit', 'Cloud exit', 'Kijun exit', 'IB/IS exit (no tf filter)'], group='exit filters:',
tooltip='Some exit filter signals. Exit filter 1 and Exit filter 2 are OR connected.')
exit_f_2 = input.string('---', title='Exit Filter 2', options=['---', 'Reverse bar exit', 'Reverse fractal exit', 'Bar breakout 2 exit', 'SMA exit', 'MACD exit', 'MACD(fast) slope exit', 'RSI50 exit',
'RSI Stochastic exit', 'TRIX slope exit',
'HMA slope exit', 'EMA1 x EMA2 exit', 'Fractals exit', 'SuperTrend exit', 'Parabolic SAR exit', 'ADX Threshold exit', 'Cloud exit', 'Kijun exit', 'IB/IS exit (no tf filter)'], group='exit filters:',
tooltip='Some exit filter signals. Exit filter 1 and Exit filter 2 are OR connected.')
//------------------------ lot size for live trading --------------------------
//Alertatron lot size on Bybit
lot_size = input.int(300, title='Lot Size', minval=1, step=100,
tooltip='Alertatron lot size string for Bybit exchange. Affects live trading only.', group='Live trading Parameter (does not affect backtesting):')
grid_gap = input.float(500, title='Grid Gap - Base Currency', minval=1, step=50, group='Grid parameter:', tooltip='The minimum trigger-gap between two trades in case of a selected grid signal.')
//------------------------ Backtest periode inputs ----------------------------
period_start = input.time(title='', inline='start_timestamp', defval=timestamp('13 Mar 2020 00:00 +0000'), group='Define the backtest period or start of trend:', tooltip='Backtest period start.')
period_stop = input.time(title='', inline='end_timestamp', defval=timestamp('31 Dec 2120 00:00 +0000'), group='Define the backtest period or start of trend:', tooltip='Backtest period end.')
//---------------------- take profit inputs -----------------------------
av_tp_en = input.bool(title='Enable take Profit - Average Position Price Profit', defval=true, group='Take profit based on average position price:', tooltip='Profit taking condition:
current price >= average position price of positions + ATR')
av_tp_qty = input.float(10, title='Take Average Position Price Profit - Quantity Of Position (Percent)', minval=1, step=5, maxval=100, group='Take profit based on average position price:',
tooltip='Reduction of the current position in percent.')
atr_l = input.int(50, title='ATR Length', minval=0, step=5, group='Take profit based on average position price:',
tooltip='ATR length for profit and step calculation')
atr_tf = input.string('W', title='ATR Time Frame', options=['60', '120', '240', '480', '960', 'D', '3D', 'W', 'M'], group='Take profit based on average position price:',
tooltip='ATR time frame for profit and step calculation')
atr_fact = input.float(1, title='ATR Factor', minval=0, step=0.1, group='Take profit based on average position price:',
tooltip='ATR factor to increase/decrease ATR for profit and step calculation')
//---------------------- stop loss inputs --------------------------
sl_en = input.bool(title='Enable Stop Loss - Average Position Price Loss', defval=true, group='Stop loss based on average position price:',
tooltip='Stop loss condition: current price <= average position price of positions - \'Stop average-entry loss...\' AND current price <= average position price of positions -
\'Stop loss step...\'')
av_sl_qty = input.float(50, title='Stop Average Position Price Loss - Quantity Of Position (Percent)', minval=0, step=5, maxval=100, group='Stop loss based on average position price:',
tooltip='Reduction of the current position in percent.')
atr_l_l = input.int(50, title='ATR Length', minval=0, step=5, group='Stop loss based on average position price:', tooltip='ATR length for loss and step calculation')
atr_tf_l = input.string('W', title='ATR Time Frame', options=['60', '120', '240', '480', '960', 'D', '3D', 'W', 'M'], group='Stop loss based on average position price:',
tooltip='ATR time frame for loss and step calculation')
atr_fact_l = input.float(1, title='ATR Factor', minval=0, step=0.1, group='Stop loss based on average position price:', tooltip='ATR factor to increase/decrease ATR for loss and step calculation')
//------------------------ Signal inputs CB/CS and IB/IS ---------------------------
trig_gap_cbcs = input.float(2, title='CB/CS Signal Offset', minval=-6, maxval=9, step=1, group='Confluence signal offsets:', tooltip='Decreasing this parameter increases the sensitivity of the signal.')
trig_gap_ibis = input.float(0, title='IB/IS Signal Offset', minval=-5, maxval=4, step=1, group='Confluence signal offsets:', tooltip='Decreasing this parameter increases the sensitivity of the signal.')
//----------------------- entry signals and filters -----------------------
sb = input.int(10, title='Segment Max Bars', minval=0, step=1, group='Shared filter and entry signal parameters:')
p_bar_sens_1 = input.float(0.6, title='Pin Bar Sensitivity 1', step=0.02, tooltip='Condition: candle wick > candle body * \'Pin bar sensitivity\' .
The smaller the factor, the more wicks are detected as part of a pin bar.', group='Shared filter and entry signal parameters:')
p_bar_sens_2 = input.int(1, title='Pin Bar Sensitivity 2', step=1, minval=1, tooltip='Condition: high/low >< last two high/low\'.', group='Shared filter and entry signal parameters:')
fr_period = input.int(2, title='Fractals Period', minval=1, group='Shared filter and entry signal parameters:')
rsi_period = input.int(14, title='RSI Period', minval=1, group='Shared filter and entry signal parameters:')
ma_period = input.int(50, title='SMA Period', minval=1, step=5, group='Shared filter and entry signal parameters:')
mult = input.float(3, title='SuperTrend Multiplier', minval=1, step=0.2, group='Shared filter and entry signal parameters:')
len = input.int(6, title='SuperTrend Length', minval=1, group='Shared filter and entry signal parameters:')
start = 0.02 //input(0.02, title= "PSAR Start (Filter/Entry)", minval= 0)
inc = 0.02 //input(0.02, title= "PSAR Increment (Filter/Entry)", minval= 0)
max = 0.2 //input(.2, title= "PSAR Maximum (Filter/Entry)", minval= 0)
di_length_s = input.int(10, title='ADX DI Length', minval=1, group='Shared filter and entry signal parameters:')
adx_smooth_s = input.int(10, title='ADX Smooth', minval=1, group='Shared filter and entry signal parameters:')
adx_thres_s = input.int(25, title='ADX Threshold', step=2, minval=1, group='Shared filter and entry signal parameters:')
windowsize = input.int(9, title="ALMA Window Size", minval=1, step=1, group='Shared filter and entry signal parameters:', tooltip='')
offset = input.float(0.85, title="ALMA Offset", minval=0, step=0.05, group='Shared filter and entry signal parameters:', tooltip='')
sigma = input.float(6, title="ALMA Sigma", minval=1, step=1, group='Shared filter and entry signal parameters:', tooltip='')
slope_len = input.int(1, minval=1, title='MACD MacdlLine Slope Lenth', tooltip='MACD\'s fast line', group='Shared filter and entry signal parameters:')
hma_len_f = input.int(100, minval=1, step=5, title='HMA Length', group='Shared filter and entry signal parameters:')
ema1_len_f = input.int(10, minval=1, step=2, title='EMA1 Length', group='Shared filter and entry signal parameters:')
ema2_len_f = input.int(20, minval=1, step=2, title='EMA2 Length', group='Shared filter and entry signal parameters:')
k_smoo_f = input.int(3, title='RSI-Stoch K-line', minval=1, tooltip='RSI Stochastic\'s fast line', group='Shared filter and entry signal parameters:')
d_smoo_f = input.int(3, title='RSI-Stoch D-line', minval=1, tooltip='RSI Stochastic\'s slow line', group='Shared filter and entry signal parameters:')
stoch_length_f = input.int(14, title='RSI-Stoch Stochastic Length', minval=1, group='Shared filter and entry signal parameters:')
rsi_length_sto_f = input.int(14, title='RSI-Stoch RSI Length', minval=1, group='Shared filter and entry signal parameters:')
trix_len_f = input.int(10, title="TRIX Length", minval=1, group='Shared filter and entry signal parameters:')
// exit filters
fr_period_x = input.int(2, title='Exit Fractals - Period', minval=1, group='Exit filter Parameters:')
fr_past_x = input.int(0, title='Exit Fractals - Past Fractal', minval=0, group='Exit filter Parameters:')
rsi_period_x = input.int(14, title='Exit RSI Period', minval=1, group='Exit filter Parameters:')
ma_period_x = input.int(50, title='Exit SMA Period', step=5, minval=1, group='Exit filter Parameters:')
mult_x = input.float(2, title='Exit SuperTrend Multiplier', minval=1, group='Exit filter Parameters:')
len_x = input.int(5, title='Exit SuperTrend Length', minval=1, group='Exit filter Parameters:')
di_length_x = input.int(10, title='Exit ADX Period', minval=1, group='Exit filter Parameters:')
adx_smooth_x = input.int(10, title='Exit ADX Smooth', minval=1, group='Exit filter Parameters:')
adx_thres_x = input.int(25, title='Exit ADX Threshold', step=2, minval=1, group='Exit filter Parameters:')
slope_len_x = input.int(1, title='Exit MACD MacdlLine Slope Lenth', minval=1, tooltip='MACD\'s fast line', group='Exit filter Parameters:')
hma_len_x = input.int(100, minval=1, step=5, title='Exit HMA Length', group='Exit filter Parameters:')
ema1_len_x = input.int(10, title='Exit EMA1 Length', minval=1, step=2, group='Exit filter Parameters:')
ema2_len_x = input.int(20, title='Exit EMA2 Length', minval=1, step=2, group='Exit filter Parameters:')
k_smoo_x = input.int(3, title='Exit RSI-Stoch K-line', minval=1, tooltip='RSI Stochastic\'s fast line', group='Exit filter Parameters:')
d_smoo_x = input.int(3, title='Exit RSI-Stoch D-line', minval=1, tooltip='RSI Stochastic\'s slow line', group='Exit filter Parameters:')
stoch_length_x = input.int(14, title='Exit RSI-Stoch Stochastic Length', minval=1, group='Exit filter Parameters:')
rsi_length_sto_x = input.int(14, title='Exit RSI-Stoch RSI Length', minval=1, group='Exit filter Parameters:')
trix_len_x = input.int(10, title="Exit TRIX Length", minval=1, group='Exit filter Parameters:')
//--------------- Current unrealized profit or loss for the open position -------------------
if panel
var info_panel = table.new(position = position.bottom_left, columns = 1, rows = 1, bgcolor=color.new(color.blue, 92), frame_width=1, border_width=1)
text1 = "Unrealized Profit/Loss:\n" + str.tostring(strategy.openprofit, "#.00")
table.cell(table_id=info_panel, column=0, row=0, text=text1, text_size= size.normal, text_color=color.new(color.silver, 0))
//----------------------- Backtest periode --------------------------------
backtest_period() =>
time >= period_start and time <= period_stop ? true : false
//-------------------- Ichimoku --------------------
TKlength = 9 //input(9, "Tenkan-sen length", minval= 1)
KJlength = 26 //input(26, "Kijun-sen length", minval= 1)
CSHSlength = 26 //input(26, "Chikouspan length/horizontal shift", minval= 1)
SBlength = 52 //input(52, "SenkouspanB length", minval= 1)
SAlength = 26 //input(26, "SenkouspanA length", minval= 1)
// calculation
TK = math.avg(ta.lowest(TKlength), ta.highest(TKlength))
KJ = math.avg(ta.lowest(KJlength), ta.highest(KJlength))
CS = close
SB = math.avg(ta.lowest(SBlength), ta.highest(SBlength))
SA = math.avg(TK, KJ)
kumo_high = math.max(SA[CSHSlength - 1], SB[CSHSlength - 1])
kumo_low = math.min(SA[CSHSlength - 1], SB[CSHSlength - 1])
//--------------------------------------------------------------------------------- Filters and entry signals -----------------------------------------------------------------------------------
//---------------------- Ichimoku filter ------------------------
var bool tkkj_x = true
if ta.crossover(TK, KJ) and TK > kumo_high and KJ > kumo_high
tkkj_x := true
tkkj_x
if ta.crossunder(TK, KJ) and TK < kumo_low and KJ < kumo_low
tkkj_x := false
tkkj_x
//Ichimoku entry signals
kijun_buy = one_side_pyr ? ta.crossover(close, KJ) : close > KJ
kumo_buy = one_side_pyr ? ta.crossover(close, kumo_high) : close > kumo_high
kumo_flip_buy = one_side_pyr ? ta.crossover(SA, SB) : SA > SB
chikou_X_price_buy = one_side_pyr ? ta.crossover(CS, high[26 - 1]) : CS > high[26 - 1]
chikou_X_kumo_buy = one_side_pyr ? ta.crossover(CS, kumo_high[26 - 1]) : CS > kumo_high[26 - 1]
price_X_tenkan_buy = one_side_pyr ? ta.crossover(close, TK) : close > TK
tenkan_X_kumo_buy = one_side_pyr ? ta.crossover(TK, kumo_high) : TK > kumo_high
tenkan_X_kijun_buy = one_side_pyr ? ta.crossover(TK, KJ) : TK > KJ
kijun_sell = one_side_pyr ? ta.crossunder(close, KJ) : close < KJ
kumo_sell = one_side_pyr ? ta.crossunder(close, kumo_low) : close < kumo_low
kumo_flip_sell = one_side_pyr ? ta.crossunder(SA, SB) : SA < SB
chikou_X_price_sell = one_side_pyr ? ta.crossunder(CS, low[26 - 1]) : CS < low[26 - 1]
chikou_X_kumo_sell = one_side_pyr ? ta.crossunder(CS, kumo_low[26 - 1]) : CS < kumo_low[26 - 1]
price_X_tenkan_sell = one_side_pyr ? ta.crossunder(close, TK) : close < TK
tenkan_X_kumo_sell = one_side_pyr ? ta.crossunder(TK, kumo_low) : TK < kumo_low
tenkan_X_kijun_sell = one_side_pyr ? ta.crossunder(TK, KJ) : TK < KJ
// Ichimoku filters
kijun_buy_f = close > KJ
kumo_buy_f = close > kumo_high
kumo_flip_buy_f = SA > SB
chikou_X_price_buy_f = CS > high[26 - 1]
chikou_X_kumo_buy_f = CS > kumo_high[26 - 1]
price_X_tenkan_buy_f = close > TK
tenkan_X_kumo_buy_f = TK > kumo_high
tenkan_X_kijun_buy_f = TK > KJ
kumo_filtered_tenkan_X_kijun_buy_f = tkkj_x and TK > kumo_high and KJ > kumo_high and TK > KJ
kijun_sell_f = close < KJ
kumo_sell_f = close < kumo_low
kumo_flip_sell_f = SA < SB
chikou_X_price_sell_f = CS < low[26 - 1]
chikou_X_kumo_sell_f = CS < kumo_low[26 - 1]
price_X_tenkan_sell_f = close < TK
tenkan_X_kumo_sell_f = TK < kumo_low
tenkan_X_kijun_sell_f = TK < KJ
kumo_filtered_tenkan_X_kijun_sell_f = not tkkj_x and TK < kumo_low and KJ < kumo_low and TK < KJ
// Ichimoku exits
kijun_buy_x = ta.crossover(high, KJ)
kijun_sell_x = ta.crossunder(low, KJ)
kumo_buy_x = ta.crossover(high, kumo_high)
kumo_sell_x = ta.crossunder(low, kumo_low)
//----------------------- bar signals -----------------------
//entry signal
bar_sig_1_buy = close > high[1] // bar breakout signal 1
bar_sig_1_sell = close < low[1]
//filter
bar_sig_1_buy_f = close > high[1] // bar breakout signal 1 - filter
bar_sig_1_sell_f = close < low[1]
//entry
bar_sig_2_buy = high > high[1] // bar breakout signal 2
bar_sig_2_sell = low < low[1]
//filter
bar_sig_2_buy_f = high > high[1] // bar breakout signal 2 - filter
bar_sig_2_sell_f = low < low[1]
rev_bar_sig_buy = close > open // reverse bar exit
rev_bar_sig_sell = close < open
hllh_buy = low > low[1] // higher-low/lower-high bar sig
hllh_sell = high < high[1]
open_buy = close != 0 // entry on every open bar sig
open_sell = close != 0
//-------------------------- trix --------------------------
f_trix(_trix_len) => 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(close), _trix_len), _trix_len), _trix_len))
trix_f = f_trix(trix_len_f)
trix_x = f_trix(trix_len_x)
trix_buy_s = ta.rising(trix_f, 1) and not ta.rising(trix_f, 1)[1] //one_side_pyr ? ta.rising(trix_f, 1) and not ta.rising(trix_f, 1)[1] : ta.rising(trix_f, 1)
trix_sell_s = ta.falling(trix_f, 1) and not ta.falling(trix_f, 1)[1] //one_side_pyr ? ta.falling(trix_f, 1) and not ta.falling(trix_f, 1)[1] : ta.falling(trix_f, 1)
trix_slo_up_f = ta.rising(trix_f, 1)
trix_slo_up_x = ta.rising(trix_x, 1) and not ta.rising(trix_x, 1)[1]
trix_slo_dn_x = ta.falling(trix_x, 1) and not ta.falling(trix_x, 1)[1]
//----------------------- rsi stochastic ----------------------------
//filter
rsi_rs_f = ta.rsi(close, rsi_length_sto_f)
k_f = ta.sma(ta.stoch(rsi_rs_f, rsi_rs_f, rsi_rs_f, stoch_length_f), k_smoo_f)
d_f = ta.sma(k_f, d_smoo_f)
//signal
kd_mom_up_f = k_f > 20 and d_f > 20 and not(k_f < d_f and k_f < 80 and d_f < 80)
kd_mom_dn_f = k_f < 80 and d_f < 80 and not(k_f > d_f and k_f > 80 and d_f > 80)
//exit
rsi_rs_x = ta.rsi(close, rsi_length_sto_x)
k_x = ta.sma(ta.stoch(rsi_rs_x, rsi_rs_x, rsi_rs_x, stoch_length_x), k_smoo_x)
d_x = ta.sma(k_x, d_smoo_x)
//signal
kd_mom_up_x = k_x > 20 and d_x > 20 and not(k_x < d_x and k_x < 80 and d_x < 80)
kd_mom_dn_x = k_x < 80 and d_x < 80 and not(k_x > d_x and k_x > 80 and d_x > 80)
//------------------------- hma ----------------------------
f_hma(_hma_len) => ta.hma(close, _hma_len)
hma_f = f_hma(hma_len_f) // entry filter
hma_x = f_hma(hma_len_x) // exit
hma_up_e = ta.rising(hma_f, 1) and not ta.rising(hma_f, 1)[1] //one_side_pyr ? ta.rising(hma_f, 1) and not ta.rising(hma_f, 1)[1] : ta.rising(hma_f, 1) // entry signal
hma_dn_e = ta.falling(hma_f, 1) and not ta.falling(hma_f, 1)[1] //one_side_pyr ? ta.falling(hma_f, 1) and not ta.falling(hma_f, 1)[1] : ta.falling(hma_f, 1)
hma_up_f = ta.rising(hma_f, 1) // entry filter
hma_up_x = ta.rising(hma_x, 1) and not ta.rising(hma_x, 1)[1] // exit
hma_dn_x = ta.falling(hma_x, 1) and not ta.falling(hma_x, 1)[1]
//------------------------ grid --------------------------
re_grid = 0.
re_grid := nz(high > re_grid[1] + grid_gap or low < re_grid[1] - grid_gap ? close : re_grid[1])
grid_ct_buy = re_grid < re_grid[1]
grid_ct_sell = re_grid > re_grid[1]
grid_re_buy = re_grid > re_grid[1]
grid_re_sell = re_grid < re_grid[1]
//plot(re_grid,"Plot", color= color.yellow, linewidth= 2)
//---------------------- reverse fractal signal and filter --------------------------
up_bar = close[0] > open[0]
dn_bar = close[0] < open[0]
hl = low[0] > low[1]
lh = high[0] < high[1]
rev_up_fr_sell = ta.pivothigh(high, 3, 0) and dn_bar and up_bar[1] or ta.pivothigh(high, 4, 1) and dn_bar and up_bar[1] or ta.pivothigh(high, 4, 1) and lh and up_bar and up_bar[1]
rev_dn_fr_buy = ta.pivotlow(low, 3, 0) and up_bar and dn_bar[1] or ta.pivotlow(low, 4, 1) and up_bar and dn_bar[1] or ta.pivotlow(low, 4, 1) and hl and dn_bar and dn_bar[1]
//------------------------- ema1 x ema2 ------------------------
f_ema(_ema_len) => ta.ema(close, _ema_len) // ma function definition
f_sma(_sma_len) => ta.sma(close, _sma_len) // ma function definition
ema1_f = f_ema(ema1_len_f)
ema2_f = f_ema(ema2_len_f)
ema1_x = f_ema(ema1_len_x)
ema2_x = f_ema(ema2_len_x)
ema_1x2_buy_s = ta.crossover(ema1_f, ema2_f)
ema_1x2_sell_s = ta.crossunder(ema1_f, ema2_f)
ema_1x2_buy_f = ema1_f > ema2_f
ema_1x2_buy_x = ta.crossover(ema1_x, ema2_x)
ema_1x2_sell_x = ta.crossunder(ema1_x, ema2_x)
//--------------------- ALMA ------------------------
alma = ta.alma(close, windowsize, offset, sigma)
//entry signals
alma_slo_up_e = ta.rising(alma, 1) and not ta.rising(alma, 1)[1] //one_side_pyr ? ta.rising(alma, 1) and not ta.rising(alma, 1)[1] : ta.rising(alma, 1)
alma_slo_dn_e = ta.falling(alma, 1) and not ta.falling(alma, 1)[1] //one_side_pyr ? ta.falling(alma, 1) and not ta.falling(alma, 1)[1] : ta.falling(alma, 1)
//filters
alma_slo_up_f = ta.rising(alma, 1)
//----------------------- macd filter and macd slope-----------------------
[macdLine_f, signalLine_f, histLine_f] = ta.macd(close, 12, 26, 9)
//filters
macd_buy = macdLine_f > signalLine_f
macd_sell = macdLine_f < signalLine_f
//exit
macd_buy_x = ta.crossover(macdLine_f, signalLine_f)
macd_sell_x = ta.crossunder(macdLine_f, signalLine_f)
//macd fast line slope
macd_slope_up_e = ta.rising(macdLine_f, slope_len) and not ta.rising(macdLine_f, slope_len)[1]
//one_side_pyr ? ta.rising(macdLine_f, slope_len) and not ta.rising(macdLine_f, slope_len)[1] : ta.rising(macdLine_f, slope_len) // entry
macd_slope_dn_e = ta.falling(macdLine_f, slope_len) and not ta.falling(macdLine_f, slope_len)[1]
//one_side_pyr ? ta.falling(macdLine_f, slope_len) and not ta.falling(macdLine_f, slope_len)[1] : ta.falling(macdLine_f, slope_len)
macd_slope_up_f = ta.rising(macdLine_f, slope_len) // filter
macd_slope_up_x = ta.rising(macdLine_f, slope_len_x) and not ta.rising(macdLine_f, slope_len_x)[1] // exit
macd_slope_dn_x = ta.falling(macdLine_f, slope_len_x) and not ta.falling(macdLine_f, slope_len_x)[1]
//---------------------- rsi filter and entry signal------------------------
f_rsi(_rsi_period) => ta.rsi(close, _rsi_period)
//entry
rsi_f = f_rsi(rsi_period)
rsi_f_buy = one_side_pyr ? ta.crossover(rsi_f, 50) : rsi_f > 50
rsi_f_sell = one_side_pyr ? ta.crossunder(rsi_f, 50) : rsi_f < 50
//filters
rsi_f_buy_f = rsi_f > 50
rsi_f_sell_f = rsi_f < 50
//exit
rsi_f_x = f_rsi(rsi_period_x)
rsi_f_buy_x = ta.crossover(rsi_f_x, 50)
rsi_f_sell_x = ta.crossunder(rsi_f_x, 50)
//---------------- Bill Williams Fractals (filter and entry signal) -----------------
up_fr = ta.pivothigh(fr_period, fr_period)
dn_fr = ta.pivotlow(fr_period, fr_period)
fractal_up_v = ta.valuewhen(up_fr, high[fr_period], 0)
fractal_dn_v = ta.valuewhen(dn_fr, low[fr_period], 0)
//entry signal
fr_upx = one_side_pyr ? ta.crossover(high, fractal_up_v) : high > fractal_up_v
fr_dnx = one_side_pyr ? ta.crossunder(low, fractal_dn_v) : low < fractal_dn_v
//filters
fr_upx_f = high > fractal_up_v
fr_dnx_f = low < fractal_dn_v
//exit
up_fr_x = ta.pivothigh(fr_period_x, fr_period_x)
dn_fr_x = ta.pivotlow(fr_period_x, fr_period_x)
fractal_up_v_x = ta.valuewhen(up_fr_x, high[fr_period_x], fr_past_x)
fractal_dn_v_x = ta.valuewhen(dn_fr_x, low[fr_period_x], fr_past_x)
fr_upx_x = ta.crossover(high, fractal_up_v_x)
fr_dnx_x = ta.crossunder(low, fractal_dn_v_x)
//-------------------- SuperTrend filter and entry signal ---------------------
//entry
[SuperTrend, Dir] = ta.supertrend(mult, len)
sup_buy = one_side_pyr ? ta.crossover(high, SuperTrend) : high > SuperTrend
sup_sell = one_side_pyr ? ta.crossunder(low, SuperTrend) : low < SuperTrend
//filters
sup_buy_f = high > SuperTrend
sup_sell_f = low < SuperTrend
//exit
[SuperTrend_x, Dir_x] = ta.supertrend(mult_x, len_x)
sup_buy_x = ta.crossover(high, SuperTrend_x)
sup_sell_x = ta.crossunder(low, SuperTrend_x)
//----------------- Parabolic SAR Signal (pb/ps) and filter -------------------
psar_buy = one_side_pyr ? ta.crossover(high, ta.sar(start, inc, max)[0]) : high > ta.sar(start, inc, max)[0]
psar_sell = one_side_pyr ? ta.crossunder(low, ta.sar(start, inc, max)[0]) : low < ta.sar(start, inc, max)[0]
//filters
psar_buy_f = high > ta.sar(start, inc, max)[0]
psar_sell_f = low < ta.sar(start, inc, max)[0]
psar_buy_x = ta.crossover(high, ta.sar(start, inc, max)[0])
psar_sell_x = ta.crossunder(low, ta.sar(start, inc, max)[0])
//-------------------------- DMI ADX entry sig and filter ---------------------------
//exit
[diplus_f_x, diminus_f_X, adx_f_x] = ta.dmi(di_length_x, adx_smooth_x)
adx_thres_f_x = ta.crossunder(adx_f_x, adx_thres_x)
//dmi and adx signal 1/2/3 and filters
[diplus_s, diminus_s, adx_s] = ta.dmi(di_length_s, adx_smooth_s)
adx_above_thres = adx_s > adx_thres_s
adx_slope_up = ta.rising(adx_s, 1)
//entry filter
long_e = diplus_s > diminus_s
short_e = diplus_s < diminus_s
//entry
long_1 = one_side_pyr ? ta.crossover(diplus_s, diminus_s) and adx_s < diplus_s and adx_s > diminus_s : diplus_s > diminus_s and adx_s < diplus_s and adx_s > diminus_s
short_1 = one_side_pyr ? ta.crossunder(diplus_s, diminus_s) and adx_s > diplus_s and adx_s < diminus_s : diplus_s < diminus_s and adx_s > diplus_s and adx_s < diminus_s
long_2 = one_side_pyr ? ta.crossover(diplus_s, diminus_s) and adx_s > adx_thres_s : diplus_s > diminus_s and adx_above_thres
short_2 = one_side_pyr ? ta.crossunder(diplus_s, diminus_s) and adx_s > adx_thres_s : diplus_s < diminus_s and adx_above_thres
//dmi adx-slope signal
adx_up_c = adx_slope_up and diplus_s > diminus_s and not (adx_slope_up and diplus_s > diminus_s)[1]
adx_dn_c = adx_slope_up and diplus_s < diminus_s and not (adx_slope_up and diplus_s < diminus_s)[1]
//-------------------------- SMA50 filter and entry---------------------------
//entry
sma_buy = one_side_pyr ? ta.crossover(close[1], f_sma(ma_period)) : close[2] > f_sma(ma_period)
sma_sell = one_side_pyr ? ta.crossunder(close[1], f_sma(ma_period)) : close[2] < f_sma(ma_period)
//filters
sma_buy_f = close[2] > f_sma(ma_period)
sma_sell_f = close[2] < f_sma(ma_period)
//exit
sma_buy_x = ta.crossover(close[1], f_sma(ma_period_x))
sma_sell_x = ta.crossunder(close[1], f_sma(ma_period_x))
//---------------- williams fractals trend lines -----------------
up_w_fr = ta.pivothigh(2, 2)
dn_w_fr = ta.pivotlow(2, 2)
y1_frup_1 = ta.valuewhen(up_w_fr, high[2], 1)
y0_frup_0 = ta.valuewhen(up_w_fr, high[2], 0)
y1_frdn_1 = ta.valuewhen(dn_w_fr, low[2], 1)
y0_frdn_0 = ta.valuewhen(dn_w_fr, low[2], 0)
// bar-id loops to get x1 and x2 for line.new()
xup0 = 2
for i = 1 to 35 by 1
if high[i + 2] >= high[i + 3] and high[i + 2] > high[i + 4] and high[i + 2] > high[i + 1] and high[i + 2] >= high[i + 0]
break
xup0 := xup0 + 1
xup0
xup1 = xup0
for i = xup1 to 50 by 1
if high[i + 2] >= high[i + 3] and high[i + 2] > high[i + 4] and high[i + 2] > high[i + 1] and high[i + 2] >= high[i + 0]
break
xup1 := xup1 + 1
xup1
xdn0 = 2
for i = 1 to 35 by 1
if low[i + 2] <= low[i + 3] and low[i + 2] < low[i + 4] and low[i + 2] < low[i + 1] and low[i + 2] <= low[i + 0]
break
xdn0 := xdn0 + 1
xdn0
xdn1 = xdn0
for i = xdn1 to 50 by 1
if low[i + 2] <= low[i + 3] and low[i + 2] < low[i + 4] and low[i + 2] < low[i + 1] and low[i + 2] <= low[i + 0]
break
xdn1 := xdn1 + 1
xdn1
// y-linebreak values for upper_line and lower_line
y_up_lvl = (y0_frup_0 - y1_frup_1) / (xup1 + 2 - xup0) * xup0 + y0_frup_0 // y = slope * x0 + y0
y_dn_lvl = (y0_frdn_0 - y1_frdn_1) / (xdn1 + 2 - xdn0) * xdn0 + y0_frdn_0
// entry
//frup_buy = ta.crossover(high, y0_frup_0)
//frdn_sell = ta.crossunder(low, y0_frdn_0)
buy_up_line = one_side_pyr ? ta.crossover(high, y_up_lvl) : high > y_up_lvl// or frup_buy
sell_dn_line = one_side_pyr ? ta.crossunder(low, y_dn_lvl) : low < y_dn_lvl// or frdn_sell
//--------------------------- Segments signal ----------------------------
count1_l = 0
count2_l = 0
segment_1_stat_l = false
segment_2_stat_l = false
segment_3_stat_l = false
higher_low = low > low[1]
var line segment_low_1_l = na
var line segment_low_2_l = na
var line segment_low_3_l = na
// long segments
for i = 0 to sb by 1
count1_l := count1_l + 1
if low[1] > low[i + 2] and higher_low
segment_1_stat_l := true
break
for i = count1_l to sb + count1_l by 1
count2_l := count2_l + 1
if low[1 + count1_l] > low[i + 2] and segment_1_stat_l
segment_2_stat_l := true
break
for i = count2_l to sb + count2_l by 1
if low[1 + count1_l + count2_l] > low[i + 2 + count1_l] and segment_2_stat_l
segment_3_stat_l := true
break
// short segments
count1_s = 0
count2_s = 0
segment_1_stat_s = false
segment_2_stat_s = false
segment_3_stat_s = false
lower_high = high < high[1]
var line segment_high_1 = na
var line segment_high_2 = na
var line segment_high_3 = na
for i = 0 to sb by 1
count1_s := count1_s + 1
if high[1] < high[i + 2] and lower_high
segment_1_stat_s := true
break
for i = count1_s to sb + count1_s by 1
count2_s := count2_s + 1
if high[1 + count1_s] < high[i + 2] and segment_1_stat_s
segment_2_stat_s := true
break
for i = count2_s to sb + count2_s by 1
if high[1 + count1_s + count2_s] < high[i + 2 + count1_s] and segment_2_stat_s
segment_3_stat_s := true
break
// segments signals
seg_stat_l = segment_1_stat_l and segment_2_stat_l and segment_3_stat_l
seg_stat_s = segment_1_stat_s and segment_2_stat_s and segment_3_stat_s
//entry
segments_buy = high > high[1] and seg_stat_l[1]
segments_sell = low < low[1] and seg_stat_s[1]
//filters
segments_buy_f = high > high[1] and seg_stat_l[1]
segments_sell_f = low < low[1] and seg_stat_s[1]
//----------------------- i-o-s-p signals ------------------------
i_bar_buy = high[1] < high[2] and low[1] > low[2] and close > high[1]
i_bar_sell = high[1] < high[2] and low[1] > low[2] and close < low[1]
o_bar_buy = high[1] > high[2] and low[1] < low[2] and high > high[1]
o_bar_sell = high[1] > high[2] and low[1] < low[2] and low < low[1]
s_bar_buy = high[2] < high[3] and low[2] > low[3] and high[1] > high[2] and low[1] < low[2] and high > high[1]
s_bar_sell = high[2] < high[3] and low[2] > low[3] and high[1] > high[2] and low[1] < low[2] and low < low[1]
//pinbar
candle_body = math.abs(open - close)
pivot_up = ta.pivothigh(high, p_bar_sens_2, 0)
pivot_dn = ta.pivotlow(low, p_bar_sens_2, 0)
up_wick = close > open ? high - close : high - open
dn_wick = close > open ? open - low : close - low
pin_up_def = high - open > p_bar_sens_1 * candle_body and close < open or high - close > p_bar_sens_1 * candle_body and close > open
pin_dn_def = open - low > p_bar_sens_1 * candle_body and close > open or close - low > p_bar_sens_1 * candle_body and close < open
p_bar_sell = pin_up_def and pivot_up and up_wick > dn_wick
p_bar_buy = pin_dn_def and pivot_dn and up_wick < dn_wick
//----------------- Ichimoku Signal B1/S1 -----------------
buy_strong_B1 = TK >= KJ and high > kumo_high and CS > high[26 - 1] and CS > kumo_high[26 - 1] and SA > SB
sell_strong_S1 = TK <= KJ and low < kumo_low and CS < low[26 - 1] and CS < kumo_low[26 - 1] and SA < SB
//----------------- Ichimoku Signal B2/S2 -----------------
buy_strong_B2 = TK >= KJ and high > kumo_high and CS > high[26 - 1]
sell_strong_S2 = TK <= KJ and low < kumo_low and CS < low[26 - 1]
//---------------------------- Confluence Signal CB/CS ----------------------------
long_short_trig = 10 //input(9, type= input.float, title= "Confluence signal trigger Level", step= 0.2)
//Indicators
// ma
sma1 = f_sma(50)
sma2 = f_sma(200)
ema1 = f_ema(50)
ema2 = f_ema(200)
ema_c = f_ema(21)
sma_c = f_sma(20)
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
rsi = f_rsi(14)
[diplus, diminus, adx] = ta.dmi(7, 7)
[superTrend, dir] = ta.supertrend(2, 5)
//Klinger Oszillator
sv = ta.change(hlc3) >= 0 ? volume : -volume
kvo = ta.ema(sv, 34) - ta.ema(sv, 55)
sig = ta.ema(kvo, 13)
//Vortex Indicator
VMP = math.sum(math.abs(high - low[1]), 14)
VMM = math.sum(math.abs(low - high[1]), 14)
STR = math.sum(ta.atr(1), 14)
VIP = VMP / STR
VIM = VMM / STR
//HMA slope
hma_slo_up = ta.rising(f_hma(15),1)
//ALMA slope
alma_slo_up = ta.rising(ta.alma(close, 9, 0.85, 6),1)
//MACD slope
macd_slo_up = ta.rising(macdLine, 1)
//Signals
var float sem_sig_w = na
var float sma_sig_w = na
var float ema_sig_w = na
var float p_kj_sig_w = na
var float tk_kj_sig_w = na
var float B1_S1_sig_w = na
var float B2_S2_sig_w = na
var float psar_sig_w = na
var float frac_sig_w = na
var float macd_sig_w = na
var float rsi_sig_w = na
var float p_tk_sig_w = na
var float dmi_sig_w = na
var float klin_sig_w = na
var float vort_sig_w = na
var float sup_sig_w = na
var float hma_sig_w = na
var float alma_sig_w = na
var float macd_s_sig_w = na
if ema_c > sma_c
sem_sig_w := 1
else if ema_c < sma_c
sem_sig_w := 0
if sma1 > sma2
sma_sig_w := 1
else if sma1 < sma2
sma_sig_w := 0
if ema1 > ema2
ema_sig_w := 1
else if ema1 < ema2
ema_sig_w := 0
if high > KJ
p_kj_sig_w := 1
else if low < KJ
p_kj_sig_w := 0
if TK > KJ
tk_kj_sig_w := 1
else if TK < KJ
tk_kj_sig_w := 0
if buy_strong_B1
B1_S1_sig_w := 1
else if sell_strong_S1
B1_S1_sig_w := 0
if buy_strong_B2
B2_S2_sig_w := 1
else if sell_strong_S2
B2_S2_sig_w := 0
if high >= ta.sar(start, inc, max)[0]
psar_sig_w := 1
else if low <= ta.sar(start, inc, max)[0]
psar_sig_w := 0
if high > fractal_up_v
frac_sig_w := 1
else if low < fractal_dn_v
frac_sig_w := 0
if macdLine > signalLine
macd_sig_w := 1
else if macdLine < signalLine
macd_sig_w := 0
if rsi > 50
rsi_sig_w := 1
else if rsi < 50
rsi_sig_w := 0
if high > TK
p_tk_sig_w := 1
else if low < TK
p_tk_sig_w := 0
if diplus > diminus
dmi_sig_w := 1
else if diplus < diminus
dmi_sig_w := 0
if sig > 0
klin_sig_w := 1
else if sig < 0
klin_sig_w := 0
if VIP > VIM
vort_sig_w := 1
else if VIP < VIM
vort_sig_w := 0
if high > superTrend
sup_sig_w := 1
else if low < superTrend
sup_sig_w := 0
if hma_slo_up
hma_sig_w := 2
else if not hma_slo_up
hma_sig_w := -1
if alma_slo_up
alma_sig_w := 2
else if not alma_slo_up
alma_sig_w := -1
if macd_slo_up
macd_s_sig_w := 1
else if not macd_slo_up
macd_s_sig_w := 0
bs_conf_sig = sma_sig_w + ema_sig_w + p_kj_sig_w + tk_kj_sig_w + B1_S1_sig_w + B2_S2_sig_w + psar_sig_w + frac_sig_w + macd_sig_w + rsi_sig_w + dmi_sig_w + klin_sig_w + vort_sig_w + sup_sig_w +
p_tk_sig_w + sem_sig_w + hma_sig_w + alma_sig_w + macd_s_sig_w
long_c = one_side_pyr ? ta.crossover(bs_conf_sig, (long_short_trig + trig_gap_cbcs)) : bs_conf_sig > (long_short_trig + trig_gap_cbcs) //with +- signal is more stable
short_c = one_side_pyr ? ta.crossunder(bs_conf_sig, (long_short_trig - trig_gap_cbcs)) : bs_conf_sig < (long_short_trig - trig_gap_cbcs)
//---------------------------- Pure Ichimoku Confluence Signal IB/IS ----------------------------
pic_l_s_trig = 5 //input(4, type= input.float, title= "Ichimoku confluence signal trigger Level", step= 0.1)
//Signals
var float tkkh_sig_w = na
var float csh_sig_w = na
var float cskh_sig_w = na
var float pkj_sig_w = na
var float ptk_sig_w = na
var float tkkj_sig_w = na
var float sasb_sig_w = na
var float ckh_sig_w = na
var float cskj_sig_w = na
var float cstk_sig_w = na
var float kjcl_sig_w = na
if TK > kumo_high
tkkh_sig_w := 1
else if TK < kumo_low
tkkh_sig_w := 0
if CS > high[26 - 1]
csh_sig_w := 1
else if CS < low[26 - 1]
csh_sig_w := 0
if CS > kumo_high[26 - 1]
cskh_sig_w := 1
else if CS < kumo_low[26 - 1]
cskh_sig_w := 0
if high > TK
ptk_sig_w := 1
else if low < TK
ptk_sig_w := 0
if high > KJ
pkj_sig_w := 1
else if low < KJ
pkj_sig_w := 0
if TK > KJ
tkkj_sig_w := 1
else if TK < KJ
tkkj_sig_w := 0
if SA > SB
sasb_sig_w := 1
else if SA < SB
sasb_sig_w := 0
if high > kumo_high
ckh_sig_w := 1
else if low < kumo_low
ckh_sig_w := 0
if CS > KJ[26 - 1]
cskj_sig_w := 1
else if CS < KJ[26 - 1]
cskj_sig_w := 0
if CS > TK[26 - 1]
cstk_sig_w := 1
else if CS < TK[26 - 1]
cstk_sig_w := 0
if KJ > kumo_high
kjcl_sig_w := 1
else if KJ < kumo_high
kjcl_sig_w := 0
bs_pic_sig = tkkh_sig_w + csh_sig_w + cskh_sig_w + ptk_sig_w + pkj_sig_w + tkkj_sig_w + sasb_sig_w + ckh_sig_w + cskj_sig_w + cstk_sig_w + kjcl_sig_w
long_pic = one_side_pyr ? ta.crossover(bs_pic_sig, pic_l_s_trig + trig_gap_ibis) : bs_pic_sig > pic_l_s_trig + trig_gap_ibis
short_pic = one_side_pyr ? ta.crossunder(bs_pic_sig, pic_l_s_trig - trig_gap_ibis) : bs_pic_sig < pic_l_s_trig - trig_gap_ibis
long_pic_x = long_pic and not long_pic[1]
short_pic_x = short_pic and not short_pic[1]
//-------------------------------------------------------------------- entry filters -------------------------------------------------------------------
f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[repaint == 'Allowed' ? 0 : 1]) // no repainting - taken from PineCoders
entry_filter_sig_buy_1 = entry_f_1 == '---' ? true :
entry_f_1 == 'TRIX slope filter' ? trix_slo_up_f :
entry_f_1 == 'RSI Stochastic filter' ? kd_mom_up_f :
entry_f_1 == 'EMA1 x EMA2 filter' ? ema_1x2_buy_f :
entry_f_1 == 'HMA slope filter' ? hma_up_f :
entry_f_1 == 'MACD(fast) slope filter' ? macd_slope_up_f :
entry_f_1 == 'MACD filter' ? macd_buy :
entry_f_1 == 'RSI50 filter' ? rsi_f_buy_f :
entry_f_1 == 'Fractals filter' ? fr_upx_f :
entry_f_1 == 'SuperTrend filter' ? sup_buy_f :
entry_f_1 == 'Parabolic SAR filter' ? psar_buy_f :
entry_f_1 == 'SMA filter' ? sma_buy_f :
entry_f_1 == 'ADX Threshold filter' ? adx_above_thres :
entry_f_1 == 'DMI filter' ? long_e :
entry_f_1 == 'Bar breakout 1 filter' ? bar_sig_1_buy_f :
entry_f_1 == 'Bar breakout 2 filter' ? bar_sig_2_buy_f :
entry_f_1 == 'Reverse fractal filter' ? rev_dn_fr_buy :
entry_f_1 == 'ALMA slope filter' ? alma_slo_up_f :
entry_f_1 == 'Price X Kumo filter' ? kumo_buy_f :
entry_f_1 == 'Price X Kijun filter' ? kijun_buy_f :
entry_f_1 == 'Kumo flip filter' ? kumo_flip_buy_f :
entry_f_1 == 'Chikou X price filter' ? chikou_X_price_buy_f :
entry_f_1 == 'Chikou X Kumo filter' ? chikou_X_kumo_buy_f :
entry_f_1 == 'Price X Tenkan filter' ? price_X_tenkan_buy_f :
entry_f_1 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_buy_f :
entry_f_1 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_buy_f :
entry_f_1 == 'B1/S1 sig' ? buy_strong_B1 :
entry_f_1 == 'B2/S2 sig' ? buy_strong_B2 : true
entry_filter_sig_sell_1 = entry_f_1 == '---' ? true :
entry_f_1 == 'TRIX slope filter' ? not trix_slo_up_f :
entry_f_1 == 'RSI Stochastic filter' ? kd_mom_dn_f :
entry_f_1 == 'EMA1 x EMA2 filter' ? not ema_1x2_buy_f :
entry_f_1 == 'HMA slope filter' ? not hma_up_f :
entry_f_1 == 'MACD(fast) slope filter' ? not macd_slope_up_f :
entry_f_1 == 'MACD filter' ? macd_sell :
entry_f_1 == 'RSI50 filter' ? rsi_f_sell_f :
entry_f_1 == 'Fractals filter' ? fr_dnx_f :
entry_f_1 == 'SuperTrend filter' ? sup_sell_f :
entry_f_1 == 'Parabolic SAR filter' ? psar_sell_f :
entry_f_1 == 'SMA filter' ? sma_sell_f :
entry_f_1 == 'ADX Threshold filter' ? adx_above_thres :
entry_f_1 == 'DMI filter' ? short_e :
entry_f_1 == 'Bar breakout 1 filter' ? bar_sig_1_sell_f :
entry_f_1 == 'Bar breakout 2 filter' ? bar_sig_2_sell_f :
entry_f_1 == 'Reverse fractal filter' ? rev_up_fr_sell :
entry_f_1 == 'ALMA slope filter' ? not alma_slo_up_f :
entry_f_1 == 'Price X Kumo filter' ? kumo_sell_f :
entry_f_1 == 'Price X Kijun filter' ? kijun_sell_f :
entry_f_1 == 'Kumo flip filter' ? kumo_flip_sell_f :
entry_f_1 == 'Chikou X price filter' ? chikou_X_price_sell_f :
entry_f_1 == 'Chikou X Kumo filter' ? chikou_X_kumo_sell_f :
entry_f_1 == 'Price X Tenkan filter' ? price_X_tenkan_sell_f :
entry_f_1 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_sell_f :
entry_f_1 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_sell_f :
entry_f_1 == 'B1/S1 sig' ? sell_strong_S1 :
entry_f_1 == 'B2/S2 sig' ? sell_strong_S2 : true
entry_filter_sig_buy_2 = entry_f_2 == '---' ? true :
entry_f_2 == 'TRIX slope filter' ? trix_slo_up_f :
entry_f_2 == 'RSI Stochastic filter' ? kd_mom_up_f :
entry_f_2 == 'EMA1 x EMA2 filter' ? ema_1x2_buy_f :
entry_f_2 == 'HMA slope filter' ? hma_up_f :
entry_f_2 == 'MACD(fast) slope filter' ? macd_slope_up_f :
entry_f_2 == 'MACD filter' ? macd_buy :
entry_f_2 == 'RSI50 filter' ? rsi_f_buy_f :
entry_f_2 == 'Fractals filter' ? fr_upx_f :
entry_f_2 == 'SuperTrend filter' ? sup_buy_f :
entry_f_2 == 'Parabolic SAR filter' ? psar_buy_f :
entry_f_2 == 'SMA filter' ? sma_buy_f :
entry_f_2 == 'ADX Threshold filter' ? adx_above_thres :
entry_f_2 == 'DMI filter' ? long_e :
entry_f_2 == 'Bar breakout 1 filter' ? bar_sig_1_buy_f :
entry_f_2 == 'Bar breakout 2 filter' ? bar_sig_2_buy_f :
entry_f_2 == 'Reverse fractal filter' ? rev_dn_fr_buy :
entry_f_2 == 'ALMA slope filter' ? alma_slo_up_f :
entry_f_2 == 'Price X Kumo filter' ? kumo_buy_f :
entry_f_2 == 'Price X Kijun filter' ? kijun_buy_f :
entry_f_2 == 'Kumo flip filter' ? kumo_flip_buy_f :
entry_f_2 == 'Chikou X price filter' ? chikou_X_price_buy_f :
entry_f_2 == 'Chikou X Kumo filter' ? chikou_X_kumo_buy_f :
entry_f_2 == 'Price X Tenkan filter' ? price_X_tenkan_buy_f :
entry_f_2 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_buy_f :
entry_f_2 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_buy_f :
entry_f_2 == 'B1/S1 sig' ? buy_strong_B1 :
entry_f_2 == 'B2/S2 sig' ? buy_strong_B2 : true
entry_filter_sig_sell_2 = entry_f_2 == '---' ? true :
entry_f_2 == 'TRIX slope filter' ? not trix_slo_up_f :
entry_f_2 == 'RSI Stochastic filter' ? kd_mom_dn_f :
entry_f_2 == 'EMA1 x EMA2 filter' ? not ema_1x2_buy_f :
entry_f_2 == 'HMA slope filter' ? not hma_up_f :
entry_f_2 == 'MACD(fast) slope filter' ? not macd_slope_up_f :
entry_f_2 == 'MACD filter' ? macd_sell :
entry_f_2 == 'RSI50 filter' ? rsi_f_sell_f :
entry_f_2 == 'Fractals filter' ? fr_dnx_f :
entry_f_2 == 'SuperTrend filter' ? sup_sell_f :
entry_f_2 == 'Parabolic SAR filter' ? psar_sell_f :
entry_f_2 == 'SMA filter' ? sma_sell_f :
entry_f_2 == 'ADX Threshold filter' ? adx_above_thres :
entry_f_2 == 'DMI filter' ? long_e :
entry_f_2 == 'Bar breakout 1 filter' ? bar_sig_1_sell_f :
entry_f_2 == 'Bar breakout 2 filter' ? bar_sig_2_sell_f :
entry_f_2 == 'Reverse fractal filter' ? rev_up_fr_sell :
entry_f_2 == 'ALMA slope filter' ? not alma_slo_up_f :
entry_f_2 == 'Price X Kumo filter' ? kumo_sell_f :
entry_f_2 == 'Price X Kijun filter' ? kijun_sell_f :
entry_f_2 == 'Kumo flip filter' ? kumo_flip_sell_f :
entry_f_2 == 'Chikou X price filter' ? chikou_X_price_sell_f :
entry_f_2 == 'Chikou X Kumo filter' ? chikou_X_kumo_sell_f :
entry_f_2 == 'Price X Tenkan filter' ? price_X_tenkan_sell_f :
entry_f_2 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_sell_f :
entry_f_2 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_sell_f :
entry_f_2 == 'B1/S1 sig' ? sell_strong_S1 :
entry_f_2 == 'B2/S2 sig' ? sell_strong_S2 : true
//entry buy filter 1 options
entry_filter_buy_1 = htf_filt_opt_1 == 'Current' ? entry_filter_sig_buy_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_filt_opt_1 == '5m' ? '5' : htf_filt_opt_1 == '10m' ? '10' : htf_filt_opt_1 == '15m' ? '15' :
htf_filt_opt_1 == '30m' ? '30' : htf_filt_opt_1 == '1H' ? '60' : htf_filt_opt_1 == '2H' ? '120' : htf_filt_opt_1 == '3H' ? '180' : htf_filt_opt_1 == '4H' ? '240' :
htf_filt_opt_1 == '6H' ? '360' : htf_filt_opt_1 == '12H' ? '720' : htf_filt_opt_1 == 'D' ? 'D' : htf_filt_opt_1 == '3D' ? '3D' : htf_filt_opt_1 == 'W' ? 'W' : htf_filt_opt_1 == 'M' ? 'M' : na,
entry_filter_sig_buy_1)
entry_filter_buy_11 = entry_f_1 == 'Segments filter (no tf filter)' ? segments_buy :
entry_f_1 == 'IB/IS sig (no tf filter)' ? long_pic[repaint == 'Allowed' ? 0 : 1] :
entry_f_1 == 'Fractals trend lines filter (no tf filter)' ? buy_up_line : true
//entry sell filter 1 options
entry_filter_sell_1 = htf_filt_opt_1 == 'Current' ? entry_filter_sig_sell_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_filt_opt_1 == '5m' ? '5' : htf_filt_opt_1 == '10m' ? '10' : htf_filt_opt_1 == '15m' ? '15' :
htf_filt_opt_1 == '30m' ? '30' : htf_filt_opt_1 == '1H' ? '60' : htf_filt_opt_1 == '2H' ? '120' : htf_filt_opt_1 == '3H' ? '180' : htf_filt_opt_1 == '4H' ? '240' :
htf_filt_opt_1 == '6H' ? '360' : htf_filt_opt_1 == '12H' ? '720' : htf_filt_opt_1 == 'D' ? 'D' : htf_filt_opt_1 == '3D' ? '3D' : htf_filt_opt_1 == 'W' ? 'W' : htf_filt_opt_1 == 'M' ? 'M' : na,
entry_filter_sig_sell_1)
entry_filter_sell_11 = entry_f_1 == 'Segments filter (no tf filter)' ? segments_sell :
entry_f_1 == 'IB/IS sig (no tf filter)' ? short_pic[repaint == 'Allowed' ? 0 : 1] :
entry_f_1 == 'Fractals trend lines filter (no tf filter)' ? sell_dn_line : true
//entry buy filter 2 options
entry_filter_buy_2 = htf_filt_opt_2 == 'Current' ? entry_filter_sig_buy_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_filt_opt_2 == '5m' ? '5' : htf_filt_opt_2 == '10m' ? '10' : htf_filt_opt_2 == '15m' ? '15' :
htf_filt_opt_2 == '30m' ? '30' : htf_filt_opt_2 == '1H' ? '60' : htf_filt_opt_2 == '2H' ? '120' : htf_filt_opt_2 == '3H' ? '180' : htf_filt_opt_2 == '4H' ? '240' :
htf_filt_opt_2 == '6H' ? '360' : htf_filt_opt_2 == '12H' ? '720' : htf_filt_opt_2 == 'D' ? 'D' : htf_filt_opt_2 == '3D' ? '3D' : htf_filt_opt_2 == 'W' ? 'W' : htf_filt_opt_2 == 'M' ? 'M' : na,
entry_filter_sig_buy_2)
entry_filter_buy_22 = entry_f_2 == 'Fractals trend lines filter (no tf filter)' ? buy_up_line :
entry_f_2 == 'Segments filter (no tf filter)' ? segments_buy :
entry_f_2 == 'IB/IS sig (no tf filter)' ? long_pic[repaint == 'Allowed' ? 0 : 1] : true
//entry sell filter 2 options
entry_filter_sell_2 = htf_filt_opt_2 == 'Current' ? entry_filter_sig_sell_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_filt_opt_2 == '5m' ? '5' : htf_filt_opt_2 == '10m' ? '10' : htf_filt_opt_2 == '15m' ? '15' :
htf_filt_opt_2 == '30m' ? '30' : htf_filt_opt_2 == '1H' ? '60' : htf_filt_opt_2 == '2H' ? '120' : htf_filt_opt_2 == '3H' ? '180' : htf_filt_opt_2 == '4H' ? '240' :
htf_filt_opt_2 == '6H' ? '360' : htf_filt_opt_2 == '12H' ? '720' : htf_filt_opt_2 == 'D' ? 'D' : htf_filt_opt_2 == '3D' ? '3D' : htf_filt_opt_2 == 'W' ? 'W' : htf_filt_opt_2 == 'M' ? 'M' : na,
entry_filter_sig_sell_2)
entry_filter_sell_22 = entry_f_2 == 'Fractals trend lines filter (no tf filter)' ? sell_dn_line :
entry_f_2 == 'Segments filter (no tf filter)' ? segments_sell :
entry_f_2 == 'IB/IS sig (no tf filter)' ? short_pic[repaint == 'Allowed' ? 0 : 1] : true
//-------------------------------------------------------------------- exit filters -----------------------------------------------------------------------
exit_filter_sig_buy_1 = exit_f_1 == '---' ? false :
exit_f_1 == 'TRIX slope exit' ? trix_slo_up_x :
exit_f_1 == 'RSI Stochastic exit' ? kd_mom_up_x :
exit_f_1 == 'EMA1 x EMA2 exit' ? ema_1x2_buy_x :
exit_f_1 == 'HMA slope exit' ? hma_up_x :
exit_f_1 == 'Reverse bar exit' ? rev_bar_sig_buy :
exit_f_1 == 'Reverse fractal exit' ? rev_dn_fr_buy :
exit_f_1 == 'Bar breakout 2 exit' ? bar_sig_2_buy :
exit_f_1 == 'MACD(fast) slope exit' ? macd_slope_up_x :
exit_f_1 == 'MACD exit' ? macd_buy_x :
exit_f_1 == 'RSI50 exit' ? rsi_f_buy_x :
exit_f_1 == 'Fractals exit' ? fr_upx_x :
exit_f_1 == 'SuperTrend exit' ? sup_buy_x :
exit_f_1 == 'Parabolic SAR exit' ? psar_buy_x :
exit_f_1 == 'SMA exit' ? sma_buy_x :
exit_f_1 == 'ADX Threshold exit' ? adx_thres_f_x :
exit_f_1 == 'Cloud exit' ? kumo_buy_x :
exit_f_1 == 'Kijun exit' ? kijun_buy_x : false
exit_filter_sig_sell_1 = exit_f_1 == '---' ? false :
exit_f_1 == 'TRIX slope exit' ? trix_slo_dn_x :
exit_f_1 == 'RSI Stochastic exit' ? kd_mom_dn_x :
exit_f_1 == 'EMA1 x EMA2 exit' ? ema_1x2_sell_x :
exit_f_1 == 'HMA slope exit' ? hma_dn_x :
exit_f_1 == 'Reverse bar exit' ? rev_bar_sig_sell :
exit_f_1 == 'Reverse fractal exit' ? rev_up_fr_sell :
exit_f_1 == 'Bar breakout 2 exit' ? bar_sig_2_sell :
exit_f_1 == 'MACD(fast) slope exit' ? macd_slope_dn_x :
exit_f_1 == 'MACD exit' ? macd_sell_x :
exit_f_1 == 'RSI50 exit' ? rsi_f_sell_x :
exit_f_1 == 'Fractals exit' ? fr_dnx_x :
exit_f_1 == 'SuperTrend exit' ? sup_sell_x :
exit_f_1 == 'Parabolic SAR exit' ? psar_sell_x :
exit_f_1 == 'SMA exit' ? sma_sell_x :
exit_f_1 == 'ADX Threshold exit' ? adx_thres_f_x :
exit_f_1 == 'Cloud exit' ? kumo_sell_x :
exit_f_1 == 'Kijun exit' ? kijun_sell_x : false
exit_filter_sig_buy_2 = exit_f_2 == '---' ? false :
exit_f_2 == 'TRIX slope exit' ? trix_slo_up_x :
exit_f_2 == 'RSI Stochastic exit' ? kd_mom_up_x :
exit_f_2 == 'EMA1 x EMA2 exit' ? ema_1x2_buy_x :
exit_f_2 == 'HMA slope exit' ? hma_up_x :
exit_f_2 == 'Reverse bar exit' ? rev_bar_sig_buy :
exit_f_2 == 'Reverse fractal exit' ? rev_dn_fr_buy :
exit_f_2 == 'Bar breakout 2 exit' ? bar_sig_2_buy :
exit_f_2 == 'MACD(fast) slope exit' ? macd_slope_up_x :
exit_f_2 == 'MACD exit' ? macd_buy_x :
exit_f_2 == 'RSI50 exit' ? rsi_f_buy_x :
exit_f_2 == 'Fractals exit' ? fr_upx_x :
exit_f_2 == 'SuperTrend exit' ? sup_buy_x :
exit_f_2 == 'Parabolic SAR exit' ? psar_buy_x :
exit_f_2 == 'SMA exit' ? sma_buy_x :
exit_f_2 == 'ADX Threshold exit' ? adx_thres_f_x :
exit_f_2 == 'Cloud exit' ? kumo_buy_x :
exit_f_2 == 'Kijun exit' ? kijun_buy_x : false
exit_filter_sig_sell_2 = exit_f_2 == '---' ? false :
exit_f_2 == 'TRIX slope exit' ? trix_slo_dn_x :
exit_f_2 == 'RSI Stochastic exit' ? kd_mom_dn_x :
exit_f_2 == 'EMA1 x EMA2 exit' ? ema_1x2_sell_x :
exit_f_2 == 'HMA slope exit' ? hma_dn_x :
exit_f_2 == 'Reverse bar exit' ? rev_bar_sig_sell :
exit_f_2 == 'Reverse fractal exit' ? rev_up_fr_sell :
exit_f_2 == 'Bar breakout 2 exit' ? bar_sig_2_sell :
exit_f_2 == 'MACD(fast) slope exit' ? macd_slope_dn_x :
exit_f_2 == 'MACD exit' ? macd_sell_x :
exit_f_2 == 'RSI50 exit' ? rsi_f_sell_x :
exit_f_2 == 'Fractals exit' ? fr_dnx_x :
exit_f_2 == 'SuperTrend exit' ? sup_sell_x :
exit_f_2 == 'Parabolic SAR exit' ? psar_sell_x :
exit_f_2 == 'SMA exit' ? sma_sell_x :
exit_f_2 == 'ADX Threshold exit' ? adx_thres_f_x :
exit_f_2 == 'Cloud exit' ? kumo_sell_x :
exit_f_2 == 'Kijun exit' ? kijun_sell_x : false
//short exit buy filter 1 options
exit_filter_buy_1 = htf_exit_opt_1 == 'Current' ? exit_filter_sig_buy_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_exit_opt_1 == '5m' ? '5' : htf_exit_opt_1 == '10m' ? '10' : htf_exit_opt_1 == '15m' ? '15' :
htf_exit_opt_1 == '30m' ? '30' : htf_exit_opt_1 == '1H' ? '60' : htf_exit_opt_1 == '2H' ? '120' : htf_exit_opt_1 == '3H' ? '180' : htf_exit_opt_1 == '4H' ? '240' :
htf_exit_opt_1 == '6H' ? '360' : htf_exit_opt_1 == '12H' ? '720' : htf_exit_opt_1 == 'D' ? 'D' : htf_exit_opt_1 == '3D' ? '3D' : htf_exit_opt_1 == 'W' ? 'W' :
htf_exit_opt_1 == 'M' ? 'M' : na, exit_filter_sig_buy_1)
exit_filter_sig_buy_11 = exit_f_1 == 'IB/IS exit (no tf filter)' ? long_pic_x[repaint == 'Allowed' ? 0 : 1] : false
//long exit sell filter 1 options
exit_filter_sell_1 = htf_exit_opt_1 == 'Current' ? exit_filter_sig_sell_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_exit_opt_1 == '5m' ? '5' : htf_exit_opt_1 == '10m' ? '10' : htf_exit_opt_1 == '15m' ? '15' :
htf_exit_opt_1 == '30m' ? '30' : htf_exit_opt_1 == '1H' ? '60' : htf_exit_opt_1 == '2H' ? '120' : htf_exit_opt_1 == '3H' ? '180' : htf_exit_opt_1 == '4H' ? '240' :
htf_exit_opt_1 == '6H' ? '360' : htf_exit_opt_1 == '12H' ? '720' : htf_exit_opt_1 == 'D' ? 'D' : htf_exit_opt_1 == '3D' ? '3D' : htf_exit_opt_1 == 'W' ? 'W' :
htf_exit_opt_1 == 'M' ? 'M' : na, exit_filter_sig_sell_1)
exit_filter_sig_sell_11 = exit_f_1 == 'IB/IS exit (no tf filter)' ? short_pic_x[repaint == 'Allowed' ? 0 : 1] : false
//short exit buy filter 2 options
exit_filter_buy_2 = htf_exit_opt_2 == 'Current' ? exit_filter_sig_buy_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_exit_opt_2 == '5m' ? '5' : htf_exit_opt_2 == '10m' ? '10' : htf_exit_opt_2 == '15m' ? '15' :
htf_exit_opt_2 == '30m' ? '30' : htf_exit_opt_2 == '1H' ? '60' : htf_exit_opt_2 == '2H' ? '120' : htf_exit_opt_2 == '3H' ? '180' : htf_exit_opt_2 == '4H' ? '240' :
htf_exit_opt_2 == '6H' ? '360' : htf_exit_opt_2 == '12H' ? '720' : htf_exit_opt_2 == 'D' ? 'D' : htf_exit_opt_2 == '3D' ? '3D' : htf_exit_opt_2 == 'W' ? 'W' :
htf_exit_opt_2 == 'M' ? 'M' : na, exit_filter_sig_buy_2)
exit_filter_sig_buy_22 = exit_f_2 == 'IB/IS exit (no tf filter)' ? long_pic_x[repaint == 'Allowed' ? 0 : 1] : false
//long exit sell filter 2 options
exit_filter_sell_2 = htf_exit_opt_2 == 'Current' ? exit_filter_sig_sell_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_exit_opt_2 == '5m' ? '5' : htf_exit_opt_2 == '10m' ? '10' : htf_exit_opt_2 == '15m' ? '15' :
htf_exit_opt_2 == '30m' ? '30' : htf_exit_opt_2 == '1H' ? '60' : htf_exit_opt_2 == '2H' ? '120' : htf_exit_opt_2 == '3H' ? '180' : htf_exit_opt_2 == '4H' ? '240' :
htf_exit_opt_2 == '6H' ? '360' : htf_exit_opt_2 == '12H' ? '720' : htf_exit_opt_2 == 'D' ? 'D' : htf_exit_opt_2 == '3D' ? '3D' : htf_exit_opt_2 == 'W' ? 'W' :
htf_exit_opt_2 == 'M' ? 'M' : na, exit_filter_sig_sell_2)
exit_filter_sig_sell_22 = exit_f_2 == 'IB/IS exit (no tf filter)' ? short_pic_x[repaint == 'Allowed' ? 0 : 1] : false
//---------------------------------------------------------------------- entry signals -------------------------------------------------------------------
entry_opt_sig_buy_1 = X_opt == '---' ? na :
X_opt == 'TRIX slope sig' ? trix_buy_s :
X_opt == 'EMA1 x EMA2 sig' ? ema_1x2_buy_s :
X_opt == 'HMA slope sig' ? hma_up_e :
X_opt == 'DMI ADX-slope sig' ? adx_up_c :
X_opt == 'DMI ADX mod sig' ? long_1 :
X_opt == 'DMI ADX classic sig' ? long_2 :
X_opt == 'Pin bar sig' ? p_bar_buy :
X_opt == 'Inside bar sig' ? i_bar_buy :
X_opt == 'Outside bar sig' ? o_bar_buy :
X_opt == 'Sandwich bar sig' ? s_bar_buy :
X_opt == 'Bar breakout 1 sig' ? bar_sig_1_buy :
X_opt == 'Bar breakout 2 sig' ? bar_sig_2_buy :
X_opt == 'Higher-low/lower-high bar sig' ? hllh_buy :
X_opt == 'Entry on every bar-open sig' ? open_buy :
X_opt == 'SMA sig' ? sma_buy :
X_opt == 'Fractals sig' ? fr_upx :
X_opt == 'Reverse fractal sig' ? rev_dn_fr_buy :
X_opt == 'MACD(fast) slope sig' ? macd_slope_up_e :
X_opt == 'RSI50 sig' ? rsi_f_buy :
X_opt == 'Parabolic SAR sig' ? psar_buy :
X_opt == 'ALMA slope sig' ? alma_slo_up_e :
X_opt == 'SuperTrend sig' ? sup_buy :
X_opt == 'Price X Kijun sig' ? kijun_buy :
X_opt == 'Price X Kumo sig' ? kumo_buy :
X_opt == 'Kumo flip sig' ? kumo_flip_buy :
X_opt == 'Chikou X price sig' ? chikou_X_price_buy :
X_opt == 'Chikou X Kumo sig' ? chikou_X_kumo_buy :
X_opt == 'Price X Tenkan sig' ? price_X_tenkan_buy :
X_opt == 'Tenkan X Kumo sig' ? tenkan_X_kumo_buy :
X_opt == 'Tenkan X Kijun sig' ? tenkan_X_kijun_buy :
X_opt == 'B1/S1 sig' ? buy_strong_B1 :
X_opt == 'B2/S2 sig' ? buy_strong_B2 : na
entry_opt_sig_sell_1 = X_opt == '---' ? na :
X_opt == 'TRIX slope sig' ? trix_sell_s :
X_opt == 'EMA1 x EMA2 sig' ? ema_1x2_sell_s :
X_opt == 'HMA slope sig' ? hma_dn_e :
X_opt == 'DMI ADX-slope sig' ? adx_dn_c :
X_opt == 'DMI ADX mod sig' ? short_1 :
X_opt == 'DMI ADX classic sig' ? short_2 :
X_opt == 'Pin bar sig' ? p_bar_sell :
X_opt == 'Inside bar sig' ? i_bar_sell :
X_opt == 'Outside bar sig' ? o_bar_sell :
X_opt == 'Sandwich bar sig' ? s_bar_sell :
X_opt == 'Bar breakout 1 sig' ? bar_sig_1_sell :
X_opt == 'Bar breakout 2 sig' ? bar_sig_2_sell :
X_opt == 'Higher-low/lower-high bar sig' ? hllh_sell :
X_opt == 'Entry on every bar-open sig' ? open_sell :
X_opt == 'SMA sig' ? sma_sell :
X_opt == 'Fractals sig' ? fr_dnx :
X_opt == 'Reverse fractal sig' ? rev_up_fr_sell :
X_opt == 'MACD(fast) slope sig' ? macd_slope_dn_e :
X_opt == 'RSI50 sig' ? rsi_f_sell :
X_opt == 'Parabolic SAR sig' ? psar_sell :
X_opt == 'ALMA slope sig' ? alma_slo_dn_e :
X_opt == 'SuperTrend sig' ? sup_sell :
X_opt == 'Price X Kijun sig' ? kijun_sell :
X_opt == 'Price X Kumo sig' ? kumo_sell :
X_opt == 'Kumo flip sig' ? kumo_flip_sell :
X_opt == 'Chikou X price sig' ? chikou_X_price_sell :
X_opt == 'Chikou X Kumo sig' ? chikou_X_kumo_sell :
X_opt == 'Price X Tenkan sig' ? price_X_tenkan_sell :
X_opt == 'Tenkan X Kumo sig' ? tenkan_X_kumo_sell :
X_opt == 'Tenkan X Kijun sig' ? tenkan_X_kijun_sell :
X_opt == 'B1/S1 sig' ? sell_strong_S1 :
X_opt == 'B2/S2 sig' ? sell_strong_S2 : na
entry_opt_sig_buy_2 = X_opt_2 == '---' ? na :
X_opt_2 == 'TRIX slope sig' ? trix_buy_s :
X_opt_2 == 'EMA1 x EMA2 sig' ? ema_1x2_buy_s :
X_opt_2 == 'HMA slope sig' ? hma_up_e :
X_opt_2 == 'DMI ADX-slope sig' ? adx_up_c :
X_opt_2 == 'DMI ADX mod sig' ? long_1 :
X_opt_2 == 'DMI ADX classic sig' ? long_2 :
X_opt_2 == 'Pin bar sig' ? p_bar_buy :
X_opt_2 == 'Inside bar sig' ? i_bar_buy :
X_opt_2 == 'Outside bar sig' ? o_bar_buy :
X_opt_2 == 'Sandwich bar sig' ? s_bar_buy :
X_opt_2 == 'Bar breakout 1 sig' ? bar_sig_1_buy :
X_opt_2 == 'Bar breakout 2 sig' ? bar_sig_2_buy :
X_opt_2 == 'Higher-low/lower-high bar sig' ? hllh_buy :
X_opt_2 == 'Entry on every bar-open sig' ? open_buy :
X_opt_2 == 'SMA sig' ? sma_buy :
X_opt_2 == 'Fractals sig' ? fr_upx :
X_opt_2 == 'Reverse fractal sig' ? rev_dn_fr_buy :
X_opt_2 == 'MACD(fast) slope sig' ? macd_slope_up_e :
X_opt_2 == 'RSI50 sig' ? rsi_f_buy :
X_opt_2 == 'Parabolic SAR sig' ? psar_buy :
X_opt_2 == 'ALMA slope sig' ? alma_slo_up_e :
X_opt_2 == 'SuperTrend sig' ? sup_buy :
X_opt_2 == 'Price X Kijun sig' ? kijun_buy :
X_opt_2 == 'Price X Kumo sig' ? kumo_buy :
X_opt_2 == 'Kumo flip sig' ? kumo_flip_buy :
X_opt_2 == 'Chikou X price sig' ? chikou_X_price_buy :
X_opt_2 == 'Chikou X Kumo sig' ? chikou_X_kumo_buy :
X_opt_2 == 'Price X Tenkan sig' ? price_X_tenkan_buy :
X_opt_2 == 'Tenkan X Kumo sig' ? tenkan_X_kumo_buy :
X_opt_2 == 'Tenkan X Kijun sig' ? tenkan_X_kijun_buy :
X_opt_2 == 'B1/S1 sig' ? buy_strong_B1 :
X_opt_2 == 'B2/S2 sig' ? buy_strong_B2 : na
entry_opt_sig_sell_2 = X_opt_2 == '---' ? na :
X_opt_2 == 'TRIX slope sig' ? trix_sell_s :
X_opt_2 == 'EMA1 x EMA2 sig' ? ema_1x2_sell_s :
X_opt_2 == 'HMA slope sig' ? hma_dn_e :
X_opt_2 == 'DMI ADX-slope sig' ? adx_dn_c :
X_opt_2 == 'DMI ADX mod sig' ? short_1 :
X_opt_2 == 'DMI ADX classic sig' ? short_2 :
X_opt_2 == 'Pin bar sig' ? p_bar_sell :
X_opt_2 == 'Inside bar sig' ? i_bar_sell :
X_opt_2 == 'Outside bar sig' ? o_bar_sell :
X_opt_2 == 'Sandwich bar sig' ? s_bar_sell :
X_opt_2 == 'Bar breakout 1 sig' ? bar_sig_1_sell :
X_opt_2 == 'Bar breakout 2 sig' ? bar_sig_2_sell :
X_opt_2 == 'Higher-low/lower-high bar sig' ? hllh_sell :
X_opt_2 == 'Entry on every bar-open sig' ? open_sell :
X_opt_2 == 'SMA sig' ? sma_sell :
X_opt_2 == 'Fractals sig' ? fr_dnx :
X_opt_2 == 'Reverse fractal sig' ? rev_up_fr_sell :
X_opt_2 == 'MACD(fast) slope sig' ? macd_slope_dn_e :
X_opt_2 == 'RSI50 sig' ? rsi_f_sell :
X_opt_2 == 'Parabolic SAR sig' ? psar_sell :
X_opt_2 == 'ALMA slope sig' ? alma_slo_dn_e :
X_opt_2 == 'SuperTrend sig' ? sup_sell :
X_opt_2 == 'Price X Kijun sig' ? kijun_sell :
X_opt_2 == 'Price X Kumo sig' ? kumo_sell :
X_opt_2 == 'Kumo flip sig' ? kumo_flip_sell :
X_opt_2 == 'Chikou X price sig' ? chikou_X_price_sell :
X_opt_2 == 'Chikou X Kumo sig' ? chikou_X_kumo_sell :
X_opt_2 == 'Price X Tenkan sig' ? price_X_tenkan_sell :
X_opt_2 == 'Tenkan X Kumo sig' ? tenkan_X_kumo_sell :
X_opt_2 == 'Tenkan X Kijun sig' ? tenkan_X_kijun_sell :
X_opt_2 == 'B1/S1 sig' ? sell_strong_S1 :
X_opt_2 == 'B2/S2 sig' ? sell_strong_S2 : na
// buy signal options 1
opt_sig_buy_1 = htf_entr_opt_1 == 'Current' ? entry_opt_sig_buy_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_entr_opt_1 == '5m' ? '5' : htf_entr_opt_1 == '10m' ? '10' : htf_entr_opt_1 == '15m' ? '15' :
htf_entr_opt_1 == '30m' ? '30' : htf_entr_opt_1 == '1H' ? '60' : htf_entr_opt_1 == '2H' ? '120' : htf_entr_opt_1 == '3H' ? '180' : htf_entr_opt_1 == '4H' ? '240' :
htf_entr_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '12H' ? '720' : htf_entr_opt_1 == 'D' ? 'D' : htf_entr_opt_1 == '3D' ? '3D' : htf_entr_opt_1 == 'W' ? 'W' :
htf_entr_opt_1 == 'M' ? 'M' : na, entry_opt_sig_buy_1)
opt_sig_buy_11 = X_opt == 'Grid - counter trend sig (no tf filter)' ? grid_ct_buy :
X_opt == 'Grid - reentry sig (no tf filter)' ? grid_re_buy :
X_opt == 'Fractals trend lines sig (no tf filter)' ? buy_up_line :
X_opt == 'Segments sig (no tf filter)' ? segments_buy :
X_opt == 'CB/CS sig (no tf filter)' ? long_c[repaint == 'Allowed' ? 0 : 1] :
X_opt == 'IB/IS sig (no tf filter)' ? long_pic[repaint == 'Allowed' ? 0 : 1] : na
// sell signal options 1
opt_sig_sell_1 = htf_entr_opt_1 == 'Current' ? entry_opt_sig_sell_1[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_entr_opt_1 == '5m' ? '5' : htf_entr_opt_1 == '10m' ? '10' : htf_entr_opt_1 == '15m' ? '15' :
htf_entr_opt_1 == '30m' ? '30' : htf_entr_opt_1 == '1H' ? '60' : htf_entr_opt_1 == '2H' ? '120' : htf_entr_opt_1 == '3H' ? '180' : htf_entr_opt_1 == '4H' ? '240' :
htf_entr_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '12H' ? '720' : htf_entr_opt_1 == 'D' ? 'D' : htf_entr_opt_1 == '3D' ? '3D' : htf_entr_opt_1 == 'W' ? 'W' :
htf_entr_opt_1 == 'M' ? 'M' : na, entry_opt_sig_sell_1)
opt_sig_sell_11 = X_opt == 'Grid - counter trend sig (no tf filter)' ? grid_ct_sell :
X_opt == 'Grid - reentry sig (no tf filter)' ? grid_re_sell :
X_opt == 'Fractals trend lines sig (no tf filter)' ? sell_dn_line :
X_opt == 'Segments sig (no tf filter)' ? segments_sell :
X_opt == 'CB/CS sig (no tf filter)' ? short_c[repaint == 'Allowed' ? 0 : 1] :
X_opt == 'IB/IS sig (no tf filter)' ? short_pic[repaint == 'Allowed' ? 0 : 1] : na
// buy signal options 2
opt_sig_buy_2 = htf_entr_opt_2 == 'Current' ? entry_opt_sig_buy_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_entr_opt_2 == '5m' ? '5' : htf_entr_opt_2 == '10m' ? '10' : htf_entr_opt_2 == '15m' ? '15' :
htf_entr_opt_2 == '30m' ? '30' : htf_entr_opt_2 == '1H' ? '60' : htf_entr_opt_2 == '2H' ? '120' : htf_entr_opt_2 == '3H' ? '180' : htf_entr_opt_2 == '4H' ? '240' :
htf_entr_opt_2 == '6H' ? '360' : htf_entr_opt_2 == '12H' ? '720' : htf_entr_opt_2 == 'D' ? 'D' : htf_entr_opt_2 == '3D' ? '3D' : htf_entr_opt_2 == 'W' ? 'W' :
htf_entr_opt_2 == 'M' ? 'M' : na, entry_opt_sig_buy_2)
opt_sig_buy_22 = X_opt_2 == 'Grid - counter trend sig (no tf filter)' ? grid_ct_buy :
X_opt_2 == 'Grid - reentry sig (no tf filter)' ? grid_re_buy :
X_opt_2 == 'Fractals trend lines sig (no tf filter)' ? buy_up_line :
X_opt_2 == 'Segments sig (no tf filter)' ? segments_buy :
X_opt_2 == 'CB/CS sig (no pyr, no tf filter)' ? long_c[repaint == 'Allowed' ? 0 : 1] :
X_opt_2 == 'IB/IS sig (no pyr, no tf filter)' ? long_pic[repaint == 'Allowed' ? 0 : 1] : na
// sell signal options 2
opt_sig_sell_2 = htf_entr_opt_2 == 'Current' ? entry_opt_sig_sell_2[repaint == 'Allowed' ? 0 : 1] :
f_secureSecurity(syminfo.tickerid,
htf_entr_opt_2 == '5m' ? '5' : htf_entr_opt_2 == '10m' ? '10' : htf_entr_opt_2 == '15m' ? '15' :
htf_entr_opt_2 == '30m' ? '30' : htf_entr_opt_2 == '1H' ? '60' : htf_entr_opt_2 == '2H' ? '120' : htf_entr_opt_2 == '3H' ? '180' : htf_entr_opt_2 == '4H' ? '240' :
htf_entr_opt_2 == '6H' ? '360' : htf_entr_opt_2 == '12H' ? '720' : htf_entr_opt_2 == 'D' ? 'D' : htf_entr_opt_2 == '3D' ? '3D' : htf_entr_opt_2 == 'W' ? 'W' :
htf_entr_opt_2 == 'M' ? 'M' : na, entry_opt_sig_sell_2)
opt_sig_sell_22 = X_opt_2 == 'Grid - counter trend sig (no tf filter)' ? grid_ct_sell :
X_opt_2 == 'Grid - reentry sig (no tf filter)' ? grid_re_sell :
X_opt_2 == 'Fractals trend lines sig (no tf filter)' ? sell_dn_line :
X_opt_2 == 'Segments sig (no tf filter)' ? segments_sell :
X_opt_2 == 'CB/CS sig (no tf filter)' ? short_c[repaint == 'Allowed' ? 0 : 1] :
X_opt_2 == 'IB/IS sig (no tf filter)' ? short_pic[repaint == 'Allowed' ? 0 : 1] : na
//---------------------------------------------------- Take profit, stop loss and trailing price --------------------------------------------------------
//take profit of average position price
atr_sec = request.security(syminfo.tickerid, atr_tf, ta.atr(atr_l))
atr_calc = atr_sec * atr_fact
tp_step = 0.
tp_step := nz(high > tp_step[1] + atr_calc or low < tp_step[1] - atr_calc ? close : tp_step[1])
tp_step_l = tp_step > tp_step[1]
tp_step_s = tp_step < tp_step[1]
av_profit_l = close - strategy.position_avg_price > atr_calc and tp_step_l
av_profit_s = strategy.position_avg_price - close > atr_calc and tp_step_s
//stop loss of average position price
atr_sec_l = request.security(syminfo.tickerid, atr_tf_l, ta.atr(atr_l_l))
atr_calc_l = atr_sec_l * atr_fact_l
sl_step = 0.
sl_step := nz(high > sl_step[1] + atr_calc_l or low < sl_step[1] - atr_calc_l ? close : sl_step[1])
sl_step_l = sl_step < sl_step[1]
sl_step_s = sl_step > sl_step[1]
sl_t_l = strategy.position_avg_price - close > atr_calc_l and sl_step_l
sl_t_s = close - strategy.position_avg_price > atr_calc_l and sl_step_s
//average position price line
plot(plot_avg_price ? strategy.position_avg_price : na, linewidth=1, color=color.new(color.blue, 30), title='position_avg_price')
//---------------------------------------------------------------- strategy entry / exit -----------------------------------------------------------------
long = entry_type != 'Short' // long or both
short = entry_type != 'Long' // short or both
both = entry_type == 'Both' // both
//exit filter
exit_long_1 = exit_filter_sell_1 or exit_filter_sell_2 or exit_filter_sig_sell_11 or exit_filter_sig_sell_22
exit_short_1 = exit_filter_buy_1 or exit_filter_buy_2 or exit_filter_sig_buy_11 or exit_filter_sig_buy_22
//opposite signal as exit signal
exit_long_2 = opt_sig_sell_1 or opt_sig_sell_2 or opt_sig_sell_11 or opt_sig_sell_22
exit_short_2 = opt_sig_buy_1 or opt_sig_buy_2 or opt_sig_buy_11 or opt_sig_buy_22
//long entry conditions for the 1st and the 2nd entry signal
entry_long_1 = (opt_sig_buy_11 or opt_sig_buy_1) and entry_filter_buy_1 and entry_filter_buy_2 and entry_filter_buy_11 and entry_filter_buy_22 and not exit_long_1
entry_long_2 = (opt_sig_buy_22 or opt_sig_buy_2) and entry_filter_buy_1 and entry_filter_buy_2 and entry_filter_buy_11 and entry_filter_buy_22 and not exit_long_1
//short entry conditions for the 1st and the 2nd entry signal
entry_short_1 = (opt_sig_sell_11 or opt_sig_sell_1) and entry_filter_sell_1 and entry_filter_sell_2 and entry_filter_sell_11 and entry_filter_sell_22 and not exit_short_1
entry_short_2 = (opt_sig_sell_22 or opt_sig_sell_2) and entry_filter_sell_1 and entry_filter_sell_2 and entry_filter_sell_11 and entry_filter_sell_22 and not exit_short_1
if backtest_period()
if long
if entry_long_1
strategy.entry('os_b', strategy.long) // 1st entry signal
if one_side_pyr and entry_long_2
strategy.entry('os_b', strategy.long) // 2nd entry signal when in pyramiding mode
if not both and not one_side_pyr ? exit_long_2 : exit_long_1
strategy.close('os_b') // opposite signal or exit-filter signal exit
if not both and one_side_pyr ? exit_long_1 and not exit_long_1[1] : na
strategy.close('os_b') // exit-filter exit
if av_tp_en and av_profit_l
strategy.close('os_b', qty_percent= av_tp_qty) // average take profit
if sl_en and sl_t_l
strategy.close('os_b', qty_percent= av_sl_qty) // average stop loss
if short
if entry_short_1
strategy.entry('os_s', strategy.short)
if one_side_pyr and entry_short_2
strategy.entry('os_s', strategy.short)
if not both and not one_side_pyr ? exit_short_2 : exit_short_1
strategy.close('os_s')
if not both and one_side_pyr ? exit_short_1 and not exit_short_1[1] : na
strategy.close('os_s')
if av_tp_en and av_profit_s
strategy.close('os_s', qty_percent= av_tp_qty)
if sl_en and sl_t_s
strategy.close('os_s', qty_percent= av_sl_qty)
//alert messages - same conditions like strategy....() - live trading
if long and entry_long_1 or
long and (one_side_pyr ? entry_long_2 : na)
alert(message= 'BybitAPI(BTCUSD) { continue(if=positionShort); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=buy, amount=' + str.tostring(lot_size) + '); } \n #bot',
freq= alert.freq_once_per_bar)
if short and entry_short_1 or
short and (one_side_pyr ? entry_short_2 : na)
alert(message= 'BybitAPI(BTCUSD) { continue(if=positionLong); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=sell, amount=' + str.tostring(lot_size) + '); } \n #bot',
freq= alert.freq_once_per_bar)
if long and (not both and not one_side_pyr ? exit_long_2 : exit_long_1) or
long and (not both and one_side_pyr ? exit_long_1 and not exit_long_1[1] : na) or
short and (not both and not one_side_pyr ? exit_short_2 : exit_short_1) or
short and (not both and one_side_pyr ? exit_short_1 and not exit_short_1[1] : na)
alert(message= 'BybitAPI(BTCUSD) { market(position= 0 %p); } \n #bot', freq= alert.freq_once_per_bar)
var float av_tp_qty_var = 100 - av_tp_qty // calc because of alertatron syntax string
var float av_sl_qty_var = 100 - av_sl_qty
if long and (av_tp_en ? av_profit_l : na) or
short and (av_tp_en ? av_profit_s : na)
alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(av_tp_qty_var) + '%p); } \n #bot', freq= alert.freq_once_per_bar)
if long and (sl_en ? sl_t_l : na) or
short and (sl_en ? sl_t_s : na)
alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(av_sl_qty_var) + '%p); } \n #bot', freq= alert.freq_once_per_bar)
|
EMA_cumulativeVolume_crossover[Strategy] | https://www.tradingview.com/script/Xwlq5xrB-EMA-cumulativeVolume-crossover-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 152 | 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("EMA_cumulativeVolume_crossover[Strategy]", overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000)
emaLength= input(50, title="EMA Length", minval=1, maxval=200)
cumulativePeriod = input(100, title="cumulative volume Period", minval=1, maxval=200)
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(8,title="Stop Loss",minval=1)
takePartialProfits=input(false, title="take partial profits (percentage same as stop loss)")
tradeDirection=input(title="Trade Direction", defval="LONG", options=["LONG", "SHORT"])
avgPrice = (high + low + close) / 3
avgPriceVolume = avgPrice * volume
cumulPriceVolume = sum(avgPriceVolume, cumulativePeriod)
cumulVolume = sum(volume, cumulativePeriod)
vwapValue = cumulPriceVolume / cumulVolume
emaVal=ema(close, emaLength)
plot(emaVal, title="EMA", color=color.green, transp=25)
plot(vwapValue, title="Cumulate Volumne / VWAP", color=color.orange, linewidth=2, transp=25)
bgcolor(emaVal>vwapValue?color.blue:color.purple)
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
strategy.entry(id="LE",comment="LE", long=true, qty=qty1, when=crossover(emaVal, vwapValue) and (tradeDirection=="LONG") ) //emaVal>vwapValue and crossover(close , emaVal)
//stoploss
stopLossVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//draw initil stop loss
plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
//partial exits
takeProfit= strategy.position_size>=1 ? (strategy.position_avg_price * (1+(stopLoss*0.01) )) : ( close[1] * 2 )
if(takePartialProfits==true)
strategy.close(id="LE", comment="Partial"+tostring(close-strategy.position_avg_price, "###.##") , qty=strategy.position_size/3 , when = (tradeDirection=="LONG" ) and close>takeProfit and crossunder(close, emaVal) ) //close<close[1] and close[1]<close[2] and close[2]<close[3])
strategy.close(id="LE" , comment="LE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when=crossunder(emaVal, vwapValue) and (tradeDirection=="LONG") )
strategy.close(id="LE" , comment="SL Exit Loss="+tostring(close-strategy.position_avg_price, "###.##"), when= close < stopLossVal and (tradeDirection=="LONG") )
//for short you dont have to wait crossodown of ema, falling is speed , so just check if close crossing down vwapVal
strategy.entry(id="SE",comment="SE", long=false, qty=qty1, when=(close<vwapValue and close<open and close[1] < vwapValue and close[1]<open[1] and close<close[1]) and emaVal>=vwapValue and (tradeDirection=="SHORT") ) //emaVal>vwapValue and crossover(close , emaVal)
//stoploss
stopLossValUpside= abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? (strategy.position_avg_price * (1+(stopLoss*0.01) )) : 0.00
//draw initil stop loss
plot(abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? stopLossValUpside : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
//partial exits
shortTakeProfit= abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
if(takePartialProfits==true)
strategy.close(id="SE", comment="Partial" , qty=strategy.position_size/3 , when = (tradeDirection=="SHORT" ) and close<shortTakeProfit ) //close<takeProfit and (emaVal - close)>8 )
//strategy.close(id="SE" , comment="SE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when=crossover(emaVal, vwapValue) and (tradeDirection=="SHORT") )
strategy.close(id="SE" , comment="SE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when= abs(strategy.position_size)>=1 and ( (emaVal<vwapValue and close>vwapValue and open>vwapValue and close>open ) or (crossover(emaVal,vwapValue)) ) and (tradeDirection=="SHORT") )
strategy.close(id="SE" , comment="SL Exit Loss="+tostring(close-strategy.position_avg_price, "###.##"), when= abs(strategy.position_size)>=1 and close > stopLossValUpside and (tradeDirection=="SHORT" ) )
|
Price action strategy FOREX with amazing results | https://www.tradingview.com/script/66n9XaEf-Price-action-strategy-FOREX-with-amazing-results/ | SoftKill21 | https://www.tradingview.com/u/SoftKill21/ | 215 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SoftKill21
//@version=4
strategy("CLOSE HIGH T3",overlay=true)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2020, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
timeinrange(res, sess) => time(res, sess) != 0
Length = input(9, minval=1)
xPrice = close
xe1 = ema(xPrice, Length)
xe2 = ema(xe1, Length)
xe3 = ema(xe2, Length)
xe4 = ema(xe3, Length)
xe5 = ema(xe4, Length)
xe6 = ema(xe5, Length)
b = 0.7
c1 = -b*b*b
c2 = 3*b*b+3*b*b*b
c3 = -6*b*b-3*b-3*b*b*b
c4 = 1+3*b+b*b*b+3*b*b
nT3Average = c1 * xe6 + c2 * xe5 + c3 * xe4 + c4 * xe3
plot(nT3Average, color=color.blue, title="T3")
myspecifictradingtimes = input('1000-1900', type=input.session, title="My Defined Hours")
//myspecifictradingtimes2 = input('1000-1900', type=input.session, title="My Defined Hours")
exittime = input('2100-2115', type=input.session, title="exit time")
optionmacd=true
entrytime = time(timeframe.period, myspecifictradingtimes) != 0
exiton = time(timeframe.period, exittime) != 0
//entrytime2 = time(timeframe.period, myspecifictradingtimes2) != 0
// long =time_cond and (entrytime or entrytime2) and close > high[1] and close > nT3Average
// short =time_cond and (entrytime or entrytime2) and close < low[1] and close < nT3Average
long =time_cond and (entrytime ) and close > high[1] and close > nT3Average
short =time_cond and (entrytime) and close < low[1] and close < nT3Average
tp = input(0.01)
sl = input(0.01)
modified=input(true)
inverse=input(true)
exit = input(false)
if(modified)
if(not exiton)
if(inverse)
strategy.entry("long",1,when=short)
strategy.entry("short",0,when=long)
/// strategy.exit("xlong","long",profit=200, loss=200)
// strategy.exit("xshort","short",profit=200, loss=200)
if(inverse==false)
strategy.entry("long",1,when=long)
strategy.entry("short",0,when=short)
if(exit)
// strategy.close("long", when = crossover(close,nT3Average))
// strategy.close("short", when = crossunder(close,nT3Average))
strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong")
strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
if(modified==false)
if(inverse)
strategy.entry("long",1,when=short)
strategy.entry("short",0,when=long)
/// strategy.exit("xlong","long",profit=200, loss=200)
// strategy.exit("xshort","short",profit=200, loss=200)
if(inverse==false)
strategy.entry("long",1,when=long)
strategy.entry("short",0,when=short)
// if(exit)
// // strategy.close("long", when = crossover(close,nT3Average))
// // strategy.close("short", when = crossunder(close,nT3Average))
strategy.exit("closelong", "long" , loss = close * sl / syminfo.mintick, alert_message = "closelong")
strategy.exit("closeshort", "short" , loss = close * sl / syminfo.mintick, alert_message = "closeshort")
//strategy.close_all(when =exiton )
//gbpnzd 10-20
//gbpcad 10-19
//gbpaud 07-19
//euruad 10-19 / 16-20
//eurnzd 08-21 / 10-20
//eurchf 08-20
//gbpchf 06-18
// 18-19settings entry gbp aud, gbpcad gbpnzd ??? 1 entry only big spread
//test |
MACD 50x Leveraged Short Strategy with Real Equity | https://www.tradingview.com/script/PAdPhuKR-MACD-50x-Leveraged-Short-Strategy-with-Real-Equity/ | Noldo | https://www.tradingview.com/u/Noldo/ | 122 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Noldo
//@version=4
strategy(title="MACD SHORT STRATEGY REAL EQUITY WITH 50X LEVERAGE",shorttitle = "MACD SHORT 50X REAL EQUITY", overlay=true,
initial_capital=100,
linktoseries = false,
default_qty_type=strategy.cash,
default_qty_value=1,
commission_type=strategy.commission.percent,
commission_value=0.0,
calc_on_order_fills = false,
calc_on_every_tick = true,
max_bars_back = 5000,
pyramiding = 0,
precision = 3)
// Variables
src = close
fromyear = input(2016, defval = 2009, minval = 2000, maxval = 2100, title = "From Year")
toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
frommonth = input(04, defval = 04, minval = 01, maxval = 12, title = "From Month")
tomonth = input(12, defval = 12, minval = 01, maxval = 12, title = "To Month")
fromday = input(01, defval = 01, minval = 01, maxval = 31, title = "From day")
today = input(31, defval = 31, minval = 01, maxval = 31, title = "To day")
term = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59))
// STRATEGY COMPONENTS
// SL values
// STOP VALUE ==>
//The 50x leverage explodes at just 2% above the current entry price and the current position size melts.
//2% below the entry price is determined as the liquidation point so that the transaction is guaranteed.
stop_value = valuewhen(strategy.position_size != 0 and strategy.position_size[1] == 0,strategy.position_avg_price * 1.02 , 0)
//
// LEVERAGE ==> 50X
leverage = 50
// POSITION SIZE ==> %1 (0.01)
possize = 1
// MACD
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ema(close, fastLength) - ema(close, slowlength)
aMACD = ema(MACD, MACDLength)
delta = MACD - aMACD
// STRATEGY
if (crossunder(delta, 0) and term)
strategy.entry("MacdSE",strategy.short,qty = possize)
if (crossover(delta, 0) and term)
strategy.close("MacdSE", true, comment="CLOSE")
if(high >= stop_value and delta < 0 and term )
strategy.close("MacdSE",true)
if time > timestamp(toyear, tomonth, today, 23, 59)
strategy.close_all()
// REAL LEVERAGE SIMULATION ---
_longmovement = strategy.position_size != 0 and strategy.position_size[1] == 0
_exitmovement = strategy.position_size[1] != 0 and strategy.position_size == 0
// MODE : Indicating a situation for winners and losers, just like in the martingale system, to know if the strategy is losing or gaining.
float mode = na
mode := change(strategy.wintrades) > 0 ? 1 : change(strategy.losstrades) > 0 ? -1 : nz(mode[1], 1)
float capital = 0.00
chg = change(strategy.position_size)
_b = valuewhen(_longmovement,strategy.position_avg_price,0)
_s = valuewhen(_exitmovement,open,0)
pips = ((_s - _b) / _b) * 100
//If we are in profit, how much will this affect all of our capital with leverage?
//If we are already at a loss, all of our position size will be gone.
// Now let's put this into expression :
capital := _longmovement ? nz(capital[1], 0) + chg : _exitmovement and mode == 1 ? (capital[1] + chg) + ((-chg * leverage * pips)/100) :
_exitmovement and mode != 1 ? capital[1] : capital[1]
// NET CAPITAL
capita = 100 + capital
float netcapital = na
netcapital := netcapital[1] <= 0 ? 0 : capita
// Now, if we are ready, it's time to see the facts:
//If we had made a strategy using 1% position size and 50x leverage, that is, our entry point would be less than 2% liquidation point, the change in our capital would be in the form of a blue-colored area.
//The result are still not good.
// The first moment we switch to - is the moment we run out of cash and the game is over.
// NOTE: It is recommended to use as chart bottom indicator.
plot(netcapital , color = color.teal , linewidth = 2)
|
HTF High/Low Repaint Strategy | https://www.tradingview.com/script/5FvIVVS2-HTF-High-Low-Repaint-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 660 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
//@version=4
strategy("HTF High/Low Repaint Strategy", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)
i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time)
i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time)
inDateRange = time >= i_startTime and time <= i_endTime
resolution = input("3M", type=input.resolution)
HTFMultiplier = input(22, minval=1, step=1)
offset = input(0, minval=0, step=1)
lookahead = input(true)
gaps = false
f_secureSecurity_on_on(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_on)
f_secureSecurity_on_off(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on, gaps=barmerge.gaps_off)
f_secureSecurity_off_on(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_off, gaps=barmerge.gaps_on)
f_secureSecurity_off_off(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_off, gaps=barmerge.gaps_off)
f_multiple_resolution(HTFMultiplier) =>
target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 7. * 24. * 60. :
timeframe.ismonthly ? 30.417 * 24. * 60. : na)
target_Res_In_Min <= 0.0417 ? "1S" :
target_Res_In_Min <= 0.167 ? "5S" :
target_Res_In_Min <= 0.376 ? "15S" :
target_Res_In_Min <= 0.751 ? "30S" :
target_Res_In_Min <= 1440 ? tostring(round(target_Res_In_Min)) :
tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"
f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset)=>
derivedResolution = resolution == ""?f_multiple_resolution(HTFMultiplier):resolution
nhigh_on_on = f_secureSecurity_on_on(syminfo.tickerid, derivedResolution, high, offset)
nlow_on_on = f_secureSecurity_on_on(syminfo.tickerid, derivedResolution, low, offset)
nhigh_on_off = f_secureSecurity_on_off(syminfo.tickerid, derivedResolution, high, offset)
nlow_on_off = f_secureSecurity_on_off(syminfo.tickerid, derivedResolution, low, offset)
nhigh_off_on = f_secureSecurity_off_on(syminfo.tickerid, derivedResolution, high, offset)
nlow_off_on = f_secureSecurity_off_on(syminfo.tickerid, derivedResolution, low, offset)
nhigh_off_off = f_secureSecurity_off_off(syminfo.tickerid, derivedResolution, high, offset)
nlow_off_off = f_secureSecurity_off_off(syminfo.tickerid, derivedResolution, low, offset)
nhigh = lookahead and gaps ? nhigh_on_on :
lookahead and not gaps ? nhigh_on_off :
not lookahead and gaps ? nhigh_off_on :
not lookahead and not gaps ? nhigh_off_off : na
nlow = lookahead and gaps ? nlow_on_on :
lookahead and not gaps ? nlow_on_off :
not lookahead and gaps ? nlow_off_on :
not lookahead and not gaps ? nlow_off_off : na
[nhigh, nlow]
[nhigh, nlow] = f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset)
[nhighlast, nlowlast] = f_get_htfHighLow(resolution, HTFMultiplier, lookahead, gaps, offset+1)
plot(nhigh , title="HTF High",style=plot.style_circles, color=color.green, linewidth=1)
plot(nlow , title="HTF Low",style=plot.style_circles, color=color.red, linewidth=1)
buyCondition = nhigh > nhighlast and nlow > nlowlast
sellCondition = nhigh < nhighlast and nlow < nlowlast
strategy.entry("Buy", strategy.long, when= buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.cancel)
strategy.entry("Sell", strategy.short, when= sellCondition and inDateRange, oca_name="oca_sell", oca_type=strategy.oca.cancel)
|
Double EMA CROSS | https://www.tradingview.com/script/mVplGpsd-Double-EMA-CROSS/ | EmreErturk_ | https://www.tradingview.com/u/EmreErturk_/ | 361 | 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/
// Double EMA CROSS By © EmreE (Emre Ertürk) Also thx for KivancOzbilgic color based bars
//@version=4
strategy(title="Double EMA CROSS", shorttitle="DEC", overlay=true)
matype = input("ema")
hidema = input(false)
sourcetype = input(close, title="Source Type")
source=close
// STEP 1:
// Configure backtest start date with inputs
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=231)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2020, minval=1800, maxval=2100)
// STEP 2:
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone,
startYear, startMonth, startDate, 0, 0))
fast = input(25, title="Fast")
slow = input(75, title="Slow")
matype1=ema(source, fast)
matype2=ema(source, slow)
signalcolor = source > matype2 ? color.blue : color.red
signal = cross(fast, slow)
hizliema=plot(hidema ? na : matype1, color=color.green, linewidth=2,transp=0, title="Fast EMA")
yavasema=plot(hidema ? na : matype2, color=color.red, linewidth=2,transp=0, title="Slow EMA")
//kesisme=plot(signal, style=cross, color=signalcolor, linewidth=5, title="Kesişme")
longCondition = crossover(matype1, matype2)
if (afterStartDate and longCondition)
strategy.entry("Long", strategy.long)
shortCondition = crossunder(matype1, matype2)
if (afterStartDate and shortCondition)
strategy.entry("Short", strategy.short)
//--------------------------------------------------------
//volume based color bars
length=input(21, "length", minval=1)
avrg=sma(volume,length)
vold1 = volume > avrg*1.5 and close<open
vold2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close<open
vold3 = volume < avrg *0.5 and close<open
volu1 = volume > avrg*1.5 and close>open
volu2 = volume >= avrg*0.5 and volume<=avrg*1.5 and close>open
volu3 = volume< avrg*0.5 and close>open
cold1=#800000
cold2=#FF0000
cold3=color.orange
colu1=#006400
colu2=color.lime
colu3=#7FFFD4
ac = vold1 ? cold1 : vold2 ? cold2 : vold3 ? cold3 : volu1 ? colu1 : volu2 ? colu2 : volu3 ? colu3 : na
barcolor(ac) |
Buy-and-hold strategy stats | https://www.tradingview.com/script/ZfPn3wG2-Buy-and-hold-strategy-stats/ | TradersForecast | https://www.tradingview.com/u/TradersForecast/ | 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/
// © TradersForecast
//@version=4
strategy("Buy-and-hold strategy stats", overlay=true, pyramiding=1, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, process_orders_on_close=true)
minDate = input(timestamp("01 Jan 2010 0:0 -0500"), title = "Start Date/Time", type = input.time)
maxDate = input(timestamp("01 Jan 2030 0:0 -0500"), title = "End Date/Time", type = input.time)
revTrd = input(false, title="Short position? (else it defaults to LONG)", type=input.bool)
strategy.close_all()
if time >= minDate and time <= maxDate
strategy.entry("My Long Entry Id", revTrd ? strategy.short : strategy.long)
|
cRSI + Waves Strategy with VWMA overlay | https://www.tradingview.com/script/mcr9VUaB-cRSI-Waves-Strategy-with-VWMA-overlay/ | Dr_Roboto | https://www.tradingview.com/u/Dr_Roboto/ | 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/
// © Dr_Roboto
//
//@version=4
//
// This indicator uses the cyclic smoothed Relative Strength Index (cRSI) instead of the traditional Relative Strength Index (RSI). See below for more info on the benefits to the cRSI.
//
// [b]My key contributions[/b]
// 1) A Weighted Moving Average (WMA) to track the general trend of the cRSI signal. This is very helpful in determining when the equity switches from bullish to bearish, which can be used to determine buy/sell points.
// This is then is used to color the region between the upper and lower cRSI bands (green above, red below).
// 2) An attempt to detect the motive (impulse) and corrective and waves. Corrective waves are indicated A, B, C, D, E, F, G. F and G waves are not technically Elliot Waves, but the way I detect waves it is really hard
// to always get it right. Once and a while you could actually see G and F a second time. Motive waves are identified as s (strong) and w (weak). Strong waves have a peak above the cRSI upper band and weak waves have a peak below the upper band.
// 3) My own divergence indicator for bull, hidden bull, bear, and hidden bear. I was not able to replicate the TradingView style of drawing a line from peak to peak, but for this indicator I think in the end it makes the chart cleaner.
// 4) I have also added "alert conditions" for most of the key events. Select the equity you want (such as: SPX) and the desired timeframe (such as: D).
// Go to the TradingView "Alerts" tab (click the alarm clock icon) --> Create Alert (alarm clock with a +) --> Change the first condition drop down to "Cyclic Smoothed RSI with Motive-Corrective Wave Indicator" --> in the
// drop down below that select the alert that you want (such as: Bull - cRSI Above WMA). You will want to give the alert a good name that includes the ticker name and time frame, for example "SPX 1D: Bull - cRSI above WMA"
//
// There is a latency issue with an indicator like this that is based on moving averages. That means they tend to trigger right after key events. Perfect timing is not possible strictly with these indicators, but they do work
// very well "on average." However, my implementation has minimal latency as peaks (tops/bottoms) only require one bar to detect.
//
// As a bit of an Easter Egg, this code can be tweaked and run as a strategy to get buy/sell signals. I use this code for both my indicator and for trading strategy. Just copy and past it into a new strategy script and just
// change it from study to something like.
// strategy("cRSI + Waves Strategy with VWMA overlay", overlay=overlay)
// The buy/sell code is at the end and just needs to be uncommented. I make no promises or guarantees about how good it is as a strategy, but it gives you some code and ideas to work with.
//
// [b]Tuning[/b]
// 1) Volume Weighted Moving Average (VWMA): This is a “hidden strategy” feature implemented that will display the high-low bands of the VWMA on the price chart if run the code using “overlay = true”.
// - [Use Volume for VWMA] If the equity does not have volume, then the VWMA will not show up. Uncheck this box and it will use the regular WMA (no volume).
// - [VWMA Length] defines how far back the WMA averages price.
//
// 2) cRSI (Black line in the indicator)
// - [CRSI Dominate Cycle Length] Increase to length that amount of time a band (upper/lower) stays high/low after a peak. Reduce the value to shorten the time. Just increment it up/down to see the effect.
// - [CRSI Moving Average Length] defines how far back the SMA averages the cRSI. This affects the purple line in the indicator.
// - [CRSI Top/Bottom Detector Lookback] defines how many bars back the peak detector looks to determine if a peak has occurred. For example, a top is detected like this: current-bar down relative to the 1-bar-back,
// 1-bar-back up relative to 2-bars-back (look back = 1), c) 2-bars-back up relative to 3-bars-back (lookback = 2), and d) 3-bars-back up relative to 4-bars-back (lookback = 3). I hope that makes sense. There are
// only 2 options for this setting: 2 or 3 bars. 2 bars will be able to detect small peaks but create more “false” peaks that may not be meaningful. 3 bars will be more robust but can miss short duration peaks.
//
// 3) Waves
// - The check boxes are self explanatory for which labels they turn on and off on the plot.
//
// 4) Divergence Indicators
// - The check boxes are self explanatory for which labels they turn on and off on the plot.
//
// [b]Hints[/b]
// - The most common parameter to change is the [CRSI Top/Bottom Detector Lookback]. Different stocks will have different levels of strength in their peaks. A setting of 2 may generate too many corrective waves.
// - Different times scales will give you different wave counts. This is to be expected. A conunter impulse wave inside a corrective wave may actually go above the cRSI WMA on a smaller time frame. You may need to increase it one or two levels to see large waves.
// - Just because you see divergence (bear or hidden bear) does not mean a price is going to go down. Often price continues to rise through bears, so take note and that is normal. Bulls are usually pretty good indicators especially if you see them on C,E,G waves.
//
//
// ---------------------------------------
// cyclic smoothed RSI (cRSI) indicator
// ---------------------------------------
// The “core” code for the cyclic smoothed RSI (cRSI) indicator was written by Lars von Theinen and is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/. Copyright (C) 2017 CC BY,
// whentotrade / Lars von Thienen. For more details on the cRSI Indicator: https://www.tradingview.com/script/TmqiR1jp-RSI-cyclic-smoothed-v2/
//
// The cyclic smoothed RSI indicator is an enhancement of the classic RSI, adding
// 1) additional smoothing according to the market vibration,
// 2) adaptive upper and lower bands according to the cyclic memory and
// 3) using the current dominant cycle length as input for the indicator.
// It is much more responsive to market moves than the basic RSI. The indicator uses the dominant cycle as input to optimize signal, smoothing, and cyclic memory. To get more in-depth information on the cyclic-smoothed
// RSI indicator, please read Decoding The Hidden Market Rhythm - Part 1: Dynamic Cycles (2017), Chapter 4: "Fine-tuning technical indicators." You need to derive the dominant cycle as input parameter for the cycle length as described in chapter 4.
//=================================================================================================================================
//=================================================================================================================================
overlay = true // plots VWMA (need to close and re-added)
// overlay = false // plots cRSI (need to close and re-added)
strategy("cRSI + Waves Strategy with VWMA overlay", overlay=overlay, max_bars_back=300)
//=================================================================================================================================
//=================================================================================================================================
// Disables cRSI and VWMA plotting so debug data can be plotted
// DEBUG = true
DEBUG = false
//=================================================================================================================================
//=================================================================================================================================
// Helper Functions
//=================================================================================================================================
//=================================================================================================================================
// function to convert bool to int
b2i(bval) =>
ival = bval ? 1 : 0
// function to look for a price in the lookback that is recently above the current price
recentAbove(in, thresh, lookback) =>
found = false
for i=0 to lookback
if in[i] >= thresh
found := true
break
if found
res = true
else
res = false
// is value rising or falling based on history
isRisingFalling(in, lookback) =>
cntThresh = round(lookback*0.6) // majority = greater than 50%
cntUp = 0
cntDown = 0
rising = false
falling = false
// count up the times it is above or below the current value
for i=1 to lookback
if in[0] > in[i]
cntUp := cntUp + 1
else if in[0] < in[i]
cntDown := cntDown + 1
// rising
if cntUp > cntThresh
rising := true
else
rising := false
// falling
if cntDown > cntThresh
falling := true
else
falling := false
// flat
flat = not(rising) and not(falling)
// if flat, then select preivous value for rising and falling
if flat
rising := rising[1]
falling := falling[1]
// return tuple
[rising,falling,flat]
// Do the last several prices form a top
isTop(price, lookback) =>
if lookback == 3
// 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals
// up->up->down
if (price[2] > price[3]) and (price[1] > price[2]) and (price[0] < price[1])
top = true
else
top = false
else
// 2 places back
// up->down
if (price[1] > price[2]) and (price[0] < price[1])
top = true
else
top = false
// Do the last several prices form a bottom
isBottom(price, lookback) =>
if lookback == 3
// 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals
// down->down->up
if (price[2] < price[3]) and (price[1] < price[2]) and (price[0] > price[1])
bottom = true
else
bottom = false
else
// 2 prices back
// down->up
if (price[1] < price[2]) and (price[0] > price[1])
bottom = true
else
bottom = false
// function to filter multiple signals in a row
filterSignal(signalFlag, lookback) =>
signalFlagFilt = signalFlag
for i = 1 to lookback
signalFlagFilt := signalFlagFilt[0] == true and signalFlagFilt[i] == true ? false : signalFlagFilt
//=================================================================================================================================
//=================================================================================================================================
// Price Movement
//=================================================================================================================================
//=================================================================================================================================
priceRising = close[0] >= close[1] and close[1] >= close[2]
priceFalling = close[0] <= close[1] and close[1] <= close[2]
// plot(priceRising?1.0:0,color=color.green)
// plot(priceFalling?1.0:0,color=color.red)
//=================================================================================================================================
//=================================================================================================================================
// Volume Weighted Moving Average (VWMA)
//=================================================================================================================================
//=================================================================================================================================
plotVWMA = overlay and not(DEBUG)
// check if volume is available for this equity
useVolume = input(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true)
vwmaLen = input(defval=21, title="VWMA Length", type=input.integer, minval=1, maxval=200)
vwma = vwma(close, vwmaLen)
vwma_high = vwma(high, vwmaLen)
vwma_low = vwma(low, vwmaLen)
if not(useVolume)
vwma := wma(close, vwmaLen)
vwma_high := wma(high, vwmaLen)
vwma_low := wma(low, vwmaLen)
// +1 when above, -1 when below, 0 when inside
vwmaSignal(priceOpen, priceClose, vwmaHigh, vwmaLow) =>
sig = 0
color = color.gray
if priceClose > vwmaHigh
sig := 1
color := color.green
else if priceClose < vwmaLow
sig := -1
color := color.red
else
sig := 0
color := color.gray
[sig,color]
[vwma_sig, vwma_color] = vwmaSignal(open, close, vwma_high, vwma_low)
priceAboveVWMA = vwma_sig == 1 ? true : false
priceBelowVWMA = vwma_sig == -1 ? true : false
// plot(priceAboveVWMA?2.0:0,color=color.blue)
// plot(priceBelowVWMA?2.0:0,color=color.maroon)
// bandTrans = input(defval=70, title="VWMA Band Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100)
// fillTrans = input(defval=70, title="VWMA Fill Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100)
bandTrans = 70
fillTrans = 70
// ***** Plot VWMA *****
highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = vwma_color, linewidth=1, transp=bandTrans)
lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = vwma_color, linewidth=1, transp=bandTrans)
fill(lowband, highband, title='VWMA Band fill', color=vwma_color, transp=fillTrans)
plot(plotVWMA?vwma:na, title='VWMA', color = vwma_color, linewidth=3, transp=0)
//=================================================================================================================================
//=================================================================================================================================
// Moving Average (VWMA)
//=================================================================================================================================
//=================================================================================================================================
smaLineWidth = 8
smaLen1 = input(defval=50, title="SMA #1 Length", type=input.integer, minval=1, maxval=200)
plot(sma(close,smaLen1), title='SMA', color = color.blue, linewidth=smaLineWidth)
smaLen2 = input(defval=100, title="SMA #2 Length", type=input.integer, minval=1, maxval=200)
plot(sma(close,smaLen2), title='SMA', color = color.black, linewidth=smaLineWidth)
//=================================================================================================================================
//=================================================================================================================================
// Moving Average Convergence Divergence (MACD)
//=================================================================================================================================
//=================================================================================================================================
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
// Is the histogram rising or falling
histLineRising = histLine[0] >= histLine[1] and histLine[1] >= histLine[2]
histLineFalling = histLine[0] <= histLine[1] and histLine[1] <= histLine[2]
// Did the histogram cross over zero
histLineCrossNeg2Pos = histLine[0] >= 0.0 and histLine[1] < 0.0
histLineCrossPos2Neg = histLine[0] <= 0.0 and histLine[1] > 0.0
// plot(histLineRising?1.0:0,color=color.green)
// plot(histLineFalling?1.0:0,color=color.red)
// plot(histLineCrossNeg2Pos?1.0:0,color=color.green)
// plot(histLineCrossPos2Neg?1.0:0,color=color.red)
//=================================================================================================================================
//=================================================================================================================================
// Cyclic Smoothed Relative Strength Index (cRSI)
//=================================================================================================================================
//=================================================================================================================================
plotCRSI = not(overlay) and not(DEBUG)
//src = input(title="cRSI Source", defval=close)
src = close
domcycle = input(10, minval=5, title="cRSI Dominant Cycle Length (persist after high/low)") //12
crsi = 0.0
cyclelen = domcycle / 2
vibration = 10
leveling = 10.0
cyclicmemory = domcycle * 2
//set min/max ranges?
torque = 2.0 / (vibration + 1)
phasingLag = (vibration - 1) / 2.0
up = rma(max(change(src), 0), cyclelen)
down = rma(-min(change(src), 0), cyclelen)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1])
// there is a bug that can cause the lower bound to be bigger than the upper bound with a value of 999999.0
// lmax = -999999.0
// lmin = 999999.0
lmax = 0.0 // don't konw why, but this fixes the bug
lmin = 0.0
for i = 0 to cyclicmemory - 1 by 1
if nz(crsi[i], -999999.0) > lmax
lmax := nz(crsi[i])
lmax
else
if nz(crsi[i], 999999.0) < lmin
lmin := nz(crsi[i])
lmin
mstep = (lmax - lmin) / 100
aperc = leveling / 100
crsiLowband = 0.0
for steps = 0 to 100 by 1
testvalue = lmin + mstep * steps
above = 0
below = 0
for m = 0 to cyclicmemory - 1 by 1
below := below + iff(crsi[m] < testvalue, 1, 0)
below
ratio = below / cyclicmemory
if ratio >= aperc
crsiLowband := testvalue
break
else
continue
crsiHighband = 0.0
for steps = 0 to 100 by 1
testvalue = lmax - mstep * steps
above = 0
for m = 0 to cyclicmemory - 1 by 1
above := above + iff(crsi[m] >= testvalue, 1, 0)
above
ratio = above / cyclicmemory
if ratio >= aperc
crsiHighband := testvalue
break
else
continue
//=================================================================================================================================
//=================================================================================================================================
// cRSI moving average
//=================================================================================================================================
//=================================================================================================================================
crsiMaLen = input(title="cRSI Moving Average Length", defval=50, minval=0, step=5, type=input.integer)
// crsiSMA = sma(crsi,crsiMaLen)
// crsiEMA = ema(crsi,crsiMaLen)
crsiWMA = wma(crsi,crsiMaLen)
// plot(crsiSMA, "CRSI SMA", color.red, linewidth=2)
// plot(crsiEMA, "CRSI EMA", color.green, linewidth=2)
// plot(crsiWMA, "CRSI WMA", color.fuchsia, linewidth=2)
//=================================================================================================================================
//=================================================================================================================================
// cRSI Feature Analysis
//=================================================================================================================================
//=================================================================================================================================
// Crossing of upper band
crsiAboveHighband = crsi >= crsiHighband
crsiBelowHighband = not(crsiAboveHighband)
crsiCrossAboveHighband = crsiAboveHighband[0] and crsiBelowHighband[1] ? true : false
crsiCrossBelowHighband = crsiBelowHighband[0] and crsiAboveHighband[1] ? true : false
// plot(crsiAboveHighband?2.0:0,color=color.black)
// plot(crsiBelowHighband?2.25:0,color=color.red)
// plot(crsiCrossAboveHighband?2.5:0,color=color.green)
// plot(crsiCrossBelowHighband?2.75:0,color=color.blue)
//-----------------------------------------------------------------------------
// Crossing of lower band
crsiAboveLowband = crsi >= crsiLowband
crsiBelowLowband = not(crsiAboveLowband)
crsiCrossAboveLowband = crsiAboveLowband[0] and crsiBelowLowband[1] ? true : false
crsiCrossBelowLowband = crsiBelowLowband[0] and crsiAboveLowband[1] ? true : false
// plot(crsiAboveLowband?1.0:0,color=color.black)
// plot(crsiBelowLowband?1.25:0,color=color.red)
// plot(crsiCrossAboveLowband?1.5:0,color=color.green)
// plot(crsiCrossBelowLowband?1.75:0,color=color.blue)
//-----------------------------------------------------------------------------
// Crossing of WMA
crsiAboveWMA = crsi >= crsiWMA
crsiBelowWMA = not(crsiAboveWMA)
crsiCrossAboveWMA = crsiAboveWMA[0] and crsiBelowWMA[1] ? true : false
crsiCrossBelowWMA = crsiBelowWMA[0] and crsiAboveWMA[1] ? true : false
// plot(crsiAboveWMA?1.0:0,color=color.black)
// plot(crsiBelowWMA?1.25:0,color=color.red)
// plot(crsiCrossAboveWMA?1.5:0,color=color.blue)
// plot(crsiCrossBelowWMA?1.75:0,color=color.maroon)
//-----------------------------------------------------------------------------
// Crossing of 50 level
crsiAbove50 = crsi >= 50
crsiBelow50 = not(crsiAbove50)
crsiCrossAbove50 = crsiAbove50[0] and crsiBelow50[1] ? true : false
crsiCrossBelow50 = crsiBelow50[0] and crsiAbove50[1] ? true : false
//-----------------------------------------------------------------------------
// CRSI falling or rising
crsiRising = crsi[0] >= crsi[1]
crsiFalling = crsi[0] < crsi[1]
// plot(crsiRising?3.0:0,color=color.green)
// plot(crsiFalling?3.0:0,color=color.red)
//-----------------------------------------------------------------------------
// Compare cRSI to crsiWMA to determine if equity is bullish (motive) or bearish (corrective)
bull = crsiAboveWMA
bear = not(bull)
bullBearColor = bull ? color.green : color.red
bullStart = bull[0] and bear[1] ? true : false
bearStart = bear[0] and bull[1] ? true : false
alertcondition(bullStart, title='Bull - cRSI above WMA', message='Bull - cRSI above WMA')
alertcondition(bearStart, title='Bear - cRSI below WMA', message='Bear - cRSI below WMA')
//=================================================================================================================================
//=================================================================================================================================
// Plot cRSI colored by Bull or Bear
//=================================================================================================================================
//=================================================================================================================================
// Basic RSI
hline(plotCRSI?50:na, title="Middle Line", linestyle=hline.style_dashed, linewidth=2)
h2 = hline(plotCRSI?70:na, title="Overbought", linestyle=hline.style_dashed, linewidth=2)
h1 = hline(plotCRSI?30:na, title="Oversold", linestyle=hline.style_dashed, linewidth=2)
fill(h1, h2, color=color.silver, transp=80)
// cRSI
crsiLB2 = plot(plotCRSI?crsiLowband:na, "cRSI LowBand", bullBearColor)
crsiHB2 = plot(plotCRSI?crsiHighband:na, "cRSI HighBand", bullBearColor)
fill(crsiLB2, crsiHB2, bullBearColor, transp=75)
plot(plotCRSI?crsiWMA:na, "CRSI WMA", color.fuchsia, linewidth=2)
plot(plotCRSI?crsi:na, "CRSI", color.black, linewidth=4)
//=================================================================================================================================
//=================================================================================================================================
// Moitve (impulse) and Corrective Waves
//=================================================================================================================================
//=================================================================================================================================
// THIS IS A MAJOR ASSUMPTION TO THIS APPROACH!!!
motiveWave = bull
correctiveWave = bear
// TOP AND BOTTOM ARE DETECTED ONE BAR LATE!!!
topBottomLookback = input(title="cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller)", defval=2, minval=2, maxval=3, step=1, type=input.integer)
crsiTop = isTop(crsi, topBottomLookback)
crsiBottom = isBottom(crsi,topBottomLookback)
// Top above high band
crsiTopAboveHighband = crsiTop and crsiAboveHighband[1]
waveStrongImpulse = crsiTopAboveHighband
// Top that does not break high band but is above WMA
crsiTopBelowHighband = (crsiTop and crsiBelowHighband[1]) and (crsi > crsiWMA)
waveWeakImpulse = crsiTopBelowHighband
//-----------------------------------------------------------------------------
// Determine the ABC, ABCDE, ABCDEFG sequence
// Note that ABCDEFG is not a true Elliott corrective wave sequence, but for this approach is shows up once in a blue moon
possibleWaveA = crsiBottom and crsiBelowLowband[1]
possibleWaveB = (crsiTop and crsiBelowWMA[1]) or (crsiTop and crsiBelow50[1]) // Also catch the tops that are above wma but stay under RSI 50 (rare)
possibleWaveC = possibleWaveA or (crsiBottom and crsiBelowWMA[1]) // sometimes wave C is above the lower band but below the WMA
// Wave AB
findWaveAB(possibleWaveA, possibleWaveB, correctiveWave) =>
isWaveAB = false
foundMatch = false
// start with Wave B
if possibleWaveB
// search backwards and look for wave A
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if possibleWaveA[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match an A and B wave?
if foundMatch
isWaveAB := true
else
isWaveAB := false
else
isWaveAB := false
waveAB = findWaveAB(possibleWaveA, possibleWaveB, correctiveWave)
// Wave ABC
findWaveABC(possibleWaveC, waveAB, correctiveWave) =>
isWaveABC = false
foundMatch = false
if possibleWaveC
// search backwards and look for wave AB
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if waveAB[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match a waveAB with C?
if foundMatch
isWaveABC := true
else
isWaveABC := false
else
isWaveABC := false
waveABC = findWaveABC(possibleWaveC, waveAB, correctiveWave)
// Wave ABCD
findWaveABCD(possibleWaveB, waveABC, correctiveWave) =>
isWaveABCD = false
foundMatch = false
if possibleWaveB
// search backwards and look for wave ABC
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if waveABC[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match a waveABC with D?
if foundMatch
isWaveABCD := true
else
isWaveABCD := false
else
isWaveABCD := false
waveABCD = findWaveABCD(possibleWaveB, waveABC, correctiveWave)
// Wave ABCDE
findWaveABCDE(possibleWaveC, waveABCD, correctiveWave) =>
isWaveABCDE = false
foundMatch = false
if possibleWaveC
// search backwards and look for another wave ABC in this correction
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if waveABCD[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match a waveABC with another waveABC?
if foundMatch
isWaveABCDE := true
else
isWaveABCDE := false
else
isWaveABCDE := false
waveABCDE = findWaveABCDE(possibleWaveC, waveABCD, correctiveWave)
// Wave ABCDEF
findWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave) =>
isWaveABCDEF = false
foundMatch = false
if possibleWaveB
// search backwards and look for another wave ABC in this correction
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if waveABCDE[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match a waveABC with another waveABC?
if foundMatch
isWaveABCDEF := true
else
isWaveABCDEF := false
else
isWaveABCDEF := false
waveABCDEF = findWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave)
// Wave ABCDEFG
findWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave) =>
isWaveABCDEFG = false
foundMatch = false
if possibleWaveC
// search backwards and look for another wave ABC in this correction
for i=1 to 50
// Equity must be in correction else invalidated
if correctiveWave[i]
if waveABCDEF[i]
foundMatch := true
break
//else
// keep looping
else
// motive wave invalidates search
foundMatch := false
break
// Did we match a waveABC with another waveABC?
if foundMatch
isWaveABCDEFG := true
else
isWaveABCDEFG := false
else
isWaveABCDEFG := false
waveABCDEFG = findWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave)
// Determine individual corrective waves
waveA = possibleWaveA and not(waveABC) and not(waveABCDE)
waveB = waveAB and not(waveABCD)
waveC = waveABC
waveD = waveABCD
waveE = waveABCDE
waveF = waveABCDEF
waveG = waveABCDEFG
//-----------------------------------------------------------------------------
// Plot key cRSI points
// plot(crsiCrossBelowHighband?crsi:na, title='cRSI cross below high band', color=color.red, linewidth=7, style=plot.style_circles)
// plot(crsiCrossAboveLowband?crsi:na, title='cRSI cross above low band', color=color.green, linewidth=7, style=plot.style_circles)
// plot(crsiCrossBelowWMA?crsi:na, title='cRSI cross below WMA', color=color.red, linewidth=5, style=plot.style_cross)
// plot(crsiCrossAboveWMA?crsi:na, title='cRSI cross above WMA', color=color.green, linewidth=5, style=plot.style_cross)
// plot(crsiCrossAbove50?crsi:na, title='cRSI cross above 50', color=color.black, linewidth=7, style=plot.style_circles)
// plot(crsiCrossBelow50?crsi:na, title='cRSI cross below 50', color=color.black, linewidth=7, style=plot.style_circles)
// plot(crsiTop?crsi[1]:na, title='cRSI Top', color=color.blue, linewidth=4, style=plot.style_cross, offset=-1)
// plot(crsiBottom?crsi[1]:na, title='cRSI Top', color=color.purple, linewidth=4, style=plot.style_cross, offset=-1)
//--------------------
// Impulse waves
plotStrong = input(title="Plot Strong Impulse Waves (above upper band)", defval=true) and plotCRSI
plotWeak = input(title="Plot Weak Impulse Waves (below upper band)", defval=true) and plotCRSI
impWaveSz = size.tiny
plotshape(plotStrong and waveStrongImpulse?crsi[1]:na, text="s", title='Strong Impulse', style=shape.labeldown, location=location.absolute, color=color.navy, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)
plotshape(plotWeak and waveWeakImpulse?crsi[1]:na, text="w", title='Weak Impulse', style=shape.labeldown, location=location.absolute, color=color.purple, transp=0, offset=-1, textcolor=color.white, size=impWaveSz)
//---------------------
// Corrective waves
// plot(possibleWaveC?crsi[1]:na, title='Possible Wave C', color=color.green, linewidth=6, style=plot.style_circles, offset=-1)
// plot(possibleWaveB?crsi[1]:na, title='Possible Wave B', color=color.blue, linewidth=6, style=plot.style_circles, offset=-1)
// plot(possibleWaveA?crsi[1]:na, title='Possible Wave A', color=color.purple, linewidth=6, style=plot.style_circles, offset=-1)
// plot(waveAB?crsi[1]:na, title='Wave AB', color=color.black, linewidth=5, style=plot.style_cross, offset=-1)
// plot(waveABC?crsi[1]:na, title='Wave ABC', color=color.black, linewidth=7, style=plot.style_cross, offset=-1)
// plot(waveABCDE?crsi[1]:na, title='Wave ABCDE', color=color.black, linewidth=9, style=plot.style_cross, offset=-1)
// plotshape(waveAB?crsi[1]:na, title='Wave AB', style=shape.triangledown, location=location.absolute, color=color.orange, transp=0, offset=-1, text="AB", textcolor=color.orange, size=size.small)
// plotshape(waveABC?crsi[1]:na, title='Wave ABC', style=shape.triangleup, location=location.absolute, color=color.blue, transp=0, offset=-1, text="ABC", textcolor=color.blue, size=size.small)
// plotshape(waveABCD?crsi[1]:na, title='Wave ABCD', style=shape.triangledown, location=location.absolute, color=color.red, transp=0, offset=-1, text="ABCD", textcolor=color.red, size=size.small)
// plotshape(waveABCDE?crsi[1]:na, title='Wave ABCDE', style=shape.triangleup, location=location.absolute, color=color.green, transp=0, offset=-1, text="ABCDE", textcolor=color.green, size=size.small)
plotWaves = input(title="Plot Corrective Waves (ABC,ABCDE)", defval=true) and plotCRSI
corWaveSz = size.small
plotshape(plotWaves and waveA?crsi[1]:na, text="A", title='Wave A', style=shape.labelup, location=location.absolute, color=color.blue, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveB?crsi[1]:na, text="B", title='Wave B', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveC?crsi[1]:na, text="C", title='Wave C', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveD?crsi[1]:na, text="D", title='Wave D', style=shape.labeldown, location=location.absolute, color=color.maroon, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveE?crsi[1]:na, text="E", title='Wave E', style=shape.labelup, location=location.absolute, color=color.lime, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveF?crsi[1]:na, text="F", title='Wave F', style=shape.labeldown, location=location.absolute, color=color.fuchsia, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotWaves and waveG?crsi[1]:na, text="G", title='Wave G', style=shape.labelup, location=location.absolute, color=color.aqua, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
//---------------------
// PRICE CHANGE BETWEEN IMPULSE AND WAVE A
//=================================================================================================================================
//=================================================================================================================================
// Divergence Indicator Using cRSI
//=================================================================================================================================
//=================================================================================================================================
plotBull = input(title="Plot Bullish (cRSI Higher-Low : Price Lower-Low)", defval=true) and plotCRSI
plotHiddenBull = input(title="Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low)", defval=true) and plotCRSI
plotBear = input(title="Plot Bearish (cRSI Lower-High : Price Higher-High", defval=true) and plotCRSI
plotHiddenBear = input(title="Plot Hidden Bearish (cRSI Higher-High : Price Lower-High)", defval=true) and plotCRSI
//------------------------------------------------------------------------------
crsiHighs = waveStrongImpulse or waveWeakImpulse
crsiLows = possibleWaveA or possibleWaveC
//------------------------------------------------------------------------------
// Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low
// Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Low
bullish(crsiLows, crsi, price) =>
foundLow = false
crsiHigherLow = false
priceHigher = false
regularBullish = false
hiddenBullish = false
if crsiLows[0] == true
for i=1 to 50
if crsiLows[i] == true
foundLow := true
// crsi higher or lower?
if crsi[0] > crsi[i]
crsiHigherLow := true
else
crsiHigherLow := false
// price higher or lower
if price[0] > price[i]
priceHigher := true
else
priceHigher := false
// found low, stop looking
break
else
continue
if foundLow
// Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low
if (crsiHigherLow==true) and (priceHigher==false)
regularBullish := true
hiddenBullish := false
// Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Low
else if (crsiHigherLow==false) and (priceHigher==true)
regularBullish := false
hiddenBullish := true
else
regularBullish := false
hiddenBullish := false
else
regularBullish := false
hiddenBullish := false
else
// this is not a low
regularBullish := false
hiddenBullish := false
// return tuple
[regularBullish,hiddenBullish]
[regularBullish,hiddenBullish] = bullish(crsiLows, crsi, close)
plotshape(plotBull and regularBullish?crsi[1]-12:na, text="Bull", title='Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotHiddenBull and hiddenBullish?crsi[1]-12:na, text="H Bull", title='Hidden Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)
//------------------------------------------------------------------------------
// Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High
// Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-High
bearish(crsiHighs, crsi, price) =>
foundHigh = false
crsiHigherHigh = false
priceHigher = false
regularBearish = false
hiddenBearish = false
if crsiHighs[0] == true
for i=1 to 50
if crsiHighs[i] == true
foundHigh := true
// crsi higher or lower?
if crsi[0] > crsi[i]
crsiHigherHigh := true
else
crsiHigherHigh := false
// price higher or lower
if price[0] > price[i]
priceHigher := true
else
priceHigher := false
// found high, stop looking
break
else
continue
if foundHigh
// Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High
if (crsiHigherHigh==false) and (priceHigher==true)
regularBearish := true
hiddenBearish := false
// Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-High
else if (crsiHigherHigh==true) and (priceHigher==false)
regularBearish := false
hiddenBearish := true
else
regularBearish := false
hiddenBearish := false
else
regularBearish := false
hiddenBearish := false
else
// this is not a low
regularBearish := false
hiddenBearish := false
// return tuple
[regularBearish,hiddenBearish]
[regularBearish,hiddenBearish] = bearish(crsiHighs, crsi, close)
plotshape(plotBear and regularBearish?crsi[1]+10:na, text="Bear", title='Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz)
plotshape(plotHiddenBear and hiddenBearish?crsi[1]+10:na, text="H Bear", title='Hidden Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=20, offset=-1, textcolor=color.white, size=corWaveSz)
//==================================================================================================================================================================================================================================================================
//==================================================================================================================================================================================================================================================================
//==================================================================================================================================================================================================================================================================
// Buy/Sell Strategy
//==================================================================================================================================================================================================================================================================
//==================================================================================================================================================================================================================================================================
//==================================================================================================================================================================================================================================================================
// Remove duplicate buy/sells if one was already executed recently
filterLookback = 5
// normalize a value in a range between min and max
normalize(val, valMin, valMax) =>
valNorm = val
valNorm := valNorm < valMin ? valMin : valNorm
valNorm := valNorm > valMax ? valMax : valNorm
valNorm := (valNorm-valMin) / (valMax-valMin)
recentWave(wave, lookback) =>
ret = false
found = false
for i=0 to lookback
if wave[i] == true
found := true
break
if found
ret := true
else
ret := false
//-----------------------------------------------------------------------------
// Levels for upper band - High
crsiHighband_extremeHighLevel = 90
crsiHighband_highLevel = 70
crsiHighband_highWeight = normalize(crsiHighband, crsiHighband_highLevel, crsiHighband_extremeHighLevel)
// Levels for upper band - Low
crsiHighband_extremeLowLevel = 45
crsiHighband_lowLevel = 55
crsiHighband_lowWeight = 1.0 - normalize(crsiHighband, crsiHighband_extremeLowLevel, crsiHighband_lowLevel)
// plot(crsiHighband_highWeight,color=color.blue)
// plot(crsiHighband_lowWeight,color=color.red)
//-----------------------------------------------------------------------------
// // Levels for lower band - High
crsiLowband_extremeHighLevel = 80
crsiLowband_highLevel = 60
crsiLowband_higheight = normalize(crsiLowband, crsiLowband_highLevel, crsiLowband_extremeHighLevel)
// Levels for lower band - Low
crsiLowband_extremeLowLevel = 20
crsiLowband_lowLevel = 45
crsiLowband_lowWeight = 1.0 - normalize(crsiLowband, crsiLowband_extremeLowLevel, crsiLowband_lowLevel)
// plot(crsiLowband_highWeight,color=color.blue)
// plot(crsiLowband_lowWeight,color=color.red)
//--------------------------------------------------------------------------------------------
// SELL
//--------------------------------------------------------------------------------------------
maxSellOrderSize = 10
crsiHighband_above_crsiHighband_highLevel = crsiHighband > crsiHighband_highLevel ? true : false
Sell1 = waveStrongImpulse
Sell2 = crsiAboveHighband and crsiFalling ? true : false // Above high band and now falling
Sell3 = crsiAboveHighband[1] and crsiFalling ? true : false // 1x previous was above high band and now falling (sometimes it can be off by a bar)
Sell4 = crsiAboveHighband[2] and crsiFalling ? true : false // 2x previous was above high band and now falling (sometimes it can be off by a bar)
//Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel
// Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel
// Sell = (Sell1 or Sell2) //and crsiHighband_above_crsiHighband_highLevel
// Sell = (Sell1 or Sell2 or Sell3) //and crsiHighband_above_crsiHighband_highLevel
Sell = (Sell1 or Sell2 or Sell3 or Sell4) and crsiHighband_above_crsiHighband_highLevel
Sell := filterSignal(Sell, filterLookback)
// Base sell size on how high the Highband is
sellSize = crsiHighband_highWeight *maxSellOrderSize // When in doubt, DON'T SELL! Stonks only go up ;)
// extreme cRSI
sellSize := crsi > crsiHighband_extremeHighLevel ? 1.5*maxSellOrderSize : sellSize
// if the sell size is small, just make min sell
sellSize := sellSize < maxSellOrderSize/3 ? 0 : sellSize
sellSize := round(sellSize)
if Sell
strategy.order("Sell", false, sellSize)
//--------------------------------------------------------------------------------------------
// BUY - Price can continue to fall even when cRSI is rising!!!
//--------------------------------------------------------------------------------------------
maxBuyOrderSize = 10
// Wait until it crosses back above WMA so it is clear that motive wave is clear.
// Buying at the bottom is really hard because RSI can start to rise yet price will continue to fall
Buy1 = bullStart
// Using waves can help do a better job timing the bottom, but big corrections can go much deeper than just Wave C (Zig Zag)
Buy2 = waveA and regularBullish
Buy3 = waveC and regularBullish
Buy4 = waveE and (topBottomLookback == 3) // usullay max is a wave E with topBottomLookback == 3
Buy5 = waveG and (topBottomLookback == 2) // can see a G wave when topBottomLookback == 2
Buy = Buy1 or Buy2 or Buy3 or Buy4 or Buy5
Buy := filterSignal(Buy, filterLookback)
// Base buy size on how low the Lowband is
buySize = crsiLowband_lowWeight*maxBuyOrderSize
// buySize := buySize < 1 ? 1 : buySize // When in doubt, BUY! Stonks only go up ;)
// Look for recent wave endings that can increase our guess of buying at a low
recentWaveC = recentWave(waveC, 10)
recentWaveE = recentWave(waveE, 10)
recentWaveG = recentWave(waveG, 10)
// buySize := recentWaveE ? 1.5*maxBuyOrderSize : buySize
// buySize := recentWaveG ? 1.5*maxBuyOrderSize : buySize
buySize := recentWaveE ? maxBuyOrderSize : buySize
buySize := recentWaveG ? maxBuyOrderSize : buySize
// if the buy size is small, just make min buy
buySize := buySize < maxSellOrderSize/3 ? 0 : buySize
buySize := round(buySize)
if Buy
strategy.order("Buy", true, buySize)
|
MA Candles Supertrend Strategy | https://www.tradingview.com/script/3o1JCZQL-MA-Candles-Supertrend-Strategy/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 638 | 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/
// © HeWhoMustNotBeNamed
//@version=5
strategy('MA Candles Supertrend Strategy', shorttitle='MACSTS', overlay=true, initial_capital=20000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, pyramiding=1, commission_value=0.01)
MAType = input.string(title='Moving Average Type', defval='rma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'])
LoopbackBars = input.int(20, step=10)
AtrMAType = input.string(title='Moving Average Type', defval='rma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma'])
AtrLength = input.int(30, step=10)
AtrMult = input(1)
adoptiveWicks = false // does not work
wicks = input(true)
dThreshold = input.float(0.2, step=0.1, maxval=1)
rThreshold = input.float(0.7, step=0.1, maxval=1)
tradeDirection = input.string(title='Trade Direction', defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])
i_startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time')
i_endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time')
inDateRange = time >= i_startTime and time <= i_endTime
strategy.risk.allow_entry_in(tradeDirection)
f_getMovingAverage(source, MAType, length) =>
ma = ta.sma(source, length)
if MAType == 'ema'
ma := ta.ema(source, length)
ma
if MAType == 'hma'
ma := ta.hma(source, length)
ma
if MAType == 'rma'
ma := ta.rma(source, length)
ma
if MAType == 'vwma'
ma := ta.vwma(source, length)
ma
if MAType == 'wma'
ma := ta.wma(source, length)
ma
ma
f_secureSecurity(_symbol, _res, _src, _offset) =>
request.security(_symbol, _res, _src[_offset], lookahead=barmerge.lookahead_on)
f_getYearlyHighLowCondition() =>
yhighrange = f_secureSecurity(syminfo.tickerid, '12M', high, 1)
ylowrange = f_secureSecurity(syminfo.tickerid, '12M', low, 1)
yearlyHighCondition = close > yhighrange * (1 - dThreshold) or close > ylowrange * (1 + rThreshold)
yearlyLowCondition = close < ylowrange * (1 + dThreshold) or close < yhighrange * (1 - rThreshold)
[yearlyHighCondition, yearlyLowCondition]
f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks) =>
truerange = math.max(oHigh, oClose[1]) - math.min(oLow, oClose[1])
averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength)
atr = averagetruerange * AtrMult
longWicks = adoptiveWicks and close < oClose or wicks
shortWicks = adoptiveWicks and close > oClose or wicks
longStop = oClose - atr
longStopPrev = nz(longStop[1], longStop)
longStop := (longWicks ? oLow[1] : oClose[1]) > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = oClose + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := (shortWicks ? oHigh[1] : oClose[1]) < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and (longWicks ? oHigh : oClose) > shortStopPrev ? 1 : dir == 1 and (shortWicks[1] ? oLow : oClose) < longStopPrev ? -1 : dir
[dir, longStop, shortStop]
oOpen = f_getMovingAverage(open, MAType, LoopbackBars)
oClose = f_getMovingAverage(close, MAType, LoopbackBars)
oHigh = f_getMovingAverage(high, MAType, LoopbackBars)
oLow = f_getMovingAverage(low, MAType, LoopbackBars)
colorByPreviousClose = false
candleColor = colorByPreviousClose ? oClose[1] < oClose ? color.green : oClose[1] > oClose ? color.red : color.silver : oOpen < oClose ? color.green : oOpen > oClose ? color.red : color.silver
plotcandle(oOpen, oHigh, oLow, oClose, 'Oscilator Candles', color=candleColor)
[yearlyHighCondition, yearlyLowCondition] = f_getYearlyHighLowCondition()
[dir, longStop, shortStop] = f_getSupertrend(oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks)
trailingStop = dir == 1 ? longStop : shortStop
trendColor = dir == 1 ? color.green : color.red
plot(trailingStop, title='TrailingStop', color=trendColor, linewidth=2, style=plot.style_linebr)
exitLongCondition = dir == -1 and (dir[1] == -1 and close < close[1] or close < longStop)
exitShortCondition = dir == 1 and (dir[1] == 1 and close > close[1] or close > shortStop)
longCondition = exitShortCondition and yearlyHighCondition and inDateRange
shortCondition = exitLongCondition and yearlyLowCondition and inDateRange
strategy.risk.allow_entry_in(tradeDirection)
strategy.entry('Long', strategy.long, when=longCondition, oca_name='oca_buy', oca_type=strategy.oca.cancel)
strategy.close('Long', when=exitLongCondition)
strategy.entry('Short', strategy.short, when=shortCondition, oca_name='oca_sell', oca_type=strategy.oca.cancel)
strategy.close('Short', when=exitShortCondition)
|
RSI-VWAP Indicator % | https://www.tradingview.com/script/d0FZtMLp/ | UnknownUnicorn2151907 | https://www.tradingview.com/u/UnknownUnicorn2151907/ | 1,936 | 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("RSI-VWAP Indicator %", overlay = false, pyramiding = 5, initial_capital = 100000, default_qty_value = 0, commission_value = 0.04, max_labels_count = 500)
//█ Initial inputs
StartDate = timestamp( "01 Jan 2000 00:00 +0000")
Spot = input(false, "Spot Trading (no leverage)", input.bool)
testPeriodStart = input(StartDate, "Start of trading", input.time)
Length = input(16, "RSI/VWAP Length", input.integer, minval = 1)
OverSold = input(18, "RSI/VWAP Oversold", input.float, minval = 0, maxval = 100)
OverBought = input(80, "RSI/VWAP Overbought", input.float, minval = 0, maxval = 100)
EquityPercent = input(25, "% Equity on Longs", input.float, minval = 0, maxval = 100)
PositionPercent = input(50, "% Position on Closings", input.float, minval = 0, maxval = 100)
Risk = input(15, "% Drawdown allowed", input.float, minval = 0, maxval = 100)
MarginRate = input(1.0, "% Margin Rate", input.float, minval = 0) / 100
// RSI with VWAP as source
RsiVwap = rsi(vwap(close), Length)
//█ Plotting
// Rsi-vwap Line Color
RsiVwapLineColor = RsiVwap > OverBought ? color.new(color.red, 50) :
RsiVwap < OverSold ? color.new(color.lime, 50) :
color.new(color.blue, 50)
// Rsi-vwap Fill Color
FillColorOverBought = RsiVwap > OverBought ? color.new(color.red, 75) : na
FillColorOverSold = RsiVwap < OverSold ? color.new(color.lime, 75) : na
// Overbought/Oversold Color
OboughtOsoldColor = color.new(color.gray, 50)
// Rsi-vwap plot
RsiVwapLine = plot(RsiVwap, "RSI/VWAP", RsiVwapLineColor, linewidth = 2)
// Plot of the top line
OverBoughtLine = plot(OverBought, "Overbought", OboughtOsoldColor)
// Plot of the bottom line
OverSoldLine = plot(OverSold, "Oversold", OboughtOsoldColor)
// Fill between plots
fill(RsiVwapLine, OverBoughtLine, FillColorOverBought)
fill(RsiVwapLine, OverSoldLine, FillColorOverSold)
// Information panel
Equity = strategy.equity
Balance = strategy.initial_capital + strategy.netprofit
RealizedPnL = strategy.netprofit
Floating = strategy.openprofit
PercentFloating = (Floating / strategy.initial_capital) * 100
PercentRealizedPnL = (RealizedPnL / strategy.initial_capital) * 100
URealizedPnL = Floating + RealizedPnL
PercentURealizedPnL = ((URealizedPnL) / strategy.initial_capital) * 100
PositionSize = strategy.position_size * strategy.position_avg_price
Cash = Spot ? max(0, Balance - PositionSize) : max(0, Balance - (PositionSize * MarginRate))
Leverage = PositionSize / Balance
Margin = Spot ? 0 : PositionSize * MarginRate
var label labelEquity = na
labelEquity := label.new(bar_index, 50, style = label.style_label_left, textcolor = #9598a1, color = #131722, textalign = text.align_left, size = size.normal,
text = "Position Size: " + tostring(strategy.position_size, '#.########') + " " + syminfo.basecurrency + "\n" +
"Cash: " + tostring(Cash, '#.##') + " " + syminfo.currency + "\n" +
"Margin: " + tostring(Margin, '#.##') + " " + syminfo.currency + "\n" +
"Floating: " + tostring(Floating, '#.##') + " " + syminfo.currency + " / "
+ tostring(PercentFloating, '#.##') + " %" + "\n" +
"Realized PnL: " + tostring(RealizedPnL, '#.##') + " " + syminfo.currency + " / "
+ tostring(PercentRealizedPnL, '#.##') + " %" + "\n" +
"Unrealized PnL: " + tostring(URealizedPnL, '#.##') + " " + syminfo.currency + " / "
+ tostring(PercentURealizedPnL, '#.##') + " %")
// Deleting previous labels
label.delete(labelEquity[1])
//█ Backtest & Alerts
// Quantities
QuantityOnLong = Spot ? (EquityPercent / 100) * ((strategy.equity / close) - strategy.position_size) :
(EquityPercent / 100) * (strategy.equity / close)
QuantityOnClose = (PositionPercent / 100) * strategy.position_size
// Buy/Long shapes
var bool long = na
if crossover(RsiVwap[1], OverSold) and (time > testPeriodStart)
label.new(bar_index, OverSold, tostring(Leverage, "#.#") + "X", textcolor = Spot ? na : #9598a1, color = color.new(color.lime, 25), style = label.style_diamond, size = size.tiny)
long := true
// Sell/Closing shapes
if crossunder(RsiVwap[1], OverBought) and (time > testPeriodStart) and not na(long)
label.new(bar_index, OverBought, color = color.new(color.red, 25), style = label.style_diamond, size = size.tiny)
// Alerts
string BuyMessage = "q=" + tostring(EquityPercent) + "% t=market"
string SellMessage = "q=" + tostring(PositionPercent) + "% t=market"
// (copy and paste on the alert window a message similar to this)
// {{strategy.order.action}} @ {{strategy.order.price}} | e={{exchange}} a=account s={{ticker}} b={{strategy.order.action}} {{strategy.order.alert_message}}
// Market orders on long
if crossover(RsiVwap, OverSold) and (time > testPeriodStart)
strategy.entry("LONG", strategy.long, qty = QuantityOnLong, alert_message = BuyMessage)
// Market orders on close
if crossunder(RsiVwap, OverBought)
strategy.close("LONG", qty_percent = PositionPercent, comment = "CLOSE", alert_message = SellMessage)
// Max Drawdown allowed percent
strategy.risk.max_drawdown(Risk, strategy.percent_of_equity)
// by XaviZ |
Oscillator Evaluator (Analysis tool) | https://www.tradingview.com/script/M9taaIkp-Oscillator-Evaluator-Analysis-tool/ | mks17 | https://www.tradingview.com/u/mks17/ | 743 | 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/
// © mks17
//@version=4
//Created for tradingview backtester
strategy(title='Oscillator Evaluator (Analysis tool)', shorttitle='Oscillator Evaluator', precision=3, initial_capital=700, pyramiding=500, default_qty_value=500, default_qty_type=strategy.cash, commission_type=strategy.commission.percent, commission_value=0.1, calc_on_every_tick=false, calc_on_order_fills=false, max_bars_back=600, overlay=false)
//--------------------Average Returns---------------------------------
avgRetR = input(title='Average Returns Ratio Adjustment', type=input.float, defval=1, minval=0.02, step=0.02) //To change the automatic calculated avgRet parameter
sum = 0.0
sum := nz(sum[1])
returns = (close - close[1]) * 100 / close
sum := sum + abs(returns)
avgRet = sum / bar_index
avgRet := avgRet * avgRetR
avgRet100 = avgRet / 100
avgRetClose100 = close * avgRet100
//---------------------------Inputs------------------------------------
lEntries = input(false, title="Show Long Entries Only")
sEntries = input(false, title="Show Short Entries Only")
stratSel = input(defval="MA Strategy", title="Strategy Selector", options=["MA Strategy", "MA Crossover Strategy", "Cross over 0 Strategy","Buy/Sell on Extremes Strategy", "Mean Reversion Strategy", "Take Profit Strategy"], type=input.string)
dataSel = input(defval="Oscillator 1", title="Oscillator Selector", options=["Oscillator 1", "Oscillator 2", "Oscillator 3"], type=input.string)
scale1 = input(title="Oscillator 1 Scale Adjustment", type=input.float, defval=1, minval=0, maxval=10, step=0.05)
tfadj1 = input(title="Oscillator 1 Timeframe Adjustment", type=input.float, defval=0.2, minval=0, maxval=10, step=0.05)
scale2 = input(title="Oscillator 2 Scale Adjustment", type=input.float, defval=1, minval=0, maxval=10, step=0.05)
tfadj2 = input(title="Oscillator 2 Timeframe Adjustment", type=input.float, defval=0.2, minval=0, maxval=10, step=0.05)
scale3 = input(title="Oscillator 3 Scale Adjustment", type=input.float, defval=1, minval=0, maxval=10, step=0.05)
tfadj3 = input(title="Oscillator 3 Timeframe Adjustment", type=input.float, defval=0.2, minval=0, maxval=10, step=0.05)
bool mastrat = false, macrossstrat = false, crossstrat = false, bsstrat = false, mrstrat = false, tpstrat = false
if stratSel == "MA Strategy"
mastrat := true
else if stratSel == "MA Crossover Strategy"
macrossstrat := true
else if stratSel == "Cross over 0 Strategy"
crossstrat := true
else if stratSel == "Buy/Sell on Extremes Strategy"
bsstrat := true
else if stratSel == "Mean Reversion Strategy"
mrstrat := true
else
tpstrat := true
//MA Strat
malmt = input(7, "MA Strat Length")
mcthr = input(0.07, "MA Strat Range Threshold", step=0.005) //"MC Range Threshold "
//MA crossOver Strat
mas = input(3, "MA Crossover Strat Short Length") //"MA Short Length"
mal = input(9, "MA Crossover Strat Long Length") //"MA Long Length"
//Cross on 0 Strat
cross = input(0, "Cross Strat Horizon", step=0.1) //"Cross over 0"
//Buy Sell on Extremes Strat
bsOversold = input(-36.2, "Buy/Sell on Extremes Strat Oversold Value", step=0.1) //"Entry Max Signal"
bsOverbought = input(47.2, "Buy/Sell on Extremes Strat Overbought Value", step=0.1) //"Entry Max Signal"
//Mean Reversion Strat
mrOversold = input(-45, "Mean Reversion Strat Oversold Value", step=0.1) //"Entry Max Signal"
mrOverbought = input(45, "Mean Reversion Strat Overbought Value", step=0.1) //"Entry Max Signal"
// factor0 = input(1, step=0.1)
// factor1 = input(1, step=0.1)
// factor2 = input(1, step=0.1)
mrtp = input(0.5, "Mean Reversion Strat TP (%)", step=0.1) / 100//
mrsl = input(0.5, "Mean Reversion Strat SL (%)", step=0.1) / 100//
//Take Profit Strat
tpOversold = input(-45, "Take Profit Strat Oversold Value", step=0.1) //"Entry Max Signal"
tpOverbought = input(45, "Take Profit Strat Overbought Value", step=0.1) //"Entry Max Signal"
tp = input(10, "Take Profit Strat TP (%)", step=1) / 100//
sl = input(4, "Take Profit Strat TP (%)", step=1) / 100//
//Max loss and Max Downturn for all strategies
emaxl = input(10, "Max Loss (%)", step=1) / 100 //"Exit Max loss"
emaxdn =input(20, "Max Downturn (%)", step=1) / 100//"Exit Max Downturn"
//-------------Oscillators-----------------
//Put here your 2 oscillators of choice for comparison
//Mine is RSI
rsi1 = rsi(ohlc4, 1)
rsi2 = rsi(ohlc4, 2), rsi2 := nz(rsi2, rsi1)
rsi3 = rsi(ohlc4, 3), rsi3 := nz(rsi3, rsi2)
rsi4 = rsi(ohlc4, 4), rsi4 := nz(rsi4, rsi3)
rsi5 = rsi(ohlc4, 5), rsi5 := nz(rsi5, rsi4)
rsi6 = rsi(ohlc4, 6), rsi6 := nz(rsi6, rsi5)
rsi7 = rsi(ohlc4, 7), rsi7 := nz(rsi7, rsi6)
LTFrsi = ((rsi1 + rsi2 + rsi3 + rsi4 + rsi5 + rsi6 + rsi7) / 7) - 50
rsi12 = rsi(ohlc4, 12), rsi12 := nz(rsi12, LTFrsi)
rsi24 = rsi(ohlc4, 24), rsi24 := nz(rsi24, rsi12)
rsi36 = rsi(ohlc4, 36), rsi36 := nz(rsi36, rsi24)
rsi48 = rsi(ohlc4, 48), rsi48 := nz(rsi48, rsi36)
rsi60 = rsi(ohlc4, 60), rsi60 := nz(rsi60, rsi48)
rsi72 = rsi(ohlc4, 72), rsi72 := nz(rsi72, rsi60)
rsi84 = rsi(ohlc4, 84), rsi84 := nz(rsi84, rsi72)
HTFrsi = ((rsi12 + rsi24 + rsi36 + rsi48 + rsi60 + rsi72 + rsi84) / 7) - 50
rsi = tfadj1 * LTFrsi + (1 - tfadj1) * HTFrsi
//And Stochastic
stoch1 = sma(stoch(close, high, low, 1), 2)
stoch2 = sma(stoch(close, high, low, 2), 2), stoch2 := nz(stoch2, stoch1)
stoch3 = sma(stoch(close, high, low, 3), 2), stoch3 := nz(stoch3, stoch2)
stoch4 = sma(stoch(close, high, low, 4), 2), stoch4 := nz(stoch4, stoch3)
stoch5 = sma(stoch(close, high, low, 5), 2), stoch5 := nz(stoch5, stoch4)
stoch6 = sma(stoch(close, high, low, 6), 2), stoch6 := nz(stoch6, stoch5)
stoch7 = sma(stoch(close, high, low, 7), 2), stoch7 := nz(stoch7, stoch6)
LTFstoch = ((stoch1 + stoch2 + stoch3 + stoch4 + stoch5 + stoch6 + stoch7) / 7) - 50
stoch12 = sma(stoch(close, high, low, 12), 2), stoch12 := nz(stoch12, LTFstoch)
stoch24 = sma(stoch(close, high, low, 24), 2), stoch24 := nz(stoch24, stoch12)
stoch36 = sma(stoch(close, high, low, 36), 2), stoch36 := nz(stoch36, stoch24)
stoch48 = sma(stoch(close, high, low, 48), 2), stoch48 := nz(stoch48, stoch36)
stoch60 = sma(stoch(close, high, low, 60), 2), stoch60 := nz(stoch60, stoch48)
stoch72 = sma(stoch(close, high, low, 72), 2), stoch72 := nz(stoch72, stoch60)
stoch84 = sma(stoch(close, high, low, 84), 2), stoch84 := nz(stoch84, stoch72)
HTFstoch = ((stoch12 + stoch24 + stoch36 + stoch48 + stoch60 + stoch72 + stoch84) / 7) - 50
stoch = tfadj2 * LTFstoch + (1 - tfadj2) * HTFstoch
//Data Selector
float data = 0.0
if dataSel == "Oscillator 1"
data := rsi * scale1
else if dataSel == "Oscillator 2"
data := stoch * scale2
else
data := stoch * scale3
//--------------------MAs---------------------
PI = 2 * asin(1)
laguerre(src, alpha) =>
// A 4-element Laguerre filter
L0 = 0.0, L2 = 0.0, L4 = 0.0, L6 = 0.0
L0 := alpha * src + (1 - alpha) * nz(L0[1], src)
L2 := -(1 - alpha) * L0 + nz(L0[1], src) + (1 - alpha) * nz(L2[1], src)
L4 := -(1 - alpha) * L2 + nz(L2[1], src) + (1 - alpha) * nz(L4[1], src)
L6 := -(1 - alpha) * L4 + nz(L4[1], src) + (1 - alpha) * nz(L6[1], src)
(L0 + 2 * L2 + 2 * L4 + L6) / 6
highpassFilter(src, highpassLength) =>
a = 0.707 * 2 * PI / highpassLength
alpha1 = 1 + (sin(a) - 1) / cos(a)
b = 1 - alpha1 / 2
c = 1 - alpha1
highpass = 0.0
highpass := highpassLength != 0 ? b * b * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * c * nz(highpass[1]) - c * c * nz(highpass[2]) : src
hilbertTransform(src) =>
0.0962 * src + 0.5769 * nz(src[2]) - 0.5769 * nz(src[4]) - 0.0962 * nz(src[6])
computeComponent(src, mesaPeriodMult) =>
hilbertTransform(src) * mesaPeriodMult
computeAlpha(src, fastLimit, slowLimit) =>
mesaPeriod = 0.0, smooth = 0.0, detrender = 0.0, I2 = 0.0, Q2 = 0.0, phase = 0.0
mesaPeriodMult = 0.075 * nz(mesaPeriod[1]) + 0.54
smooth := (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10
detrender := computeComponent(smooth, mesaPeriodMult)
I1 = nz(detrender[3])
Q1 = computeComponent(detrender, mesaPeriodMult)
jI = computeComponent(I1, mesaPeriodMult)
jQ = computeComponent(Q1, mesaPeriodMult)
I2 := I1 - jQ
Q2 := Q1 + jI
I2 := 0.2 * I2 + 0.8 * nz(I2[1])
Q2 := 0.2 * Q2 + 0.8 * nz(Q2[1])
Re = I2 * nz(I2[1]) + Q2 * nz(Q2[1])
Im = I2 * nz(Q2[1]) - Q2 * nz(I2[1])
Re := 0.2 * Re + 0.8 * nz(Re[1])
Im := 0.2 * Im + 0.8 * nz(Im[1])
if Re != 0 and Im != 0
mesaPeriod := 2 * PI / atan(Im / Re)
if mesaPeriod > 1.5 * nz(mesaPeriod[1])
mesaPeriod := 1.5 * nz(mesaPeriod[1])
if mesaPeriod < 0.67 * nz(mesaPeriod[1])
mesaPeriod := 0.67 * nz(mesaPeriod[1])
if mesaPeriod < 6
mesaPeriod := 6
if mesaPeriod > 50
mesaPeriod := 50
mesaPeriod := 0.2 * mesaPeriod + 0.8 * nz(mesaPeriod[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
alpha
mama(_src, _fastlimit, _slowlimit) =>
alpha = computeAlpha(_src, _fastlimit, _slowlimit)
mama = 0.0
mama := alpha * _src + (1 - alpha) * nz(mama[1], _src)
kama(_src, _len) =>
mom = abs(change(_src, _len))
volatility = sum(abs(change(_src)), _len)
er = volatility != 0 ? mom / volatility : 0
fastAlpha = 0.6666
slowAlpha = 0.0645
alpha = pow((er * (fastAlpha - slowAlpha)) + slowAlpha, 2)
kama = 0.0
kama := alpha * _src + (1 - alpha) * nz(kama[1], _src)
percent(nom, div) =>
100 * nom / div
vidya(_src, _len) =>
alpha = 6 / (_len + 1)
momm = change(_src)
m1 = momm >= 0.0 ? momm : 0.0
m2 = momm >= 0.0 ? 0.0 : -momm
sm1 = sum(m1, _len)
sm2 = sum(m2, _len)
chandeMO = nz(percent(sm1 - sm2, sm1 + sm2))
k = abs(chandeMO) / 100
vidya = 0.0
vidya := alpha * k * _src + (1 - alpha * k) * nz(vidya[1], _src)
sSmooth(src, length) =>
//Ehlers Super Smooth Filter
arg = sqrt(2) * PI / length
a1 = exp(-arg)
coef2 = 2 * a1 * cos(arg)
coef3 = -pow(a1, 2)
coef1 = 1 - coef2 - coef3
src1 = nz(src[1], src)
src2 = nz(src[2], src1)
ssf = 0.0
ssf := coef1 * (src + src1) * 0.5 + coef2 * nz(ssf[1], src1) + coef3 * nz(ssf[2], src2)
filter(type, src, len) =>
// MA type Selector
type == "Laguerre" ? laguerre(src, 4.0 / (1 + len)) : type == "EMA" ? ema(src, len) : type == "SMA" ? sma(src, len) : type == "MAMA" ? mama(src, 4.5 / len, 0.45 / len) : type == "KAMA" ? kama(src, len) : type == "VIDYA" ? vidya(src, len) : type == "S Smooth" ? sSmooth(src, len) : src
//-------------------------Strategies---------------------
//-------------MA Strategy
bool bear = false, bool bull = false, bool range = false, var rangeprice = close, ma2 = 0.0
if mastrat
ma2 := filter("Laguerre", data, malmt) //Market Cycle MA
//Average Change MA
change = (ma2 - ma2[1]) / ma2
suma4 = 0.0
suma4 := nz(suma4[1])
abschange = abs(change)
suma4 := suma4 + abschange * 100
avgChange = suma4 / bar_index
avgChange100 = ma2 * avgChange / 100
mcthr := mcthr * avgChange100
ma2a = ma2 + 50
dataa = data + 50
//Normal Range if ma is flat then is a range
if (mcthr >= -0.15 * avgChange100 and mcthr <= 0.15 * avgChange100)
if (ma2a[1] - ma2a >= mcthr)
bear := true
if (ma2a - ma2a[1] >= mcthr and not(bear))
bull := true
if (abs(ma2a - ma2a[1]) < mcthr and not(bear or bull))
range := true
//MC Change if above or below MA complete change to opossite condition
if (mcthr < -0.15 * avgChange100)
if (abs(ma2a - ma2a[1]) < -mcthr - 0.15 * avgChange100)
range := true
if (dataa > ma2a and data > ma2a and not(range))
bull := true
if (dataa < ma2a and data < ma2a and not(range or bull))
bear := true
//MC Range if above or below MA cahnge to range condition
if (mcthr > 0.15 * avgChange100)
if (abs(ma2a - ma2a[1]) < mcthr - 0.15 * avgChange100 or (ma2a - ma2a[1] >= mcthr - 0.15 * avgChange100 and dataa < ma2a and dataa < ma2a or ma2a[1] - ma2a >= mcthr - 0.15 * avgChange100 and dataa > ma2a and dataa > ma2a))
range := true
if (ma2a - ma2a[1] >= mcthr - 0.15 * avgChange100 and not(range))
bull := true
if (ma2a[1] - ma2a >= mcthr - 0.15* avgChange100 and not(range or bull))
bear := true
rangeprice := range[1] == false and range ? ma2 : range[1] and range == false ? na : rangeprice[1]
//--------------MA CrossOver Strategy
ma1 = 0.0, ma3 = 0.0
if macrossstrat
ma1 := filter("EMA", data, mas) //"MA Short"
ma3 := filter("Laguerre", data, mal) //"MA Long"
//-------------------------Entry Strategy---------------------------
longentry = 0, shortentry = 0, x2longentry = 0, x2shortentry = 0, shortexit = 0, longexit = 0, overBought = 0, overSold = 0
last_open_long = float(na), last_open_short = float(na), var last_close_long = float(na), var last_close_short = float(na)
var pyramiding = 0 //To know the current pyramiding
var longCounter = 0, var shortCounter = 0 //To keep track of the position we are in
var maxProfit = float(na)
if (longCounter == 0 or shortCounter == 0)
//MA Strat
if mastrat
if (longCounter == 0 and shortCounter == 0 or longCounter == 0 and shortCounter == 1)
if (bull)
longentry := 1
longCounter := 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if (shortCounter == 0 and longCounter == 0 or longCounter == 1 and shortCounter == 0)
if (bear)
shortentry := 1
shortCounter := 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
//MA CrossOver Strat
if macrossstrat
if (longCounter == 0 and ma1 >= ma3)
longentry := 1
longCounter := 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if (shortCounter == 0 and ma1 < ma3)
shortentry := 1
shortCounter := 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
//Cross 0 Strat
if crossstrat
if (data >= cross and longCounter == 0)
longentry := 1
longCounter := 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if (data < cross and shortCounter == 0)
shortentry := 1
shortCounter := 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
//Buy/Sell on Extremes Strat
if bsstrat
if data < bsOversold
longentry := 1
longCounter := longCounter + 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if data > bsOverbought
shortentry := 1
shortCounter := shortCounter + 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
//Mean Reversion Strat
if mrstrat
if (shortCounter == 0 and longCounter == 0 and data < mrOversold)
longentry := 1
longCounter := longCounter + 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if (longCounter == 0 and shortCounter == 0 and data > mrOverbought)
shortentry := 1
shortCounter := shortCounter + 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
//Take Profit Strat
if tpstrat
if (shortCounter == 0 and longCounter == 0 and crossunder(data, tpOversold))
longentry := 1
longCounter := longCounter + 1
if (shortCounter != 0 and sEntries)
shortexit := 1
shortCounter := 0
if (longCounter == 0 and shortCounter == 0 and crossover(data, tpOverbought))
shortentry := 1
shortCounter := shortCounter + 1
if (longCounter != 0 and lEntries)
longexit := 1
longCounter := 0
last_open_long := longentry == 1 or x2longentry == 1 ? close : nz(last_open_long[1])
last_open_short := shortentry == 1 or x2shortentry == 1 ? close : nz(last_open_short[1])
if longCounter > 0
maxProfit := max(maxProfit[1], close)
else if shortCounter > 0
maxProfit := min(maxProfit[1], close)
else
maxProfit := 0
if longentry == 1 or x2longentry == 1 or shortentry == 1 or x2shortentry == 1
maxProfit := close
//-----------------------Close Strategy-------------------------------
if (longCounter != 0 or shortCounter != 0)
//Max Loss Exits
maxlossLong = close < last_open_long * (1 - emaxl)
maxlossShort = close > last_open_short * (1 + emaxl)
if (longCounter != 0 and maxlossLong)
longexit := 4
longCounter := 0
shortCounter := 0
if (shortCounter != 0 and maxlossShort)
shortexit := 4
shortCounter := 0
longCounter := 0
maxdowntLong = close < maxProfit * (1 - emaxdn)
maxdowntShort = close > maxProfit * (1 + emaxdn)
//Max Downturn Exits
if (longCounter != 0 and maxdowntLong)
longexit := 5
longCounter := 0
shortCounter := 0
if (shortCounter != 0 and maxdowntShort)
shortexit := 5
shortCounter := 0
longCounter := 0
//Mean Reversion Strat
if mrstrat
if (longCounter != 0 and close > last_open_long * (1 + mrtp))
longexit := 2
longCounter := 0
if (longCounter != 0 and close < last_open_long * (1 - mrsl))
longexit := 3
longCounter := 0
if (shortCounter != 0 and close < last_open_short * (1 - mrtp))
shortexit := 2
shortCounter := 0
if (shortCounter != 0 and close > last_open_short * (1 + mrsl))
shortexit := 3
shortCounter := 0
//Take Profit Strat
if tpstrat
if (longCounter != 0 and close > last_open_long * (1 + tp))
longexit := 2
longCounter := 0
if (longCounter != 0 and close < last_open_long * (1 - sl))
longexit := 3
longCounter := 0
if (shortCounter != 0 and close < last_open_short * (1 - tp))
shortexit := 2
shortCounter := 0
if (shortCounter != 0 and close > last_open_short * (1 + sl))
shortexit := 3
shortCounter := 0
//--------------------------Backtesting & Orders-----------------------------
useTB1 = input(false, title="Time Break 1")
startTime1 = input(defval = timestamp("01 Jan 2017"), title = "TB Start Time", type = input.time)
days1 = input(title="TB 1 Range (days)", type=input.integer, defval=40, minval=1)
// useTB2 = input(false, title="Time Break 2")
//startTime2 = input(defval = timestamp("01 Aug 2017 00:00 +0000"), title = "TB Start Time", type = input.time)
// days2 = input(title="TB 2 Range (days)", type=input.integer, defval=20, minval=1)
useTR = input(true, title="Time Range")
startTime = input(defval = timestamp("01 Jan 2000"), title = "TR Start Time", type = input.time)
endTime = input(defval = timestamp("01 Jun 2020"), title = "TR End Time", type = input.time)
useWF = input(true, title="Walk-Forward")
weeks = input(title="WF Range (weeks)", type=input.integer, defval=50, minval=0)
//Time Range & Walk Forward Test
window() => // create function "within window of time"
time >= startTime and time <= endTime ? true : false
finish2 = endTime + weeks * timestamp(1970, 1, 8, 00, 00) // WF finish window
window2() => // To show the WF period
time >= endTime and time <= finish2 ? true : false
window3() => // To include the WF period and the backtest period
time >= startTime and time <= finish2 ? true : false
///Time Breaks
finish4 = startTime1 + days1 * timestamp(1970, 1, 2, 00, 00)
window4() => // create function "within window of time"
time >= startTime1 and time <= finish4 ? true : false
// finish5 = startTime2 + days2 * timestamp(1970, 1, 2, 00, 00)
// window5() => // create function "within window of time"
// time >= startTime2 and time <= finish5 ? true : false
if useTB1 and window4() //or useTB2 and window5()
longentry := 0
shortentry := 0
x2longentry := 0
x2shortentry := 0
//Strategy and Backtest Conditions
//smallOrder = (orderqty * ctorder) / close == 0 ? 2 : (orderqty * ctorder) / close
//smallOrder = strategy.equity * mcordqty / close
if useTR and useWF == false and window() or useWF and useTR == false and window2() or useWF and useTR and window3()
if lEntries == false
strategy.entry("Short", false, oca_name="oca_short", oca_type=strategy.oca.reduce, when=shortentry == 1)
//strategy.entry("2xShort", false, oca_name="oca_short", oca_type=strategy.oca.reduce, when=x2shortentry == 1)
if sEntries == false
strategy.entry("Long", true, oca_name="oca_long", oca_type=strategy.oca.reduce, when=longentry == 1)
//strategy.entry("2xLong", true, oca_name="oca_long", oca_type=strategy.oca.reduce, when=x2longentry == 1)
if strategy.position_size != 0
strategy.close("Short", when=shortexit == 1, comment="Exit") //
strategy.close("Long", when=longexit == 1, comment="Exit") //
strategy.close("2xShort", when=shortexit == 1, comment="Exit") //
strategy.close("2xLong", when=longexit == 1, comment="Exit") //
strategy.close_all(when=longexit == 4 or shortexit == 4, comment="Max Loss")
strategy.close_all(when=longexit == 5 or shortexit == 5, comment="Max Downturn")
strategy.exit("TP", qty_percent=100, stop=high, oca_name="oca_long", when=longexit == 2)
strategy.exit("TP", qty_percent=100, stop=low, oca_name="oca_short", when=shortexit == 2)
strategy.exit("SL", qty_percent=100, stop=high, oca_name="oca_long", when=longexit == 3)
strategy.exit("SL", qty_percent=100, stop=low, oca_name="oca_short", when=shortexit == 3)
//-------------------------Plotting----------------------------
plotchar(longCounter - shortCounter, title="Position Counter", char="•", color=color.white, transp=100, location=location.top, size=size.tiny)
plotchar(avgRet, title="Average Returns", char="•", color=color.white, transp=100, location=location.top, size=size.tiny)
cColor = bull ? color.lime : range ? color.maroon : color.orange
plot(mastrat ? ma2 : na, color=cColor, transp=0, title="MA Strat", style=plot.style_linebr)
plot(macrossstrat ? ma1 : na, color=color.blue)
plot(macrossstrat ? ma3 : na, color=color.orange)
plot(data, color=color.black)
hline(0)
hline(50, linestyle=hline.style_solid)
hline(-50, linestyle=hline.style_solid)
|
RMI + Triple HMRSI + Double EVWRSI + TERSI + CMO Strategy | https://www.tradingview.com/script/8KaVydkk-RMI-Triple-HMRSI-Double-EVWRSI-TERSI-CMO-Strategy/ | burgercrisis | https://www.tradingview.com/u/burgercrisis/ | 158 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © burgercrisis
//@version=4
strategy("RMI + Triple HMRSI + Double EVWRSI + TERSI Strategy")
//* Backtesting Period Selector | Component *//
//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made *//
testStartYear = input(2021, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testStopYear = input(999999, "Backtest Stop Year")
testStopMonth = input(9, "Backtest Stop Month")
testStopDay = input(26, "Backtest Stop Day")
testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
/////////////// END - Backtesting Period Selector | Component ///////////////
src = input(close, "Price", type = input.source)
CMOlength = input(9, minval=1, title="Alpha Chande Momentum Length")
//CMO
momm = change(src)
f1(m) => m >= 0.0 ? m : 0.0
f2(m) => m >= 0.0 ? 0.0 : -m
m1 = f1(momm)
m2 = f2(momm)
sm1 = sum(m1, CMOlength)
sm2 = sum(m2, CMOlength)
percent(nom, div) => 100 * nom / div
chandeMO = percent(sm1-sm2, sm1+sm2)
plot(chandeMO, "Chande MO", color=color.blue)
//RMI
// Copyright (c) 2018-present, Alex Orekhov (everget)
// Relative Momentum Index script may be freely distributed under the MIT license.
length3 = input(title="RMI Length", type=input.integer, minval=1, defval=30)
momentumLength3 = input(title="RMI Momentum ", type=input.integer, minval=1, defval=25)
up3 = rma(max(change(src, momentumLength3), 0), length3)
down3 = rma(-min(change(src, momentumLength3), 0), length3)
rmi3 = (down3 == 0 ? 100 : up3 == 0 ? 0 : 100 - (100 / (1 + up3 / down3)))-50
//
//
// end RMI, end Alex Orekhov copywrite
//
//
lengthMA = input(7)
lengthRSI = input(14)
thrsi = hma(hma(hma(rsi(src, lengthRSI), lengthMA), lengthMA), lengthMA)
thrsi1 = (thrsi-50)*10
lengthMA2 = input(7)
lengthRSI2 = input(14)
devwrsi = ((ema(ema(vwma(rsi(src, lengthRSI2), lengthMA2), lengthMA2), lengthMA2))-50)*5
lengthMA3 = input(7)
lengthRSI3 = input(14)
tersi = ((ema(ema(ema(rsi(src, lengthRSI3), lengthMA3), lengthMA3), lengthMA3))-50)*10
rmirsi = ((thrsi*rmi3/25))
//Boundary Lines
obLevel1 = input(0, title="Chande Sellline")
osLevel1 = input(0, title="Chande Buyline")
hline(obLevel1, color=#0bc4d9)
hline(osLevel1, color=#0bc4d9)
obLevel2 = input(0, title="Triple HMRSI Sellline")
osLevel2 = input(0, title="Triple HMRSI Buyline")
hline(obLevel2, color=#5a0bd9)
hline(osLevel2, color=#5a0bd9)
obLevel3 = input(0, title="DEVWRSI Sellline")
osLevel3 = input(0, title="DEVWRSI Buyline")
hline(obLevel3, color=#5a0bd9)
hline(osLevel3, color=#5a0bd9)
obLevel4 = input(0, title="TERSI Sellline")
osLevel4 = input(0, title="TERSI Buyline")
hline(obLevel4, color=#5a0bd9)
hline(osLevel4, color=#5a0bd9)
obLevel5 = input(0, title="RMI Sellline")
osLevel5 = input(0, title="RMI Buyline")
hline(obLevel5, color=#5a0bd9)
hline(osLevel5, color=#5a0bd9)
obLevel6 = input(0, title="RMI*RSI Sellline")
osLevel6 = input(0, title="RMI*RSI Buyline")
hline(obLevel6, color=#5a0bd9)
hline(osLevel6, color=#5a0bd9)
plot((thrsi1), title="THRSI")
plot(devwrsi, color=color.red, title="DEVWRSI")
plot(tersi, color=color.yellow, title="TERSI")
plot(rmirsi, color=color.purple, title="RMI*HMRSI")
plot(rmi3, color=color.orange, title="RMI")
longcondition1 = crossover(chandeMO, osLevel1)
shortcondition1 = crossunder(chandeMO, obLevel1)
longcondition2 = rmirsi<osLevel6 and rmi3<osLevel5 and tersi<osLevel4 and devwrsi<osLevel3 and thrsi1<osLevel2 and longcondition1
shortcondition2 = rmirsi>obLevel6 and rmi3>obLevel5 and tersi>obLevel4 and devwrsi>obLevel3 and thrsi1>obLevel2 and shortcondition1
if testPeriod()
if longcondition2
strategy.entry("Buy", strategy.long)
if shortcondition2
strategy.entry("Sell", strategy.short)
hline(0, color=#C0C0C0, linestyle=hline.style_dashed, title="Zero Line") |
Bollinger Band with Fib Golden Ratio (0.618) | https://www.tradingview.com/script/WrQQipHz-Bollinger-Band-with-Fib-Golden-Ratio-0-618/ | mohanee | https://www.tradingview.com/u/mohanee/ | 237 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mohanee
//@version=4
strategy(title="Bollinger Band with Fib Golden Ratio (0.618)", shorttitle="Bollinger Band with Fib Golden Ratio" , overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD)
length = input(50,title="BB Length" , minval=1)
src1 = input(hlc3, title="Source")
//mult1 = input(1.33, minval=0.001, maxval=50)
mult = input(1.5,title="multplier", minval=0.001, maxval=50)
stopLoss=input(5,title="Stop Loss",minval=1)
basis = vwma(src1, length)
dev = mult * stdev(src1, length)
//dev3 = mult3 * stdev(src, length)
upper_618= basis + (0.618*dev)
lower_618= basis - (0.618*dev)
//lower_618_dev3= basis - (0.618*dev3)
plot_upper618= plot(upper_618, color=color.purple, linewidth=2, title="0.618")
plot(basis, color=color.purple,style=plot.style_circles, linewidth=2)
plot_lower618= plot(lower_618, color=color.purple, linewidth=2, title="0.618 entry")
//plot_lower618_dev3= plot(lower_618_dev3, color=color.red, linewidth=1, title="0.618 stop")
//plot_lower618= plot(lower_618, color=color.purple, linewidth=1, title="0.618 entry")
ema200=ema(close,200)
ema50=ema(close,50)
plot (ema200, title="ema200", color=color.orange, linewidth=2)
plot (ema50, title="ema50", color=color.blue , linewidth=2)
longCondition= ema50 > ema200
strategy.entry(id="BB_Fib618", long=true, when = longCondition and ( close < lower_618 or low <= lower_618) )
strategy.close(id="BB_Fib618", comment="points="+tostring(close - strategy.position_avg_price, "###.##") , when = strategy.position_size >= 1 and crossover(close,upper_618 ))
//stoploss exit
stopLossVal = strategy.position_size>=1 ? strategy.position_avg_price * ( 1 - (stopLoss/100) ) : 0.00
strategy.close(id="BB_Fib618", comment="SL="+tostring(close - strategy.position_avg_price, "###.##"), when=abs(strategy.position_size)>=1 and close < stopLossVal ) //and close > strategy.position_avg_price )
|
Triple EMA Strategy | https://www.tradingview.com/script/a9mAFvYF-Triple-EMA-Strategy/ | IndoPilot | https://www.tradingview.com/u/IndoPilot/ | 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/
// © Matt Dearden - IndoPilot
// @version=4
/////////////////////////////////////////////////////// Initial Parameters ///////////////////////////////////////////////////////
SystemName = "Triple EMA Strategy"
ShortSystemName = "TEMA"
InitPosition = 100000
InitCapital = 100000
InitCommission = 0.004 //approx value to compensate for Oanda spreads
InitPyramidMax = 0
CalcOnorderFills = true
strategy(title=SystemName, shorttitle=ShortSystemName, overlay=true, pyramiding=InitPyramidMax,
default_qty_type=strategy.cash, default_qty_value=InitPosition, commission_type=strategy.commission.percent,
commission_value=InitCommission, initial_capital=InitCapital, max_lines_count=500,
max_labels_count=500, process_orders_on_close=false, calc_on_every_tick=false)
///////////////////////////////////////////////////////////// Inputs /////////////////////////////////////////////////////////////
DateFilter = input(false, "═════ Data Filtering ═════")
InitYear = input(title="Year", type=input.integer, defval=2021, minval=2000, maxval=2021)
InitMonth = input(title="Month (0=ALL)", type=input.integer, defval=0, minval=0, maxval=12)
InitStopLoss = input(title="Stop Loss (ticks)", type=input.integer, defval=100, minval=0, maxval=1000)
TrailingStopLoss = input(title="Trailing S/L (ticks)", type=input.integer, defval=130, minval=0, maxval=1000)
InitBuffer = input(title="Buffer (ticks)", type=input.integer, defval=15, minval=0, maxval=1000)
InitEMA1 = input(title="EMA 1", type=input.integer, defval=5, minval=0, maxval=1000)
InitEMA2 = input(title="EMA 2", type=input.integer, defval=20, minval=0, maxval=1000)
InitEMA3 = input(title="EMA 3", type=input.integer, defval=50, minval=0, maxval=1000)
//////////////////////////////////////////////////////////// Variables ///////////////////////////////////////////////////////////
var StopLoss = float(0.0)
var StartPrice = float(0.0)
//setup multipliers and catch JPY difference
Multiplier = syminfo.currency == "JPY" ? 10 : 1000
//get the daily exchange rate from yesterday
//X_rate = security(AccountCurrency+syminfo.currency, "D", close[1])
OrderQty = int(InitCapital / (InitStopLoss / Multiplier))
Buffer = InitBuffer / (Multiplier * 100)
/////////////////////////////////////////////////////// Triple EMA Strategy //////////////////////////////////////////////////////
EMA1 = ema(close, InitEMA1)
EMA2= ema(close, InitEMA2)
EMA3 = ema(close, InitEMA3)
//entry conditions
longCondition = crossover(EMA1, EMA2) and close > EMA3 and EMA1 > EMA3 and EMA2 > EMA3 and close > (close[1] + Buffer)
shortCondition = crossunder(EMA1, EMA2) and close < EMA3 and EMA1 < EMA3 and EMA2 < EMA3 and close < (close[1] - Buffer)
/////////////////////////////////////////////////////// Trailing Stoploss ////////////////////////////////////////////////////////
if (strategy.position_size > 0 and (close > (StartPrice + (TrailingStopLoss / (100 * Multiplier)))))
StopLoss := max(StopLoss, close - (TrailingStopLoss / (100 * Multiplier)))
strategy.exit("Long Stoploss", "Long", stop=StopLoss)
if (strategy.position_size < 0 and (close < (StartPrice - (InitStopLoss / (100 * Multiplier)))))
StopLoss := min(StopLoss, close + (TrailingStopLoss / (100 * Multiplier)))
strategy.exit("Short Stoploss", "Short", stop=StopLoss)
///////////////////////////////////////////////////////// Setup entries /////////////////////////////////////////////////////////
if (longCondition and year == InitYear and (InitMonth == 0 or month == InitMonth))
StartPrice := close
StopLoss := StartPrice - (InitStopLoss / (100 * Multiplier))
strategy.entry("Long", strategy.long, qty=OrderQty)
strategy.exit("Long Stoploss", "Long", stop=StopLoss)
if (shortCondition and year == InitYear and (InitMonth == 0 or month == InitMonth))
StartPrice := close
StopLoss := StartPrice + (InitStopLoss / (100 * Multiplier))
strategy.entry("Short", strategy.short, qty=OrderQty)
strategy.exit("Short Stoploss", "Short", stop=StopLoss)
///////////////////////////////////////////////////////// Draw the EMAs /////////////////////////////////////////////////////////
plot(EMA1, "EMA1", color=#00FF00)
plot(EMA2, "EMA2", color=#FF0000)
plot(EMA3, "EMA3", color=#4040FF)
|
Flawless Victory Strategy - 15min BTC Machine Learning Strategy | https://www.tradingview.com/script/i3Uc79fF-Flawless-Victory-Strategy-15min-BTC-Machine-Learning-Strategy/ | Bunghole | https://www.tradingview.com/u/Bunghole/ | 8,573 | 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/
// © Bunghole
//@version=4
strategy(overlay=true, shorttitle="Flawless Victory Strategy", default_qty_type = strategy.percent_of_equity, initial_capital = 100000, default_qty_value = 100, pyramiding = 0, title="Flawless Victory Strategy", currency = 'USD')
////////// ** Inputs ** //////////
// Stoploss and Profits Inputs
v1 = input(true, title="Version 1 - Doesn't Use SL/TP")
v2 = input(false, title="Version 2 - Uses SL/TP")
v3 = input(false, title="Version 3 - Uses SL/TP")
v2stoploss_input = input(6.604, title='Stop Loss %', type=input.float, minval=0.01)/100
v2takeprofit_input = input(2.328, title='Take Profit %', type=input.float, minval=0.01)/100
v2stoploss_level = strategy.position_avg_price * (1 - v2stoploss_input)
v2takeprofit_level = strategy.position_avg_price * (1 + v2takeprofit_input)
v3stoploss_input = input(8.882, title='Stop Loss %', type=input.float, minval=0.01)/100
v3takeprofit_input = input(2.317, title='Take Profit %', type=input.float, minval=0.01)/100
v3stoploss_level = strategy.position_avg_price * (1 - v3stoploss_input)
v3takeprofit_level = strategy.position_avg_price * (1 + v3takeprofit_input)
plot(v2 and v2stoploss_input and v2stoploss_level ? v2stoploss_level: na, color=color.red, style=plot.style_linebr, linewidth=2, title="v2 Stoploss")
plot(v2 and v2takeprofit_input ? v2takeprofit_level: na, color=color.green, style=plot.style_linebr, linewidth=2, title="v2 Profit")
plot(v3 and v3stoploss_input and v3stoploss_level ? v3stoploss_level: na, color=color.red, style=plot.style_linebr, linewidth=2, title="v3 Stoploss")
plot(v3 and v3takeprofit_input ? v3takeprofit_level: na, color=color.green, style=plot.style_linebr, linewidth=2, title="v3 Profit")
////////// ** Indicators ** //////////
// RSI
len = 14
src = close
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
// MFI
MFIlength = 14
MFIsrc = hlc3
MFIupper = sum(volume * (change(MFIsrc) <= 0 ? 0 : MFIsrc), MFIlength)
MFIlower = sum(volume * (change(MFIsrc) >= 0 ? 0 : MFIsrc), MFIlength)
_rsi(MFIupper, MFIlower) =>
if MFIlower == 0
100
if MFIupper == 0
0
100.0 - (100.0 / (1.0 + MFIupper / MFIlower))
mfi = _rsi(MFIupper, MFIlower)
// v1 Bollinger Bands
length1 = 20
src1 = close
mult1 = 1.0
basis1 = sma(src1, length1)
dev1 = mult1 * stdev(src1, length1)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
// v2 Bollinger Bands
length2 = 17
src2 = close
mult2 = 1.0
basis2 = sma(src2, length2)
dev2 = mult2 * stdev(src2, length2)
upper2 = basis2 + dev2
lower2 = basis2 - dev2
////////// ** Triggers and Guards ** //////////
// v1 Strategy Parameters
RSILowerLevel1 = 42
RSIUpperLevel1 = 70
BBBuyTrigger1 = src1 < lower1
BBSellTrigger1 = src1 > upper1
rsiBuyGuard1 = rsi > RSILowerLevel1
rsiSellGuard1 = rsi > RSIUpperLevel1
// v2 Strategy Parameters
RSILowerLevel2 = 42
RSIUpperLevel2 = 76
BBBuyTrigger2 = src2 < lower2
BBSellTrigger2 = src2 > upper2
rsiBuyGuard2 = rsi > RSILowerLevel2
rsiSellGuard2 = rsi > RSIUpperLevel2
// v3 Strategy Parameters
MFILowerLevel3 = 60
RSIUpperLevel3 = 65
MFIUpperLevel3 = 64
BBBuyTrigger3 = src1 < lower1
BBSellTrigger3 = src1 > upper1
mfiBuyGuard3 = mfi < MFILowerLevel3
rsiSellGuard3 = rsi > RSIUpperLevel3
mfiSellGuard3 = mfi > MFIUpperLevel3
//////////** Strategy Signals ** //////////
// v1 Signals
Buy_1 = BBBuyTrigger1 and rsiBuyGuard1
Sell_1 = BBSellTrigger1 and rsiSellGuard1
if v1 == true
strategy.entry("Long", strategy.long, when = Buy_1, alert_message = "v1 - Buy Signal!")
strategy.close("Long", when = Sell_1, alert_message = "v1 - Sell Signal!")
// v2 Signals
Buy_2 = BBBuyTrigger2 and rsiBuyGuard2
Sell_2 = BBSellTrigger2 and rsiSellGuard2
if v2 == true
strategy.entry("Long", strategy.long, when = Buy_2, alert_message = "v2 - Buy Signal!")
strategy.close("Long", when = Sell_2, alert_message = "v2 - Sell Signal!")
strategy.exit("Stoploss/TP", "Long", stop = v2stoploss_level, limit = v2takeprofit_level)
// v3 Signals
Buy_3 = BBBuyTrigger3 and mfiBuyGuard3
Sell_3 = BBSellTrigger3 and rsiSellGuard3 and mfiSellGuard3
if v3 == true
strategy.entry("Long", strategy.long, when = Buy_3, alert_message = "v2 - Buy Signal!")
strategy.close("Long", when = Sell_3, alert_message = "v2 - Sell Signal!")
strategy.exit("Stoploss/TP", "Long", stop = v3stoploss_level, limit = v3takeprofit_level)
|
Basic SMA 200 Strategy | https://www.tradingview.com/script/EXtBltMY-Basic-SMA-200-Strategy/ | Ichimoku-Trading | https://www.tradingview.com/u/Ichimoku-Trading/ | 142 | 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/
// © Ichimoku-Trading by TradersEldorado
//@version=4
strategy("simple MA 200 cross", overlay=true)
//Inputs
MA_Len = input(title="Moving Average Length", type=input.integer, defval=200)
//Moving Average
MA = sma(close, MA_Len)
//Entry
longCondition = crossover(close, MA)
if (longCondition)
strategy.entry("Long", strategy.long)
//Exit
exitCondition = crossunder(close, MA)
if (exitCondition)
strategy.close("Long")
//Plot
plot(MA, title="Moving Average")
plotshape(longCondition, style=shape.arrowup, color=color.green, location=location.belowbar, size=size.normal, title="Entry", text="Entry")
plotshape(exitCondition, style=shape.arrowdown, color=color.red, location=location.abovebar, size=size.normal, title="Exit", text="Exit") |
McClellan Oscillator Strategy | https://www.tradingview.com/script/pxfqn7b4-McClellan-Oscillator-Strategy/ | sparrow_hawk_737 | https://www.tradingview.com/u/sparrow_hawk_737/ | 57 | 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/
// © sparrow_hawk_737
//@version=3
strategy("McClellan Oscillator Strategy", default_qty_type=strategy.percent_of_equity, default_qty_value=100)
exitWhenOscIsZero = input(false, title="Exit when oscillator goes under 0?")
enterWhenOscIsZero = input(false, title="Enter when oscillator goes over 0?")
isRA=input(true, title="Stockcharts version (Ratio Adjusted)?")
rm=input(defval=1000, title="RANA ratio multiplier")
showEMAs=input(false, title="Show EMAs?")
showOsc=input(true, title="Show Oscillator?")
slowLengthSell = input(20, title="Slow Length Sell")
fastLengthSell = input(9, title="Fast Length Sell")
slowLengthBuy = input(20, title="Slow Length Buy")
fastLengthBuy = input(9, title="Fast Length Buy")
useCTF=input(false, title="Use Custom Timeframe?"),
tf=useCTF?input("D", type=resolution, title="Custom Timeframe"):period // Recommend NOT enabling this
gaps=barmerge.gaps_off // Recommend leaving this OFF
src=close
// Varianta doar cu NYSE sau doar cu NASDAQ da semnale long mai proaste decat
// varianta cu toate bursele, dar uneori (f rar) cea cu NYSE le da mai devreme.
use_ny=input(100.0,"NYSE %")/100
use_nq=input(0,"NASDAQ %")/100
use_us=input(100.0,"US %")/100
use_dj=input(0,"DJ %")/100
use_ax=input(100.0,"AX %")/100
use_am=input(0,"AM %")/100
ai=0.0, di=0.0
adv=use_ny*nz(security("ADVN.NY", tf, src, gaps))+use_nq*nz(security("ADVN.NQ", tf, src, gaps))+use_us*nz(security("ADVN.US", tf, src, gaps))+use_dj*nz(security("ADVN.DJ", tf, src, gaps))+use_ax*nz(security("ADVN.AX", tf, src, gaps))+use_am*nz(security("ADVN.AM", tf, src, gaps))
dec=use_ny*nz(security("DECL.NY", tf, src, gaps))+use_nq*nz(security("DECL.NQ", tf, src, gaps))+use_us*nz(security("DECL.US", tf, src, gaps))+use_dj*nz(security("DECL.DJ", tf, src, gaps))+use_ax*nz(security("DECL.AX", tf, src, gaps))+use_am*nz(security("DECL.AM", tf, src, gaps))
ai:=ai+adv, di:=di+dec
rana=rm * (ai-di)/(ai+di)
moonel = input(16, "mo1 length")
mtwol = input(36, "mo2 length")
e1=isRA?ema(rana, moonel):ema(ai-di, moonel),e2=isRA?ema(rana, mtwol):ema(ai-di, mtwol)
mo=e1-e2
hline(0, title="0")
plot(showOsc?mo<0?mo:0:na, style=area, color=white, title="-")
plot(showOsc?mo>=0?mo:0:na, style=area, color=white, title="+")
plot(showOsc?mo:na, style=line, color=black, title="MO", linewidth=2)
plot(showEMAs?e1:na, color=blue, linewidth=2, title="19 EMA")
plot(showEMAs?e2:na, color=red, linewidth=2, title="39 EMA")
short= mo>=100 and mo<mo[1]
long= mo<=-100 and mo>mo[1]
bgcolor(long ? green : short ? red : white, transp=75)
alertcondition(long and not long[1], "McC long ", "McC long ")
alertcondition(short and not short[1], "McC short ", "McC short ")
exited = false
inpos = strategy.position_size > 0
mas1 = ema(mo, fastLengthSell)
mas2 = ema(mo, slowLengthSell)
mab1 = ema(mo, fastLengthBuy)
mab2 = ema(mo, slowLengthBuy)
plot(mas1, color=blue, linewidth=2, title="39 EMA")
plot(mas2, color=orange, linewidth=2, title="39 EMA")
plot(mab1, color=red, linewidth=2, title="39 EMA")
plot(mab2, color=black, linewidth=2, title="39 EMA")
get_bbr(x, length) =>
mult = 2
basis = sma(x, length)
dev = mult * stdev(x, length)
upper = basis + dev
lower = basis - dev
(x - lower)/(upper - lower)
vxx = security("VXX", "", close)
vvix = security("VVIX", "", close)
bbr1 = get_bbr(vvix, input(10, title="vvix bbr length"))
bbr2 = get_bbr(vxx, input(20,title="vxx bbr length"))
mmthsell = input(true, "Only sell when percent of X stocks is in downtrend")
// 25 is the max observed so far
mmth = sma(security(input("MMOH", "Percent of stocks above X"), "", close), input(20, "percent of stocks length"))
mmthlow =( ( mmth[0] - mmth[1] ) + ( mmth[1] - mmth[2] ) + ( mmth[2] - mmth[3] ) ) / 3 < 0
mmfi = security("MMFI", "", close)
mmfibbr = get_bbr(mmfi, 100)
buy2 = mmfibbr >= 0 and ( mmfibbr[1] <= 0.01)
skew = security("SKEW", "", close)
skewma = sma(skew, input(10, "SKEW MA LENGTH"))
skewpos = ( ( (skewma - skewma[1]) + (skewma[1] - skewma[2]) + (skewma[2] - skewma[3]) ) / 3) > 0
skbbr = get_bbr(skew, input(29, "skew bbr length"))
skewthresh = input(1.1, "skew bbr thresh")
extremenegativeskew = (skbbr > skewthresh) or (skbbr[1] > skewthresh)
v1 = security("VX1!", "", close)
v2 = security("VX2!", "", close)
vix = security("VIX", "", close)
roll_yield = (v1 - vix) / vix
shape = ( v2 - v1 )
rysell = roll_yield <= 0.01
plot(roll_yield * 100, color=orange, linewidth=2,title="ROLL YIELD")
plot(shape * 10, color=yellow, linewidth=2,title="VIX SHAPE")
iwm = security("IWM", "", close)
iwmma12 = sma(iwm, input(12))
buy3 = iwm > iwmma12
sell = rysell and mmthlow and ( crossunder(mas1, mas2) or mas1 < mas2 ) and ( bbr1 >= 0.90 or bbr2 >= 0.90 and mas1 < mas1[1]) and not extremenegativeskew and not buy3
preznobuy = ((year - 2004) % 4 == 0 and month == 10 ? dayofmonth < 10 and dayofmonth > 31 : true)
prezsell = ((year - 2004) % 4 == 0 and month == 10 ? dayofmonth >= 10 and dayofmonth <= 17 : false)
if (preznobuy and extremenegativeskew and strategy.position_size <= 0)
strategy.entry("extremenegativeskew", strategy.long)
if (preznobuy and ( (crossover(mab1, mab2) or mab1 > mab2)) and strategy.position_size <= 0)
strategy.entry("mab cross", strategy.long)
if (preznobuy and (buy2 and skewpos) and strategy.position_size <= 0)
strategy.entry("mmfi + skew bottom", strategy.long)
if (preznobuy and (buy3 and skewpos) and strategy.position_size <= 0)
strategy.entry("RUS bottom", strategy.long)
if ((prezsell or sell) and strategy.position_size > 0)
strategy.close_all()
|
Zweig Market Breadth Thrust Indicator Strategy | https://www.tradingview.com/script/f31wnImM-Zweig-Market-Breadth-Thrust-Indicator-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 277 | 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("Zweig Market Breadth Thrust Indicator Strategy", overlay=false, pyramiding=3 , default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD)
ma_type = input("EMA", options=["SMA","EMA","WMA"] )
ma_length = input(defval=65, minval=1, title="MA Length")
mkt = input ("NYSE" , options=["NYSE","NASDAQ", "AMEX", "COMBINED"] )
buyEntryAt = input(0.40, minval=0.10, maxval=0.60)
stopLoss = input(title="Stop Loss%", defval=5, minval=1)
trailingStop = input(false, title="Trailing Stop")
partialCloseIndicator = input("RSI", title="Partial Close using Indicator ", options=["ZWEIG", "RSI"])
colorOBOS = input(true, title="Color OB/OS")
showDecLineThrust= input(false, title="show DecLine Thrust")
//function
getMAval(s,l, ma_type) => ma_type== "SMA" ? sma(s,l): ma_type== "EMA" ? ema(s,l) : ma_type=="WMA" ? wma(s,l) : sma(s,l)
//calculate Zweig Market Breadth Thrust
/////////////////////////////////////////////////////////////
res = "D"
advn="ADVN", decn="DECN" // NYSE
advnq="ADVQ", decnq="DECQ" // NASDAQ
advna="ADVA", decna="DECA" // AMEX
advc="(ADVN+ADVQ+ADVA)/3.0"
decc="(DECN+DECQ+DECA)/3.0"
adv= security(mkt=="COMBINED" ? advc:mkt == "NYSE" ? advn: mkt == "NASDAQ" ? advnq : mkt == "AMEX" ? advna:na, res, close) //res
dec= security(mkt=="COMBINED" ? decc:mkt == "NYSE" ? decn:mkt == "NASDAQ" ? decnq : mkt == "AMEX" ? decna:na, res, close)
zmbti = getMAval(adv/(adv+dec), ma_length, ma_type)
zmbtr = getMAval(dec/(adv+dec), ma_length, ma_type)
//calculate Zweig Market Breadth Thrust
/////////////////////////////////////////////////////////////
myRsi = rsi(close, 5)
//Plot
/////////////////////////////////////////////////////////////
osl=plot(buyEntryAt, color=color.gray, style=plot.style_linebr, title="OS")
//osl1=plot(0.45, color=color.blue, style=plot.style_circles, linewidth=2 , title="OS1")
obl=plot(0.615, color=color.gray, style=plot.style_linebr, title="OB")
osd=plot(colorOBOS?(zmbti<buyEntryAt?zmbti:buyEntryAt):na, style=plot.style_linebr,linewidth=0, title="DummyOS")
obd=plot(colorOBOS?(zmbti>0.615?zmbti:0.615):na, style=plot.style_linebr, linewidth=0, title="DummyOB")
fill(osl,obl,color.purple, title="RegionFill")
fill(osl, osd, color.green, transp=60, title="OSFill")
fill(obl, obd, color.red, transp=60, title="OBFill")
plot(zmbti, color=color.blue, linewidth=2, title="BreadthThrust(advances)")
plot(showDecLineThrust == true ? zmbtr : na, color=color.red, linewidth=2, title="BreadthThrust(declines)")
//plot
/////////////////////////////////////////////////////////////
//Strategy
/////////////////////////////////////////////////////////////
strategy.entry(id="zmbtiLong" , long=true, when=crossover(zmbti, buyEntryAt) )
////// Calculate trailing SL
sl_val = close * stopLoss / 100
trailing_sl = 0.0
trailing_sl := strategy.position_size>=1 ? max(low - sl_val, nz(trailing_sl[1])) : na
stopLossVal = strategy.position_size>=1 ? strategy.position_avg_price * ( 1 - (stopLoss / 100) ) : 0.00
//draw initil stop loss
//plot(strategy.position_size>=1 ? trailing_sl : na, color = color.blue , style=plot.style_linebr, linewidth = 2, title = "stop loss")
//exit partial position when zmbti crossing down OB level
strategy.close(id="zmbtiLong" , comment="Partial close ZWEIG" , qty=strategy.position_size/3 , when=strategy.position_size>=1 and partialCloseIndicator=="ZWEIG" and close>strategy.position_avg_price and crossunder(zmbti, 0.6) )
strategy.close(id="zmbtiLong" , comment="Partial close RSI" , qty=strategy.position_size/3 , when=strategy.position_size>=1 and partialCloseIndicator=="RSI" and close>strategy.position_avg_price and crossunder(myRsi, 90) )
//exit whole position when zmbti turns back to OS Level
strategy.close(id="zmbtiLong" , comment="close all" , when=strategy.position_size>=1 and close >strategy.position_avg_price and crossunder(zmbti , buyEntryAt) )
//exit whole position when stop loss hits
strategy.close(id="zmbtiLong" , comment="TSL", when=strategy.position_size>=1 and trailingStop==true and close < trailing_sl ) //if trailing stop is set
strategy.close(id="zmbtiLong" , comment="SL", when=strategy.position_size>=1 and close < stopLossVal ) //if trailing stop is NOT set
|
(IK) Grid Script | https://www.tradingview.com/script/IIchZZ2m-IK-Grid-Script/ | tapRoot_coding | https://www.tradingview.com/u/tapRoot_coding/ | 1,111 | 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/
// © tapRoot_coding - Ian Kuzmik
//@version=4
strategy("(IK) Grid Script", overlay=true, pyramiding=14, close_entries_rule="ANY", default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)
// == INPUT ==
i_autoBounds = input(group="Grid Bounds", title="Use Auto Bounds?", defval=false, type=input.bool) // calculate upper and lower bound of the grid automatically? This will theorhetically be less profitable, but will certainly require less attention
i_boundSrc = input(group="Grid Bounds", title="(Auto) Bound Source", defval="Hi & Low", options=["Hi & Low", "Average"]) // should bounds of the auto grid be calculated from recent High & Low, or from a Simple Moving Average
i_boundLookback = input(group="Grid Bounds", title="(Auto) Bound Lookback", defval=250, type=input.integer, maxval=500, minval=0) // when calculating auto grid bounds, how far back should we look for a High & Low, or what should the length be of our sma
i_boundDev = input(group="Grid Bounds", title="(Auto) Bound Deviation", defval=0.10, type=input.float, maxval=1, minval=-1) // if sourcing auto bounds from High & Low, this percentage will (positive) widen or (negative) narrow the bound limits. If sourcing from Average, this is the deviation (up and down) from the sma, and CANNOT be negative.
i_upperBound = input(group="Grid Bounds", title="(Manual) Upper Boundry", defval=0.285, type=input.float) // for manual grid bounds only. The upperbound price of your grid
i_lowerBound = input(group="Grid Bounds", title="(Manual) Lower Boundry", defval=0.225, type=input.float) // for manual grid bounds only. The lowerbound price of your grid.
i_gridQty = input(group="Grid Lines", title="Grid Line Quantity", defval=8, maxval=15, minval=3, type=input.integer) // how many grid lines are in your grid
// == FUNCTIONS ==
// for auto grid only. return the upperbound if _up == true, or the lowerbound if _up == false
f_getGridBounds(_bs, _bl, _bd, _up) =>
if _bs == "Hi & Low"
_up ? highest(close, _bl) * (1 + _bd) : lowest(close, _bl) * (1 - _bd)
else
avg = sma(close, _bl)
_up ? avg * (1 + _bd) : avg * (1 - _bd)
// using the lowerbound, grid width, and grid line quantity, build an array of prices (grid lines) from the bottom up
f_buildGrid(_lb, _gw, _gq) =>
gridArr = array.new_float(0)
for i=0 to _gq-1
array.push(gridArr, _lb+(_gw*i))
gridArr
// return an array that contains the closest grid lines above and below current price (not counting the line price is currently on). This is solely for plotting purposes
f_getNearGridLines(_gridArr, _price) =>
arr = array.new_int(3)
for i = 0 to array.size(_gridArr)-1
if array.get(_gridArr, i) > _price
array.set(arr, 0, i == array.size(_gridArr)-1 ? i : i+1)
array.set(arr, 1, i == 0 ? i : i-1)
break
arr
// == VARIABLES ==
var upperBound = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true) : i_upperBound // upperbound of our grid
var lowerBound = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false) : i_lowerBound // lowerbound of our grid
var gridWidth = (upperBound - lowerBound)/(i_gridQty-1) // space between lines in our grid
var gridLineArr = f_buildGrid(lowerBound, gridWidth, i_gridQty) // an array of prices that correspond to our grid lines
var orderArr = array.new_bool(i_gridQty, false) // a boolean array that indicates if there is an open order corresponding to each grid line
var closeLineArr = f_getNearGridLines(gridLineArr, close) // for plotting purposes - an array of 2 indices that correspond to grid lines near price
var nearTopGridLine = array.get(closeLineArr, 0) // for plotting purposes - the index (in our grid line array) of the closest grid line above current price
var nearBotGridLine = array.get(closeLineArr, 1) // for plotting purposes - the index (in our grid line array) of the closest grid line below current price
// == LOGIC ==
// ENTRY & EXIT
for i = 0 to (array.size(gridLineArr) - 1)
if close < array.get(gridLineArr, i) and not array.get(orderArr, i) and i < (array.size(gridLineArr) - 1)
buyId = i
array.set(orderArr, buyId, true)
strategy.entry(id=tostring(buyId), long=true, qty=(strategy.initial_capital/(i_gridQty-1))/close, comment="#"+tostring(buyId))
if close > array.get(gridLineArr, i) and i != 0
if array.get(orderArr, i-1)
sellId = i-1
array.set(orderArr, sellId, false)
strategy.close(id=tostring(sellId), comment="#"+tostring(sellId))
// MAINTAIN GRID
// update auto grid (if active)
if i_autoBounds
upperBound := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true)
lowerBound := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false)
gridWidth := (upperBound - lowerBound)/(i_gridQty-1)
gridLineArr := f_buildGrid(lowerBound, gridWidth, i_gridQty)
// update near grid lines (for plotting purposes)
closeLineArr := f_getNearGridLines(gridLineArr, close)
nearTopGridLine := array.get(closeLineArr, 0)
nearBotGridLine := array.get(closeLineArr, 1)
// plot grid lines
plot(array.size(gridLineArr) > 0 ? array.get(gridLineArr,0) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 1 ? array.get(gridLineArr,1) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 2 ? array.get(gridLineArr,2) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 3 ? array.get(gridLineArr,3) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 4 ? array.get(gridLineArr,4) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 5 ? array.get(gridLineArr,5) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 6 ? array.get(gridLineArr,6) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 7 ? array.get(gridLineArr,7) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 8 ? array.get(gridLineArr,8) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 9 ? array.get(gridLineArr,9) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 10 ? array.get(gridLineArr,10) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 11 ? array.get(gridLineArr,11) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 12 ? array.get(gridLineArr,12) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 13 ? array.get(gridLineArr,13) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 14 ? array.get(gridLineArr,14) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
// plot near grid lines
plot(array.get(gridLineArr, nearTopGridLine), color=color.rgb(255,0,255,20), style=plot.style_stepline, linewidth=2)
plot(array.get(gridLineArr, nearBotGridLine), color=color.rgb(0,0,255,20), style=plot.style_stepline, linewidth=2)
|
SMIO strat | https://www.tradingview.com/script/N8nGnOsj-SMIO-strat/ | Nico_TM | https://www.tradingview.com/u/Nico_TM/ | 29 | 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/
// © Nico_TM
//@version=4
strategy(shorttitle= "MFM", title= "SMIO", overlay=true)
longlen = input(35, minval=1, title="Long Length")
shortlen = input(15, minval=1, title="Short Length")
siglen = input(15, minval=1, title="Signal Line Length")
erg = tsi(close, shortlen, longlen)
sig = ema(erg, siglen)
osc = erg - sig
plot(osc, color=#FF8080, style=plot.style_histogram, title="SMI Ergodic Oscillator")
long = crossover(osc, 0)
short = crossunder(osc, 0)
strategy.entry("long", true, when = long)
strategy.entry("short", false, when = short)
strategy.close("long", when = short)
strategy.close("short", when = long)
start = timestamp(2020, 6, 1, 0, 0)
end = timestamp(2021, 6, 1 ,0, 0) |
Hi-Lo Channel Strategy | https://www.tradingview.com/script/nGQYrGYv-Hi-Lo-Channel-Strategy/ | shiner_trading | https://www.tradingview.com/u/shiner_trading/ | 116 | 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/
// © shiner_trading
// [email protected]
//@version=4
strategy("Hi-Lo Channel Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital=500, default_qty_value=100, currency="USD")
lenh = input(5, "High-Based MA")
lenl = input (5, "Low-Based MA")
ha = input(true, "Use Heikin Ashi OHCL values (on real chart)?")
ha_h = security(heikinashi(syminfo.tickerid), timeframe.period, high)
ha_l = security(heikinashi(syminfo.tickerid), timeframe.period, low)
ha_c = security(heikinashi(syminfo.tickerid), timeframe.period, close)
float mah = na
float mal = na
longCondition = false
shortCondition = false
/// HA is the check mark box in the configuration.
/// IF "Use Heikin Ashi OHCL values?" is true, then the strategy will use the Heikin Ashi close values
// and therefore give the same buy/sell signals regardless of what chart you are viewing.
/// That being said, if "Use Heikin Ashi OHCL values?" is FALSE, yet you are viewing Heikin Ashi candles on your chart,
// then logically you will also get the same buy/sell signals
if ha == true
mah := sma(ha_h, lenh)
mal := sma(ha_l, lenl)
longCondition := ha_c > mah
shortCondition := ha_c < mal
if ha == false
mah := sma(high, lenh)
mal := sma(low, lenl)
longCondition := close > mah
shortCondition := close < mal
plot(mah, color=color.green)
plot(mal, color=color.red)
if (longCondition)
strategy.entry("Buy", 100)
if (shortCondition)
strategy.close("Buy") |
RSI Trend Crypto | https://www.tradingview.com/script/Ru7qOVtp-RSI-Trend-Crypto/ | FieryTrading | https://www.tradingview.com/u/FieryTrading/ | 1,852 | 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/
// © FieryTrading
//@version=4
strategy("RSI Trend Crypto", overlay=false, pyramiding=1, commission_value=0.2, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Input
UseEmergency = input(false, "Use Emergency Exit?")
RSIlong = input(35, "RSI Long Cross")
RSIclose = input(75, "RSI Close Position")
Emergencyclose = input(10, "RSI Emergency Close Position")
// RSI
rsi = rsi(close, 14)
// Conditions
long = crossover(rsi, RSIlong)
longclose = crossunder(rsi, RSIclose)
emergency = crossunder(rsi, Emergencyclose)
// Plots
plot(rsi, color=color.white, linewidth=2)
plot(RSIlong, color=color.green)
plot(RSIclose, color=color.red)
// Alert messages
// When using a bot remember to use "{{strategy.order.alert_message}}" in your alert
// You can edit the alert message freely to suit your needs
LongAlert = 'RSI Long Cross: LONG'
CloseAlert = 'RSI Close Position'
EmergencyAlert = 'RSI Emergency Close'
// Strategy
if long
strategy.entry("Long", strategy.long, alert_message=LongAlert)
if longclose
strategy.close("Long", alert_message=CloseAlert)
if emergency and UseEmergency==true
strategy.close("Long", alert_message=EmergencyAlert)
|
Backtesting 3commas DCA Bot v2 | https://www.tradingview.com/script/8d6Auyst-Backtesting-3commas-DCA-Bot-v2/ | rouxam | https://www.tradingview.com/u/rouxam/ | 4,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/
// © rouxam
//@version=4
// Author: rouxam
strategy("Backtesting 3commas DCA Bot v2", overlay=true, pyramiding=99, process_orders_on_close=true, commission_type=strategy.commission.percent, commission_value=0.1, initial_capital=3009)
// Important Note : Initial Capital above is written to match the default value based on bot parameters.
// It is expected the user will update the initial_capital via the GUI Parameters > Properties tab
// A warning will displayed in case initial capital and max amount for bot usage do not match.
// ----------------------------------
// Strategy Inputs
// ----------------------------------
take_profit = input(4.5, type=input.float, title="Take Profit (%)", minval=0.0, step=0.1)/100
take_profit_type = input(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])
ttp = input(0.0, type=input.float, title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100
stop_loss = input(0.0, type=input.float, title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100
order_size_type = input(defval="Fixed", title="Order Size Type", options=["Fixed", "% of equity"])
base_order = input(100.0, type=input.float,title="Base Order")
safe_order = input(140.0, type=input.float,title="Safety Order")
max_safe_order = input(6, title="Max Safety Trades Count", minval=0, maxval=99, step=1)
price_deviation = input(1.5, type=input.float, title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100
safe_order_volume_scale = input(1.5, type=input.float, title="Safety Order Volume Scale", step=0.1)
safe_order_step_scale = input(1.6, type=input.float, title="Safety Order Step Scale", step=0.1)
dsc = input(defval="RSI-7", title="Deal Start Condition", options=["Start ASAP", "RSI-7", "TV presets"])
dsc_rsi_threshold = input(defval=30, title="[RSI-7 only] RSI Threshold", minval=1, maxval=99)
dsc_technicals = input(defval="Strong", title="[TV presets only] Strength", options=["Strong", "Weak"])
dsc_res = input("", title="[RSI-7 and TV presets Only] Indicator Timeframe", type=input.resolution)
bot_direction = input(defval="Long", title="Bot Direction", options=["Long", "Short"])
start_time = input(defval=timestamp("15 June 2021 06:00"), title="Start Time", type=input.time)
end_time = input(defval=timestamp("31 Dec 2021 20:00"), title="End Time", type=input.time)
// ----------------------------------
// Declarations
// ----------------------------------
var bo_level = 0.0
var last_so_level = 0.0
var so_level = 0.0
var ttp_active = false
var ttp_extremum = 0.0
var ttp_level = 0.0
var stop_level = 0.0
var take_profit_level = 0.0
var deal_counter = 0
var stop_loss_counter = 0
var stop_loss_on_bar = false
var latest_price = close
var deal_start_condition = false
var start_time_actual = start_time
var end_time_actual = start_time
// CONSTANTS
var float init_price = na
var IS_LONG = bot_direction == "Long"
// ----------------------------------
// Utilities functions
// ----------------------------------
pretty_date(t) => tostring(dayofmonth(t)) + "/" + tostring(month(t)) + "/" + tostring(year(t))
within_window() => time >= start_time and time <= end_time
base_order_size() => order_size_type == "Fixed" ? base_order : base_order/100 * strategy.equity
safe_order_size() => order_size_type == "Fixed" ? safe_order : safe_order/100 * strategy.equity
safety_order_deviation(index) => price_deviation * pow(safe_order_step_scale, index - 1)
safety_order_price(index, last_safety_order_price) =>
if IS_LONG
last_safety_order_price * (1 - safety_order_deviation(index))
else
last_safety_order_price * (1 + safety_order_deviation(index))
safety_order_qty(index) => safe_order_size() * pow(safe_order_volume_scale, index - 1)
max_amount_for_bot_usage() =>
var total_qty = 0.0
var last_order_qty = 0.0
total_qty := base_order_size()
last_order_qty := safe_order_size()
if max_safe_order > 0
for index = 1 to max_safe_order
total_qty := total_qty + safety_order_qty(index)
total_qty // returned value
max_deviation() =>
var total_deviation = 0.0
total_deviation := 0.0
for index = 1 to max_safe_order
total_deviation := total_deviation + safety_order_deviation(index)
currency_format() =>
if syminfo.currency == "USDT" or syminfo.currency == "USD" or syminfo.currency == "TUSD" or syminfo.currency == "BUSD" or syminfo.currency == "USDC" or syminfo.currency == "EUR" or syminfo.currency == "AUD"
"#.##"
else if syminfo.currency == "BTC"
"#.########"
else
// TODO (rouxam) list more options
"#.####"
// ***********************************
// Deal Start Condition Strategies
// ***********************************
// RSI-7
// ***********************************
rsi_signal() =>
// Regular strat would be crossover but not for 3C DCA Bot
rsi7 = rsi(close, 7)
if IS_LONG
[rsi7 < dsc_rsi_threshold, close]
else
[rsi7 > dsc_rsi_threshold, close]
// TV presets
// ***********************************
// This whole section is from the TradingView "Technical Ratings" code.
// Adding the Technical Ratings "indicator" as input to this "strategy" is not sufficient for our purpose,
// Therefore the code is copy-pasted.
// ***********************************
// Awesome Oscillator
AO() =>
sma(hl2, 5) - sma(hl2, 34)
// Stochastic RSI
StochRSI() =>
rsi1 = rsi(close, 14)
K = sma(stoch(rsi1, rsi1, rsi1, 14), 3)
D = sma(K, 3)
[K, D]
// Ultimate Oscillator
tl() => close[1] < low ? close[1]: low
uo(ShortLen, MiddlLen, LongLen) =>
Value1 = sum(tr, ShortLen)
Value2 = sum(tr, MiddlLen)
Value3 = sum(tr, LongLen)
Value4 = sum(close - tl(), ShortLen)
Value5 = sum(close - tl(), MiddlLen)
Value6 = sum(close - tl(), LongLen)
float UO = na
if Value1 != 0 and Value2 != 0 and Value3 != 0
var0 = LongLen / ShortLen
var1 = LongLen / MiddlLen
Value7 = (Value4 / Value1) * (var0)
Value8 = (Value5 / Value2) * (var1)
Value9 = (Value6 / Value3)
UO := (Value7 + Value8 + Value9) / (var0 + var1 + 1)
UO
// Ichimoku Cloud
donchian(len) => avg(lowest(len), highest(len))
ichimoku_cloud() =>
conversionLine = donchian(9)
baseLine = donchian(26)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(52)
[conversionLine, baseLine, leadLine1, leadLine2]
calcRatingMA(ma, src) => na(ma) or na(src) ? na : (ma == src ? 0 : ( ma < src ? 1 : -1 ))
calcRating(buy, sell) => buy ? 1 : ( sell ? -1 : 0 )
ta_presets_signal() =>
//============== MA =================
SMA10 = sma(close, 10)
SMA20 = sma(close, 20)
SMA30 = sma(close, 30)
SMA50 = sma(close, 50)
SMA100 = sma(close, 100)
SMA200 = sma(close, 200)
EMA10 = ema(close, 10)
EMA20 = ema(close, 20)
EMA30 = ema(close, 30)
EMA50 = ema(close, 50)
EMA100 = ema(close, 100)
EMA200 = ema(close, 200)
HullMA9 = hma(close, 9)
// Volume Weighted Moving Average (VWMA)
VWMA = vwma(close, 20)
[IC_CLine, IC_BLine, IC_Lead1, IC_Lead2] = ichimoku_cloud()
// ======= Other =============
// Relative Strength Index, RSI
RSI = rsi(close,14)
// Stochastic
lengthStoch = 14
smoothKStoch = 3
smoothDStoch = 3
kStoch = sma(stoch(close, high, low, lengthStoch), smoothKStoch)
dStoch = sma(kStoch, smoothDStoch)
// Commodity Channel Index, CCI
CCI = cci(close, 20)
// Average Directional Index
float adxValue = na, float adxPlus = na, float adxMinus = na
[P, M, V] = dmi(14, 14)
adxValue := V
adxPlus := P
adxMinus := M
// Awesome Oscillator
ao = AO()
// Momentum
Mom = mom(close, 10)
// Moving Average Convergence/Divergence, MACD
[macdMACD, signalMACD, _] = macd(close, 12, 26, 9)
// Stochastic RSI
[Stoch_RSI_K, Stoch_RSI_D] = StochRSI()
// Williams Percent Range
WR = wpr(14)
// Bull / Bear Power
BullPower = high - ema(close, 13)
BearPower = low - ema(close, 13)
// Ultimate Oscillator
UO = uo(7,14,28)
if not na(UO)
UO := UO * 100
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PriceAvg = ema(close, 50)
DownTrend = close < PriceAvg
UpTrend = close > PriceAvg
// calculate trading recommendation based on SMA/EMA
float ratingMA = 0
float ratingMAC = 0
if not na(SMA10)
ratingMA := ratingMA + calcRatingMA(SMA10, close)
ratingMAC := ratingMAC + 1
if not na(SMA20)
ratingMA := ratingMA + calcRatingMA(SMA20, close)
ratingMAC := ratingMAC + 1
if not na(SMA30)
ratingMA := ratingMA + calcRatingMA(SMA30, close)
ratingMAC := ratingMAC + 1
if not na(SMA50)
ratingMA := ratingMA + calcRatingMA(SMA50, close)
ratingMAC := ratingMAC + 1
if not na(SMA100)
ratingMA := ratingMA + calcRatingMA(SMA100, close)
ratingMAC := ratingMAC + 1
if not na(SMA200)
ratingMA := ratingMA + calcRatingMA(SMA200, close)
ratingMAC := ratingMAC + 1
if not na(EMA10)
ratingMA := ratingMA + calcRatingMA(EMA10, close)
ratingMAC := ratingMAC + 1
if not na(EMA20)
ratingMA := ratingMA + calcRatingMA(EMA20, close)
ratingMAC := ratingMAC + 1
if not na(EMA30)
ratingMA := ratingMA + calcRatingMA(EMA30, close)
ratingMAC := ratingMAC + 1
if not na(EMA50)
ratingMA := ratingMA + calcRatingMA(EMA50, close)
ratingMAC := ratingMAC + 1
if not na(EMA100)
ratingMA := ratingMA + calcRatingMA(EMA100, close)
ratingMAC := ratingMAC + 1
if not na(EMA200)
ratingMA := ratingMA + calcRatingMA(EMA200, close)
ratingMAC := ratingMAC + 1
if not na(HullMA9)
ratingHullMA9 = calcRatingMA(HullMA9, close)
ratingMA := ratingMA + ratingHullMA9
ratingMAC := ratingMAC + 1
if not na(VWMA)
ratingVWMA = calcRatingMA(VWMA, close)
ratingMA := ratingMA + ratingVWMA
ratingMAC := ratingMAC + 1
float ratingIC = na
if not (na(IC_Lead1) or na(IC_Lead2) or na(close) or na(close[1]) or na(IC_BLine) or na(IC_CLine))
ratingIC := calcRating(
IC_Lead1 > IC_Lead2 and close > IC_Lead1 and close < IC_BLine and close[1] < IC_CLine and close > IC_CLine,
IC_Lead2 > IC_Lead1 and close < IC_Lead2 and close > IC_BLine and close[1] > IC_CLine and close < IC_CLine)
if not na(ratingIC)
ratingMA := ratingMA + ratingIC
ratingMAC := ratingMAC + 1
ratingMA := ratingMAC > 0 ? ratingMA / ratingMAC : na
float ratingOther = 0
float ratingOtherC = 0
ratingRSI = RSI
if not(na(ratingRSI) or na(ratingRSI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingRSI < 30 and ratingRSI[1] < ratingRSI, ratingRSI > 70 and ratingRSI[1] > ratingRSI)
if not(na(kStoch) or na(dStoch) or na(kStoch[1]) or na(dStoch[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(kStoch < 20 and dStoch < 20 and kStoch > dStoch and kStoch[1] < dStoch[1], kStoch > 80 and dStoch > 80 and kStoch < dStoch and kStoch[1] > dStoch[1])
ratingCCI = CCI
if not(na(ratingCCI) or na(ratingCCI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingCCI < -100 and ratingCCI > ratingCCI[1], ratingCCI > 100 and ratingCCI < ratingCCI[1])
if not(na(adxValue) or na(adxPlus[1]) or na(adxMinus[1]) or na(adxPlus) or na(adxMinus))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(adxValue > 20 and adxPlus[1] < adxMinus[1] and adxPlus > adxMinus, adxValue > 20 and adxPlus[1] > adxMinus[1] and adxPlus < adxMinus)
if not(na(ao) or na(ao[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(crossover(ao,0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]), crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1]))
if not(na(Mom) or na(Mom[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(Mom > Mom[1], Mom < Mom[1])
if not(na(macdMACD) or na(signalMACD))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(macdMACD > signalMACD, macdMACD < signalMACD)
float ratingStoch_RSI = na
if not(na(DownTrend) or na(UpTrend) or na(Stoch_RSI_K) or na(Stoch_RSI_D) or na(Stoch_RSI_K[1]) or na(Stoch_RSI_D[1]))
ratingStoch_RSI := calcRating(
DownTrend and Stoch_RSI_K < 20 and Stoch_RSI_D < 20 and Stoch_RSI_K > Stoch_RSI_D and Stoch_RSI_K[1] < Stoch_RSI_D[1],
UpTrend and Stoch_RSI_K > 80 and Stoch_RSI_D > 80 and Stoch_RSI_K < Stoch_RSI_D and Stoch_RSI_K[1] > Stoch_RSI_D[1])
if not na(ratingStoch_RSI)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingStoch_RSI
float ratingWR = na
if not(na(WR) or na(WR[1]))
ratingWR := calcRating(WR < -80 and WR > WR[1], WR > -20 and WR < WR[1])
if not na(ratingWR)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingWR
float ratingBBPower = na
if not(na(UpTrend) or na(DownTrend) or na(BearPower) or na(BearPower[1]) or na(BullPower) or na(BullPower[1]))
ratingBBPower := calcRating(
UpTrend and BearPower < 0 and BearPower > BearPower[1],
DownTrend and BullPower > 0 and BullPower < BullPower[1])
if not na(ratingBBPower)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingBBPower
float ratingUO = na
if not(na(UO))
ratingUO := calcRating(UO > 70, UO < 30)
if not na(ratingUO)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingUO
ratingOther := ratingOtherC > 0 ? ratingOther / ratingOtherC : na
float ratingTotal = 0
float ratingTotalC = 0
if not na(ratingMA)
ratingTotal := ratingTotal + ratingMA
ratingTotalC := ratingTotalC + 1
if not na(ratingOther)
ratingTotal := ratingTotal + ratingOther
ratingTotalC := ratingTotalC + 1
ratingTotal := ratingTotalC > 0 ? ratingTotal / ratingTotalC : na
// little piece of @rouxam logic
var bool start_condition = false
float bound = dsc_technicals == "Strong" ? 0.5 : 0.1
if IS_LONG
start_condition := ratingTotal > bound
else
start_condition := ratingTotal < -bound
[start_condition, close]
// ----------------------------------
// (Re-)Initialize
// ----------------------------------
var max_amount = max_amount_for_bot_usage()
var max_dev = max_deviation()
init_price := na(init_price) and within_window() ? open : init_price
latest_price := within_window() ? close : latest_price
// Actualize the start and end time of the backtesting window because number of bars is limited.
// NOTE: limits on number of available bars:
// TradingView FREE account: 5000 bars available,
// TradingView PRO/PRO+ account: 10000 bars available,
// TradingView PREMIUM account: 20000 bars available.
start_time_actual := barstate.isfirst and time > start_time_actual ? time : start_time_actual
end_time_actual := time > end_time_actual and time <= end_time ? time : end_time_actual
if strategy.position_size == 0.0
ttp_extremum := 0.0
ttp_active := false
deal_start_condition := false
// ----------------------------------
// Open deal with Base Order on Deal Start Condition
// ----------------------------------
[dsc_rsi, bo_level_rsi] = security(syminfo.tickerid, dsc_res, rsi_signal())
[dsc_ta, bo_level_ta] = security(syminfo.tickerid, dsc_res, ta_presets_signal())
if(strategy.opentrades == 0 and within_window() and close > 0 and strategy.equity > 0.0)
// Compute deal start condition
if dsc == "Start ASAP"
deal_start_condition := true
bo_level := close
if dsc == "RSI-7"
deal_start_condition := dsc_rsi
bo_level := bo_level_rsi
if dsc == "TV presets"
deal_start_condition := dsc_ta
bo_level := bo_level_ta
// Place Buy Order
if deal_start_condition
deal_counter := deal_counter + 1
if IS_LONG
strategy.entry("BO", limit=bo_level, long=strategy.long, qty=base_order_size()/bo_level)
else
strategy.entry("BO", limit=bo_level, long=strategy.short, qty=base_order_size()/bo_level)
last_so_level := bo_level
// Place Safety Orders
if max_safe_order > 0
for index = 1 to max_safe_order
so_level := safety_order_price(index, last_so_level)
so_name = "SO" + tostring(index)
if IS_LONG
strategy.entry(so_name, long=strategy.long, limit=so_level, qty=safety_order_qty(index)/so_level)
else
strategy.entry(so_name, long=strategy.short, limit=so_level, qty=safety_order_qty(index)/so_level)
last_so_level := so_level
// ----------------------------------
// Close Deal on SL, TP or TTP
// ----------------------------------
if abs(strategy.position_size) > 0
take_profit_factor = IS_LONG ? (1 + take_profit) : (1 - take_profit)
stop_loss_factor = IS_LONG ? (1 - stop_loss) : (1 + stop_loss)
ttp_factor = IS_LONG ? (1 - ttp) : (1 + ttp)
stop_level := bo_level * stop_loss_factor
if take_profit_type == "% from total volume"
take_profit_level := strategy.position_avg_price * take_profit_factor
else
take_profit_level := bo_level * take_profit_factor
// Stop Loss
stop_loss_on_bar := false
if stop_loss > max_dev and not ttp_active
if IS_LONG and low < stop_level
stop_loss_counter := stop_loss_counter + 1
strategy.exit(id="x", stop=stop_level, comment="SL")
stop_loss_on_bar := true
else if not IS_LONG and high > stop_level
stop_loss_counter := stop_loss_counter + 1
strategy.exit(id="x", stop=stop_level, comment="SL")
stop_loss_on_bar := true
if not stop_loss_on_bar
if ttp == 0.0
// Simple take profit
strategy.exit(id="x", limit=take_profit_level, comment="TP")
else
// Trailing take profit
if IS_LONG and high >= take_profit_level
ttp_extremum := max(high, ttp_extremum)
ttp_active := true
if not IS_LONG and low <= take_profit_level
ttp_extremum := min(low, ttp_extremum)
ttp_active := true
if ttp_active
ttp_level := ttp_extremum * ttp_factor
strategy.exit(id="x", stop=ttp_level, comment="TTP")
// Cleanup
if (crossunder(strategy.opentrades, 0.5))
strategy.close_all()
strategy.cancel_all()
// ----------------------------------
// Results
// ----------------------------------
profit = max(strategy.equity, 0.0) - strategy.initial_capital
profit_pct = profit / strategy.initial_capital
add_line(the_table, the_row, the_label, the_value, is_warning) =>
// if providing a value, the row is shown as: the_label | the_value
// else: the_label is considered to be a title
is_even = (the_row % 2) == 1
is_title = na(the_value) ? true : false
text = is_title ? "" : tostring(the_value)
bg_color = is_title ? color.black : is_warning ? color.red : is_even ? color.silver : color.white
text_color = is_title ? color.white : color.black
left_cell_align = is_title ? text.align_right : text.align_left
table.cell(the_table, 0, the_row, the_label, bgcolor=bg_color, text_color=text_color, text_size=size.auto, text_halign=left_cell_align)
table.cell(the_table, 1, the_row, text, bgcolor=bg_color, text_color=text_color, text_size=size.auto, text_halign=text.align_right)
var string warnings_text = ""
var warnings = array.new_string(0, "")
if (max_amount / strategy.initial_capital > 1.005 or max_amount / strategy.initial_capital < 0.995)
if order_size_type == "Fixed"
array.push(warnings, "Strategy Initial Capital (currently " + tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency
+ ") must match Max Amount For Bot Usage (" + tostring(max_amount, currency_format()) + " " + syminfo.currency + ")")
else
array.push(warnings, "Please adjust Base Order and Safe Order percentage to reach 100% of usage of capital. Currently using " + tostring(max_amount / strategy.initial_capital, "#.##%"))
if (max_dev >= 1.0)
array.push(warnings, "Max Price Deviation (" + tostring(max_dev, "#.##%") + ") cannot be >= 100.0%")
if (stop_loss > 0.0 and stop_loss <= max_dev)
array.push(warnings, "Stop Loss (" + tostring(stop_loss, "#.##%") + ") should be greater than Max Price Deviation (" + tostring(max_dev, "#.##%") + ")")
if ((timeframe.isminutes and not (tonumber(timeframe.period) < 30)) or timeframe.isdwm)
array.push(warnings, "Backtesting may be inaccurate. Recommended to use timeframe of 15m or less")
if (ttp >= take_profit)
array.push(warnings, "Trailing Take Profit (" + tostring(ttp, "#.##%") + ") cannot be greater than Take Profit (" + tostring(take_profit, "#.##%") + ")")
// Making the results table
var results_table = table.new(position.top_right, 2, 20, frame_color=color.black)
curr_row = -1
None = int(na)
curr_row += 1, add_line(results_table, curr_row, "Bot setup", None, false)
if (array.size(warnings) > 0)
for index = 1 to array.size(warnings)
curr_row += 1
add_line(results_table, curr_row, "Please review your strategy settings", array.pop(warnings), true)
curr_row += 1, add_line(results_table, curr_row, "Dates", pretty_date(start_time_actual) + " to " + pretty_date(end_time_actual), false)
curr_row += 1, add_line(results_table, curr_row, "Deal Start Condition", dsc, false)
curr_row += 1, add_line(results_table, curr_row, "Base and Safety Orders", "BO: " + tostring(base_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency + " / " + "SO: " + tostring(safe_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Price Deviation", tostring(price_deviation, "#.##%"), false)
curr_row += 1, add_line(results_table, curr_row, "Safe Order Scale", "Volume: " + tostring(safe_order_volume_scale) + " / Scale: " + tostring(safe_order_step_scale), false)
curr_row += 1, add_line(results_table, curr_row, "Take Profit / Stop Loss", tostring(take_profit, "#.##%") + (ttp > 0.0 ? "( Trailing: " + tostring(ttp, "#.##%") + ")" : "") + "/ " + (stop_loss > 0.0 ? tostring(stop_loss, "#.##%") : "No Stop Loss"), false)
curr_row += 1, add_line(results_table, curr_row, "Max Amount For Bot Usage", tostring(max_amount, currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Max Coverage", tostring(max_safe_order) + " Safety Orders / " + tostring(max_dev, "#.##%"), false)
curr_row += 1, add_line(results_table, curr_row, "Summary", None, false)
curr_row += 1, add_line(results_table, curr_row, "Initial Capital", tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Final Capital", tostring(max(strategy.equity, 0.0), currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Net Result", tostring(profit, currency_format()) + " " + syminfo.currency + " (" + tostring(profit_pct, "#.##%") + ")", false)
curr_row += 1, add_line(results_table, curr_row, "Total Deals", tostring(deal_counter), false)
if stop_loss > 0.0
curr_row += 1, add_line(results_table, curr_row, "Deals Closed on Stop Loss", tostring(stop_loss_counter), false)
if IS_LONG
buy_hold_profit = (latest_price - init_price) / init_price * strategy.initial_capital
buy_hold_profit_pct = buy_hold_profit / strategy.initial_capital
ratio = profit_pct / buy_hold_profit_pct
curr_row += 1, add_line(results_table, curr_row, "Comparison to Buy-And-Hold", None, false)
curr_row += 1, add_line(results_table, curr_row, "Net Result for Buy-and-hold", tostring(buy_hold_profit, currency_format()) + " " + syminfo.currency + " (" + tostring(buy_hold_profit_pct, "#.##%") + ")", false)
curr_row += 1, add_line(results_table, curr_row, "(Bot Performance) / (Buy-and-hold Performance)", tostring(ratio, "#.###"), false)
|