import MetaTrader5 as mt5
import numpy as np
import datetime

if not mt5.initialize():
    print("initialize() failed")
    quit()

rates = mt5.copy_rates_from_pos("USDJPY", mt5.TIMEFRAME_H1, 0, 105)
mt5.shutdown()

if rates is None:
    print("Failed to get rates")
    quit()

closes = [r[4] for r in rates]

def calc_mt5_logic(prices_array, period=100):
    ld = []
    for i in range(1, len(prices_array)):
        if prices_array[i-1] > 0:
            ld.append(np.log(prices_array[i] / prices_array[i-1]))
            
    ld = ld[-period:]
    mean = np.mean(ld)
    cd = 0.0
    mx = -1e300
    mn = 1e300
    ssq = 0.0
    for d_val in ld:
        d = d_val - mean
        cd += d
        if cd > mx: mx = cd
        if cd < mn: mn = cd
        ssq += d * d
    R = mx - mn
    if R == 0: R = 1e-10
    S = np.sqrt(ssq / period)
    if S == 0: S = 1e-10
    hurst = np.log(R / S) / np.log(period)
    return max(0.0, min(1.0, hurst))

print(f"Total bars fetched: {len(closes)}")
# Print the last 3 dates to see what time they represent
for i in range(1, 4):
    t = datetime.datetime.fromtimestamp(rates[-i][0], tz=datetime.timezone.utc)
    print(f"Bar -{i} time: {t}, Close: {rates[-i][4]}")

closed_bars = closes[:-1] 

val_current = calc_mt5_logic(closed_bars[-101:], 100)
print(f"Hurst for currently closed 100 bars (ending at previous full hour): {val_current:.4f}")

val_1ha = calc_mt5_logic(closed_bars[-102:-1], 100)
print(f"Hurst for 1 hour ago (ending 2 full hours ago): {val_1ha:.4f}")
