library(gdata)
library(TTR) # rsi, sma...
library(e1071) # svm
# library(caret)
library(quantmod)

getData <- function(csvFile) {
  fileCsv = read.csv(csvFile)
  myData = data.frame(
    date = c(fileCsv[1]),
    time = c(fileCsv[2]),
    open = c(fileCsv[3]),
    max  = c(fileCsv[4]),
    min  = c(fileCsv[5]),
    close = c(fileCsv[6]),
    volume = c(fileCsv[7])
  )
  colnames(myData, do.NULL = FALSE)
  colnames(myData) <- c("date", "time", "open", "max", "min", "close","volume")
  return(myData)
  
}
RSIdata <- function(period, price, type, wtsArg) {
  rsi <- RSI(price, n=period, maType=type, wts=wtsArg)
}

# normalize value between 1 values
normalizeThis <- function(arr, x, y){
  # Normalize to [0, 1]:
  m <- min(arr, na.rm = TRUE);
  rnge <- max(arr,na.rm = TRUE) - m;
  arr <- (arr - m) / rnge;
  
  # Then scale to [x,y]:
  rnge2 <- y - x;
  normalized <- (arr*rnge2) + x;
  return(normalized);
}

# shift data / oppposite to Lag function
shift <- function(x, n){
  c(x[-(seq(n))], rep(NA, n))
}

# count crossover via prev and next value
crossover <- function(prevOne, prevTwo, one, two, myArr) {
  was <- prevOne-prevTwo;
  is <- one - two;
  myVar <- 0
  if(was < -0 && is >= 0) {
    # print('fromBellow');
    myVar <- 1;
  } else if (was > 0 && is <= 0){
    # print('fromAbove')
    myVar <- -1;
  }
  return(myVar);
}


tryOne <- function(dataMine, windowSize, cost, epsilon, gamma, type) {		
  resultD.data <- c();
  resultD.Prediction <- c();
  resultD.error <- c();
  resultD.sma3 <- c()
  dataMine <- subset(dataMine, select = -c(date, time) )
  for(i in 1:(nrow(dataMine)-windowSize-1)) {
    SVM<-svm(Class ~ .,data= dataMine[i:(windowSize-1+i),], kernel=type, gamma=gamma, epsilon=epsilon, cost=cost)
    TestPrediction <- predict(SVM,subset(dataMine[windowSize+i,],select = -c(Class)))
    resultD.data <- c(resultD.data, dataMine[windowSize+i, "Class"])
    resultD.Prediction <- c(resultD.Prediction, TestPrediction)
  }
  resultD.error <- abs(resultD.data[1:length(resultD.Prediction)] - resultD.Prediction);	 
  plot(1:(length(resultD.Prediction)),resultD.Prediction,type="l",col="blue",main="Predikce procentualni zmeny ceny", xlab="Vzorek", ylab="Cena")
  lines(1:(length(resultD.data)),resultD.data,col="red")
  lines(1:(length(resultD.Prediction)), Training[(windowSize+1):(length(resultD.Prediction)+windowSize),"sma3"], col="green")
  l <- length(resultD.Prediction)
  resultD <- data.frame(resultD.error[1:l],resultD.data[1:l],resultD.Prediction[1:l]);
  colnames(resultD, do.NULL = FALSE)
  colnames(resultD) <- c('error',"data","Prediction")
  return(resultD)
} 

