#!/usr/bin/env python
# coding: utf-8

# In[1]:


#Import MetaTrader5 package
import MetaTrader5 as mt5

#Import datetime for selecting data
from datetime import datetime

#Keeping track of time
import time

#Import matplotlib
import matplotlib.pyplot as plt

#Intepret glass box model
from interpret.glassbox import ExplainableBoostingClassifier

#Intepret GUI dashboard utility
from interpret import show

#Pandas for handling data
import pandas as pd

#Pandas-ta for calculating technical indicators
import pandas_ta as ta

#Scoring metric to assess model accuracy
from sklearn.metrics import precision_score

#ONNX
import onnx

#Import ebm2onnx
import ebm2onnx

#Path handling
from sys import argv


# In[2]:


#Trading global variables
#The symbol we want to trade
MARKET_SYMBOL = 'Volatility 75 Index'
#This data frame will store the most recent price update
LAST_CLOSE = pd.DataFrame()
#We may not always enter at the price we want, how much deviation can we tolerate?
DEVIATION = 100
#For demonstrational purposes we will always enter at the minimum volume
#However,we will not hardcode the minimum volume, we will fetch it dynamically
VOLUME = 0
#How many times the minimum lotsize should our positions be?
LOT_MUTLIPLE = 1
#What timeframe are we working on?
TIMEFRAME = mt5.TIMEFRAME_M1


# In[3]:


#Our login credentials
login = 30516497
password = '**dARERECHIMURENGA__2008'
server = 'Deriv-Demo'


# In[4]:


#Initializing out MT5 terminal and logging in
if mt5.initialize(login=login,password=password,server=server):
    print('Logged in successfully')
else:
    print('Failed to login')


# In[5]:


help(mt5.copy_rates_from)


# In[6]:


#Fetching historical data
data = pd.DataFrame(mt5.copy_rates_from_pos('Volatility 75 Index',mt5.TIMEFRAME_M1,0,90000))


# In[7]:


#Let's create a function to preprocess our data
def preprocess(data):
    data['mid_point'] = ((data['high'] + data['low']) / 2)

    data['mid_point_growth'] = data['mid_point'].diff().diff()

    data['mid_point_growth_lag'] = data['mid_point_growth'].shift(1)

    data['height'] = (data['mid_point'] - data['close'])

    data['height - 1'] = data['height'].shift(1)
    
    data['height_growth'] = data['height'].diff().diff()
    
    data['height_growth_lag'] = data['height_growth'].shift(1)
    
    data['time'] = pd.to_datetime(data['time'],unit='s')
    
    data.dropna(axis=0,inplace=True)
    
    data['target'] = (data['close'].shift(-1) > data['close']).astype(int)


# In[8]:


preprocess(data)

data


# In[9]:


predictors = ['height - 1','height_growth','mid_point_growth','mid_point']
target     = ['target']

train_start = 3
train_end = 80000

test_start = 80001


# In[10]:


#Train set
train_x = data.loc[train_start:train_end,predictors]
train_y = data.loc[train_start:train_end,target]

#Test set
test_x = data.loc[test_start:,predictors]
test_y = data.loc[test_start:,target]


# In[11]:


#Let us fit our glass box model
glass_box = ExplainableBoostingClassifier()
glass_box.fit(train_x,train_y)


# In[12]:


show(glass_box.explain_global())


# In[13]:


#Obtaining glass box predictions
glass_box_predictions = pd.DataFrame(glass_box.predict(test_x))


# In[14]:


glass_box_predictions.plot.kde()
test_y.plot.kde()


# In[15]:


glass_box_score = precision_score(test_y,glass_box_predictions)

glass_box_score


# In[16]:


#We can also obtain individual explanations for each prediction
show(glass_box.explain_local(test_x,test_y))


# In[17]:


train_x.shape


# In[18]:


terminal_info=mt5.terminal_info()
print(terminal_info)


# In[19]:


file_path=terminal_info.data_path+"\\MQL5\\Files\\"
print(file_path)


# In[335]:


data_path=argv[0]
last_index=data_path.rfind("\\")+1
data_path=data_path[0:last_index]
print("data path to save onnx model",data_path)


# In[336]:


onnx_model = ebm2onnx.to_onnx(glass_box,ebm2onnx.get_dtype_from_pandas(train_x))


# In[337]:


#Save the ONNX model in python
output_path = data_path+"Volatility_75_EBM.onnx"
onnx.save_model(onnx_model,output_path)


# In[338]:


#Save the ONNX model as a file to be imported in our MetaEditor
output_path = file_path+"Volatility_75_EBM.onnx"
onnx.save_model(onnx_model,output_path)


# In[110]:


data.dtypes

