Lorentzian Classification Strategy - Teamviewer
Lorentzian Classification Strategy - Teamviewer
0 at
https://mozilla.org/MPL/2.0/
// ©rp4000
// @version=5
strategy('RoyalPrince Strategy using Lorentzian Classification by RoyalPrince',
'Lorentzian Classification', true, precision=4,
max_labels_count=500,currency=currency.USD, initial_capital=50,
commission_value=0.00, default_qty_type = strategy.percent_of_equity,
default_qty_value = 100)
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 useConfidenceFilter
bool useAdxFilter
float regimeThreshold
int adxThreshold
type Filter
bool volatility
bool regime
bool adx
// ==========================
// ==== Helper Functions ====
// ==========================
Settings settings =
Settings.new(
input.source(title='Source', defval=hlc3, group="General Settings",
tooltip="Source of the input data"),
input.int(title='Neighbors Count', defval=8, group="General Settings", minval=1,
maxval=100, step=1, tooltip="Number of neighbors to consider"),
input.int(title="Max Bars Back", defval=2000, group="General Settings"),
input.int(title="Feature Count", defval=5, group="Feature Engineering",
minval=2, maxval=5, tooltip="Number of features to use for ML predictions."),
input.int(title="Color Compression", defval=1, group="General Settings",
minval=1, maxval=10, tooltip="Compression factor for adjusting the intensity of the
color scale."),
input.bool(title="Show Exits", defval=false, group="General Settings",
tooltip="Show the exit threshold on the chart.", inline="exits"),
input.bool(title="Use Dynamic Exits", defval=false, group="General Settings",
tooltip="Attempts to let profits ride by dynamically adjusting the exit threshold
based on kernel regression.", inline="exits")
)
// Label Object: Used for classifying historical data as training data for the ML
Model
Label direction =
Label.new(
long=1,
short=-1,
neutral=0
)
// 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")
// Backtest Settings
show_info = input.bool(true, 'Show Backtest Results', tooltip='Displays the win
rate of the given configuration.', group='Backtesting')
// =================================
// ==== 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)
// 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(isBullishChange)
barsSinceGreenEntry = ta.barssince(startLongTrade)
barsSinceGreenExit = ta.barssince(isBearishChange)
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 (barsSinceGreenEntry <
barsSinceRedEntry)
endShortTradeStrict = ((isHeldFourBars and isLastSignalSell) or
(isHeldLessThanFourBars and isNewBuySignal)) and (barsSinceGreenEntry >
barsSinceRedEntry)
// =========================
// ==== 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=knn.color_green(prediction), size=size.small, offset=0)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar,
knn.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=-1)
plotshape(endShortTrade and settings.showExits ? low : na, 'StopSell',
shape.xcross, location.absolute, color=#FD1707, size=size.tiny, offset=-1)
// ================
// ==== Alerts ====
// ================
// =========================
// ==== Display Signals ====
// =========================
// =====================
// ==== Backtesting ====
// =====================
// The following can be used to display real-time winrate approximations. This can
be a useful mechanism for obtaining real-time feedback during Feature Engineering.
// 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, totalStopLosses, totalTrades, tradeStatsHeader,
winLossRatio, winRate] = knn.backtest(high, low, open, startLongTrade,
endLongTrade, startShortTrade, endShortTrade, isStopLossHit, maxBarsBackIndex,
bar_index)
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 show_info
var tbl = knn.init_table()
if barstate.islast
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses,
winLossRatio, winRate, totalStopLosses)
// ================
// ==== Order ====
// ================
if (startLongTrade)
strategy.entry("My Long Entry Id", strategy.long, comment = "ENTER")
if (endLongTrade)
strategy.close("My Long Entry Id", comment = "EXIT")