Pine script-2
Pine script-2
ema = ta.ema(input(close,"Source",group="EMA"),input(10,"Length",group="EMA"))
plot(ema, "EMA", color=color.white)
// study("RSI Cloud by Wilson", "RSI Cloud")
// //@version=5
// indicator("Hull Butterfly Oscillator [LuxAlgo]", "Hull Butterfly Oscillator
[LuxAlgo]")
//-----------------------------------------------------------------------------}
//Settings
//----------------------------------------------------a-------------------------{
lengthh = input(14, group="Hull Butterfly Oscillator")
//Style
bull_css_0 = input.color(color.new(#0cb51a, 50), 'Bullish Gradient'
, inline = 'inline0'
, group = 'Hull Butterfly Oscillator')
//-----------------------------------------------------------------------------}
//Normalization variables
//-----------------------------------------------------------------------------{
var short_len = int(lengthh / 2)
var hull_len = int(math.sqrt(lengthh))
//-----------------------------------------------------------------------------}
//Hull coefficients
//-----------------------------------------------------------------------------{
var lcwa_coeffs = array.new_float(hull_len, 0)
var hull_coeffs = array.new_float(0)
if barstate.isfirst
//Linearly combined WMA coeffs
for i = 0 to lengthh-1
sum1 = math.max(short_len - i, 0)
sum2 = lengthh - i
//-----------------------------------------------------------------------------}
//Hull squeeze oscillator
//-----------------------------------------------------------------------------{
var os = 0
var len = array.size(hull_coeffs)-1
hma = 0.
inv_hma = 0.
for i = 0 to len
hma += srch[i] * array.get(hull_coeffs, i)
inv_hma += srch[len-i] * array.get(hull_coeffs, i)
hso = hma - inv_hma
//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------{
//Colors
css0 = color.from_gradient(hso, 0, cmean, bull_css_0, bull_css_1)
css1 = color.from_gradient(hso, -cmean, 0, bear_css_1, bear_css_0)
css = hso > 0 ? css0 : css1
// //Oscillator line/histogram
// plot(hso, 'Hull Butterfly', css
// , style = plot.style_histogram)
ema_buy1 = use_ema1?low>ema:true
ema_sell1 = use_ema1?high<ema:true
rsi_buy1 = use_rsi1?rsi>maplot:true
rsi_sell1 = use_rsi1?rsi<maplot:true
hma_buy1 = use_hma1?hso>0:true
hma_sell1 = use_hma1?hso<=0:true
ema_buy2 = use_ema2?low>ema:true
ema_sell2 = use_ema2?high<ema:true
rsi_buy2 = use_rsi2?rsi>maplot:true
rsi_sell2 = use_rsi2?rsi<maplot:true
hma_buy2 = use_hma2?hso>0:true
hma_sell2 = use_hma2?hso<=0:true
st_buy2 = use_st2 ? directionc==-1:true
st_sell2 = use_st2 ? directionc==1:true
hma1(x, p) =>
ta.wma(2 * ta.wma(x, p / 2) - ta.wma(x, p), math.round(math.sqrt(p)))
hma3(x, p) =>
per = p / 2
ta.wma(ta.wma(x, per / 3) * 3 - ta.wma(x, per / 2) - ta.wma(x, per), per)
kahlman(x, g) =>
kf = 0.0
dk = x - nz(kf[1], x)
smooth = nz(kf[1], x) + dk * math.sqrt(g * 2)
velo = 0.0
velo := nz(velo[1], 0) + g * dk
kf := smooth + velo
kf
import jdehorty/MLExtensions/2 as ml
import jdehorty/KernelFunctions/2 as kernels
type Settings
float source
int neighborsCount
int maxBarsBack
int featureCount
int colorCompression
bool showExits
bool useDynamicExits
type Label
int long
int short
int neutral
type FeatureArrays
array<float> f1
array<float> f2
array<float> f3
array<float> f4
array<float> f5
type FeatureSeries
float f1
float f2
float f3
float f4
float f5
type MLModel
int firstBarIndex
array<int> trainingLabels
int loopSize
float lastDistance
array<float> distancesArray
array<int> predictionsArray
int prediction
type FilterSettings
bool useVolatilityFilter
bool useRegimeFilter
bool useAdxFilter
float regimeThreshold
int adxThreshold
type Filter
bool volatility
bool regime
bool adx
// ==========================
// ==== Helper Functions ====
// ==========================
// EMA Settings
useEmaFilter = input.bool(title="Use EMA Filter", defval=false, group="Filters",
inline="ema")
emaPeriod = input.int(title="Period", defval=200, minval=1, step=1,
group="Filters", inline="ema", tooltip="The period of the EMA used for the EMA
Filter.")
isEmaUptrend = useEmaFilter ? close > ta.ema(close, emaPeriod) : true
isEmaDowntrend = useEmaFilter ? close < ta.ema(close, emaPeriod) : true
useSmaFilter = input.bool(title="Use SMA Filter", defval=false, group="Filters",
inline="sma")
smaPeriod = input.int(title="Period", defval=200, minval=1, step=1,
group="Filters", inline="sma", tooltip="The period of the SMA used for the SMA
Filter.")
isSmaUptrend = useSmaFilter ? close > ta.sma(close, smaPeriod) : true
isSmaDowntrend = useSmaFilter ? close < ta.sma(close, smaPeriod) : true
// Display Settings
showBarColors = input.bool(true, "Show Bar Colors", tooltip="Whether to show the
bar colors.", group="Display Settings")
showBarPredictions = input.bool(defval = true, title = "Show Bar Prediction
Values", tooltip = "Will show the ML model's evaluation of each bar as an
integer.", group="Display Settings")
useAtrOffset = input.bool(defval = false, title = "Use ATR Offset", tooltip = "Will
use the ATR offset instead of the bar prediction offset.", group="Display
Settings")
barPredictionsOffset = input.float(0, "Bar Prediction Offset", minval=0,
tooltip="The offset of the bar predictions as a percentage from the bar high or
close.", group="Display Settings")
// =================================
// ==== Next Bar Classification ====
// =================================
array.push(y_train_array, y_train_series)
lastDistance = -1.0
size = math.min(settings.maxBarsBack-1, array.size(y_train_array)-1)
sizeLoop = math.min(settings.maxBarsBack-1, size)
// ============================
// ==== Prediction Filters ====
// ============================
// User Defined Filters: Used for adjusting the frequency of the ML Model's
predictions
filter_all = filter.volatility and filter.regime and filter.adx
// Filtered Signal: The model's prediction of future price movement direction with
user-defined filters applied
signal := prediction > 0 and filter_all ? direction.long : prediction < 0 and
filter_all ? direction.short : nz(signal[1])
// ===========================
// ==== Entries and Exits ====
// ===========================
// Dynamic Exit Conditions: Booleans for ML Model Position Exits based on Fractal
Filters and Kernel Regression Filters
lastSignalWasBullish = ta.barssince(startLongTrade) < ta.barssince(startShortTrade)
lastSignalWasBearish = ta.barssince(startShortTrade) < ta.barssince(startLongTrade)
barsSinceRedEntry = ta.barssince(startShortTrade)
barsSinceRedExit = ta.barssince(alertBullish)
barsSinceGreenEntry = ta.barssince(startLongTrade)
barsSinceGreenExit = ta.barssince(alertBearish)
isValidShortExit = barsSinceRedExit > barsSinceRedEntry
isValidLongExit = barsSinceGreenExit > barsSinceGreenEntry
endLongTradeDynamic = (isBearishChange and isValidLongExit[1])
endShortTradeDynamic = (isBullishChange and isValidShortExit[1])
// Fixed Exit Conditions: Booleans for ML Model Position Exits based on a Bar-Count
Filters
endLongTradeStrict = ((isHeldFourBars and isLastSignalBuy) or
(isHeldLessThanFourBars and isNewSellSignal and isLastSignalBuy)) and
startLongTrade[4]
endShortTradeStrict = ((isHeldFourBars and isLastSignalSell) or
(isHeldLessThanFourBars and isNewBuySignal and isLastSignalSell)) and
startShortTrade[4]
isDynamicExitValid = not useEmaFilter and not useSmaFilter and not
useKernelSmoothing
endLongTrade = settings.useDynamicExits and isDynamicExitValid ?
endLongTradeDynamic : endLongTradeStrict
endShortTrade = settings.useDynamicExits and isDynamicExitValid ?
endShortTradeDynamic : endShortTradeStrict
// =========================
// ==== Plotting Labels ====
// =========================
// Note: These will not repaint once the most recent bar has fully closed. By
default, signals appear over the last closed bar; to override this behavior set
offset=0.
plotshape(startLongTrade ? low : na, 'Buy', shape.labelup, location.belowbar,
color=ml.color_green(prediction), size=size.small, offset=0)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar,
ml.color_red(-prediction), size=size.small, offset=0)
plotshape(endLongTrade and settings.showExits ? high : na, 'StopBuy', shape.xcross,
location.absolute, color=#3AFF17, size=size.tiny, offset=0)
plotshape(endShortTrade and settings.showExits ? low : na, 'StopSell',
shape.xcross, location.absolute, color=#FD1707, size=size.tiny, offset=0)
// ================
// ==== Alerts ====
// ================
// // Separate Alerts for Entries and Exits
// alertcondition(startLongTrade, title='Open Long ▲', message='LDC Open Long ▲ |
{{ticker}}@{{close}} | ({{interval}})')
// alertcondition(endLongTrade, title='Close Long ▲', message='LDC Close Long ▲ |
{{ticker}}@{{close}} | ({{interval}})')
// alertcondition(startShortTrade, title='Open Short ▼', message='LDC Open Short |
{{ticker}}@{{close}} | ({{interval}})')
// alertcondition(endShortTrade, title='Close Short ▼', message='LDC Close Short ▼
| {{ticker}}@{{close}} | ({{interval}})')
// =========================
// ==== Display Signals ====
// =========================
// =====================
// ==== Backtesting ====
// =====================
// The following can be used to display real-time trade stats. This can be a useful
mechanism for obtaining real-time feedback during Feature Engineering. This does
NOT replace the need to properly backtest.
// Note: In this context, a "Stop-Loss" is defined instances where the ML Signal
prematurely flips directions before an exit signal can be generated.
[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader,
winLossRatio, winRate] = ml.backtest(high, low, open, startLongTrade, endLongTrade,
startShortTrade, endShortTrade, isEarlySignalFlip, maxBarsBackIndex, bar_index,
settings.source, useWorstCase)
init_table() =>
c_transparent = color.new(color.black, 100)
table.new(position.top_right, columns=2, rows=7,
frame_color=color.new(color.black, 100), frame_width=1, border_width=1,
border_color=c_transparent)
if showTradeStats
var tbl = ml.init_table()
if barstate.islast
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses,
winLossRatio, winRate, totalEarlySignalFlips)