Forex Algorithm
Forex Algorithm
//@version=5
indicator(")", '', true, format=format.price, precision=2,
timeframe="", timeframe_gaps=true)
//-- Inputs
TF = input.timeframe('5', 'Resolution',
['1','3','5','10','15','30','45','60','120','180','240','480'
,'D','W','M'])
N = input.int (10, '# of Data Points [2:n]',
2)
K = input.int (100, '# of Nearest Neighbors
(K) [1:252]', 1, 252)
ADJ = input.bool (true, 'Adjust Prediction',
inline='b')
REP = input.bool (false, 'Non-Repainting',
inline='b')
ADDON = input.string ('Z-Score', 'Add-On',
['None','Pivot Point','Z-Score'])
LAGP = input.int (5, 'Pivot Point Lag [2:n] if
selected', 2)
LAGZ = input.int (20, 'Z-Score Lag [2:n] if
selected', 2)
DISP = input.string ('Both', 'Show Outcomes',
['Curve','Predict','Both'])
ODS = input.source (hlcc4, 'Projection Base')
//-- Functions
for i = 0 to N-1
float d = math.abs(data[i] - data[i+1])
//-- euclidean will do just as well
// float d = math.sqrt(math.pow(data[i] - data[i+1],
2))
array.push(distances, d)
int size = array.size(distances)
nearest_neighbors
predict(neighbors, data) => //-- predict the expected price
and calculate next bar's direction
float prediction = array.avg(neighbors)
int direction = prediction < data[ADJ?0:1] ? 1 :
prediction > data[ADJ?0:1] ? -1 : 0
[prediction, direction]
ordinary_color(dir) =>
dir==1?green(9):dir==-1?red(9):na
//-- Logic
rep = REP?1:0
[O,H,L,C] = request.security('', TF,
[open,high[rep],low[rep],close[rep]])
nn = knn(C)
[pred,dir] = predict(nn, C)
clr = ADDON=='Z-Score'?zscore_color(C, LAGZ,
dir):ADDON=='Pivot Point'?pivot_color(H,L,LAGP,
dir):ordinary_color(dir)
//-- Visuals
//plot(ta.sma(close,20))
plot(DISP=='Curve' or DISP=='Both' ? pred : na, 'kNN
Curve', clr, 3, offset=0)
plot(DISP=='Predict' or DISP=='Both' ? ODS : na,
'Prediction', clr, 5, plot.style_circles, offset=2,
show_last=1)