init <- function(dataFromMt4) {
  # RSI
  # rsiPeriod <- 14
  # closeRSI <- RSI(dataFromMt4[,'close'], n=rsiPeriod, maType='WMA', wts=dataFromMt4[,'close'])
  rsiPeriod <- 5
  closeRSI <- RSI(dataFromMt4[,'close'], n=rsiPeriod, maType='EMA', wts=dataFromMt4[,'close'])
  closeRSI1 <- Lag(closeRSI,1)
  closeRSI2 <- Lag(closeRSI,2)
  
  # stochastic <- SMI(try.xts(dataFromMt4[,c('high','low','open')], error = as.matrix), nFastK=14, nFastD=3, nSlowD=3, bounded=TRUE, smooth=1)
  stochastic <- SMI(try.xts(dataFromMt4[,c('high','low','open')], error = as.matrix), nFastK=14, nFastD=3, nSlowD=3, bounded=TRUE, smooth=1)
  
  ROC1 <- dataFromMt4[,'close'] / Lag(dataFromMt4[,'close'],1)
  
  ROC5 <- dataFromMt4[,'close'] / Lag(dataFromMt4[,'close'],5)
  
  ROC10 <- dataFromMt4[,'close'] / Lag(dataFromMt4[,'close'],5)
  
  # macd
  # macdInd <- MACD( dataFromMt4[,'close'], 12, 26, 9, maType="EMA" )
  macdInd <- MACD( dataFromMt4[,'close'], 5, 12, 3, maType="EMA" )
  macdInd1 <- Lag(macdInd[,"macd"],1)
  macdInd2 <- Lag(macdInd[,"macd"],2)
  
  sma5 <- SMA(dataFromMt4[,'close'],n=5)
  sma10 <- SMA(dataFromMt4[,'close'],n=10)
  
  OSCP <- (SMA(dataFromMt4[,'close'],n=5) - SMA(dataFromMt4[,'close'],n=10))/SMA(dataFromMt4[,'close'],n=5)
  
  # sma
  sma5Ind <- SMA(dataFromMt4[,'close'],n=5)
  sma5Ind1 <- dataFromMt4[,'close'] - Lag(sma5Ind,1)
  sma5Ind2 <- dataFromMt4[,'close'] - Lag(sma5Ind,2)
  sma5Ind <- dataFromMt4[,'close'] - sma5Ind
  
  RDP1 <-  ((dataFromMt4[,'close'] - Lag(dataFromMt4[,'close'], k=1))/Lag(dataFromMt4[,'close'], k=1)) * 100
  RDP2 <-  ((dataFromMt4[,'close'] - Lag(dataFromMt4[,'close'], k=2))/Lag(dataFromMt4[,'close'], k=2)) * 100
  RDP3 <-  ((dataFromMt4[,'close'] - Lag(dataFromMt4[,'close'], k=3))/Lag(dataFromMt4[,'close'], k=3)) * 100
  RDP4 <-  ((dataFromMt4[,'close'] - Lag(dataFromMt4[,'close'], k=4))/Lag(dataFromMt4[,'close'], k=4)) * 100
  RDP5 <-  ((dataFromMt4[,'close'] - Lag(dataFromMt4[,'close'], k=5))/Lag(dataFromMt4[,'close'], k=5)) * 100
  
  sma3minus <- dataFromMt4[,'close'] - SMA(dataFromMt4[,'close'],n=3)
  sma3minusOpen <- dataFromMt4[,'open'] - SMA(dataFromMt4[,'close'],n=3)
  sma3minusHigh <- dataFromMt4[,'high'] - SMA(dataFromMt4[,'close'],n=3)
  sma3minusLow <- dataFromMt4[,'low'] - SMA(dataFromMt4[,'close'],n=3)
  
  # ema 50
  ema50 <- dataFromMt4[,'close'] - EMA(dataFromMt4[,'close'], n=50)
  
  RDPp1 <- ((shift(dataFromMt4[,'close'],5) - dataFromMt4[,'close'])/dataFromMt4[,'close']) * 100
  
  smaPeriod <- 10
  
  # Class to be predicted! #
  Class <- ifelse(RDPp1 < -0.0000, 'DOWN','UP') 
  ########
  ## Data set used for prediction
  DataSet<-data.frame( 
    ema50,
    
    # sma3minus,
    # sma3minusOpen, sma3minusHigh, sma3minusLow,
    
    stochastic[,"SMI"], stochastic[,"signal"],
    
    # ROC1, ROC5, ROC10, 
    # 
    sma5, sma10,
    # OSCP,
    
    # closeRSI, closeRSI1,closeRSI2,
    # # 
    macdInd[,'macd'],
    # macdInd1,macdInd2,
    # 
    # sma5Ind, sma5Ind1,sma5Ind2,
    # 
    # RDP1, RDP2, RDP3, RDP4, RDP5,
    
    Class
  )
  colnames(DataSet, do.NULL = FALSE)
  colnames(DataSet) <- c(
    "ema50",
    # 
    # "sma3minus",
    # 
    # "sma3minusOpen", "sma3minusHigh", "sma3minusLow",
    
    "stochastic", "signalStoch",
    
    # "ROC1", "ROC5", "ROC10", 
    
    "sma5", "sma10",
    # "OSCP",
    
    # "closeRSI","closeRSI1","closeRSI2",
    # 
    "macdInd",
    # "macdInd1","macdInd2",
    # 
    # "sma5Ind","sma5Ind1","sma5Ind2",
    # 
    # "RDP1", "RDP2", "RDP3", "RDP4", "RDP5",
    
    "Class")	
  
  # crop data because of ema 50
  DataSet <- DataSet[-c(1:(50)),]
  return(DataSet)
}

