# Copyright 2021, MetaQuotes Ltd.
# https://www.mql5.com

import MetaTrader5 as mt
import pandas as pd
import pytrendseries as pts

if not mt.initialize("D:\\Project\\mt\\MT5\\terminal64.exe"):
    print('initialize() failed!')
else:
   print(mt.version())
   sb=mt.symbols_total()
   rts=None
   if sb > 0:
     rts=mt.copy_rates_from_pos("GOLD_micro",mt.TIMEFRAME_M15,0,1000) 
   mt.shutdown()
   rts_fm=pd.DataFrame(rts)
   rts_fm['time']=pd.to_datetime(rts_fm['time'], unit='s')
   td_data=rts_fm[['time','close']].set_index('time')
   # print(td_data.head(10))

td='downtrend' # or "uptrend"
wd=120
limit=6

trends=pts.detecttrend(td_data,trend=td,limit=limit,window=wd)
# print(trends.head(15))
# pts.vizplot.plot_trend(td_data,trends)

rts_fm['trend']=0
rts_fm['trend_index']=0
max_len_rts=len(rts_fm)
max_len=len(trends)
last_start=0
last_end=0
for trend in trends.iterrows():
    start=trend[1]['index_from']
    end=trend[1]['index_to']

    if trend[0]==1 and start!=0:
        # Since the rts_fm["trend"] itself has been initialized to 0, there is no need to change the "trend" column
        rts_fm['trend_index'][0:start]=list(range(0,start))
    elif trend[0]==max_len and end!=max_len_rts-1:
        #we need to see if it ends in a downtrend at the end of the data
        rts_fm['trend_index'][last_end+1:len(rts_fm)]=list(range(0,max_len_rts-last_end-1))
    else:
        #Process the uptrend segments other than the beginning and end of the data
        rts_fm["trend_index"][last_end+1:start]=list(range(0,start-last_end-1))
    
    #Process each segments of the downtrend
    rts_fm["trend"][start:end+1]=1
    rts_fm["trend_index"][start:end+1]=list(range(0,end-start+1))
    last_start=start
    last_end=end
#rts_fm=rts_fm.iloc[trends.iloc[0,:]['index_from']:end,:]
rts_fm.to_csv('GOLD_micro_M15.csv')