## main function
myData = data.frame(
  date = c(dateFromMT4),
  # time = c(timeFromMT4),
  open = c(openFromMT4),
  high  = c(highFromMT4),
  low  = c(lowFromMT4),
  close = c(closeFromMT4)
  # volume = c(volumeFromMT4)
)

DataSet <- init(myData);

# , gamma=0.015, epsilon= 0.015, cost=0.5
# SVM<-svm(Class ~ .,data= head(DataSet,-5), kernel="radial", gamma=0.015, epsilon= 0.015, cost=0.5)
SVM<-svm(Class ~ .,data= head(DataSet,-5), kernel="radial", gamma=4, cost=10)
# SVM<-svm(Class ~ .,data= head(DataSet,-5), kernel="radial", gamma=2, cost=1)
# 0.00390625 0.001
# SVM<-svm(Class ~ .,data= head(DataSet,-5), kernel="sigmoid", gamma=0.00390625, cost=0.001)
# SVM<-svm(Class ~ .,data= head(DataSet,-5), kernel="sigmoid", gamma=0.2, epsilon= 0, cost=0.1)
# Prediction <- predict(SVM,subset(DataSet[nrow(DataSet),],select = -c(Class)))
Prediction1 <- predict(SVM,subset(DataSet[nrow(DataSet)-4,],select = -c(Class)))
Prediction2 <- predict(SVM,subset(DataSet[nrow(DataSet)-3,],select = -c(Class)))
Prediction3 <- predict(SVM,subset(DataSet[nrow(DataSet)-2,],select = -c(Class)))
Prediction4 <- predict(SVM,subset(DataSet[nrow(DataSet)-1,],select = -c(Class)))
Prediction5 <- predict(SVM,subset(DataSet[nrow(DataSet),],select = -c(Class)))
# Prediction <- ifelse(Prediction == "UP", 1,ifelse(Prediction == "DOWN", -1, 0))
Prediction1 <- ifelse(Prediction1 == "UP", 1,ifelse(Prediction1 == "DOWN", -1, 0))
Prediction2 <- ifelse(Prediction2 == "UP", 1,ifelse(Prediction2 == "DOWN", -1, 0))
Prediction3 <- ifelse(Prediction3 == "UP", 1,ifelse(Prediction3 == "DOWN", -1, 0))
Prediction4 <- ifelse(Prediction4 == "UP", 1,ifelse(Prediction4 == "DOWN", -1, 0))
Prediction5 <- ifelse(Prediction5 == "UP", 1,ifelse(Prediction5 == "DOWN", -1, 0))
# Prediction <- round(mean(Prediction1, Prediction2, Prediction3, Prediction4,Prediction5))
if(Prediction1 + Prediction2 + Prediction3 + Prediction4 + Prediction5 == -5) {
  Prediction <- Prediction1
  # -1
} else if(Prediction1 + Prediction2 + Prediction3 + Prediction4 + Prediction5 == 5) {
  Prediction <- 1
} else {
  Prediction <- 0
}
print(append("Prediction: ",Prediction))
