from jugaad_trader import Zerodha
from datetime import datetime, timedelta
import pandas as pd

from ta.volume import VolumeWeightedAveragePrice
from talib import EMA

today = datetime.today()

kite = Zerodha()
kite.set_access_token()

nfo_instruments = pd.DataFrame(kite.instruments("NFO"))
banknifty_instruments = nfo_instruments.loc[(
    nfo_instruments.name == 'BANKNIFTY')]

banknifty_data = pd.DataFrame(kite.historical_data(260105, today - timedelta(days=9) , today, "day"))

overall = 0
for index, row in banknifty_data.iterrows():
    close = int(round(row.close, -2))
    date = row.date.date()
    instrument_tokens = banknifty_instruments.loc[banknifty_instruments.strike == close, [
        'instrument_token', 'tradingsymbol']].head(2).instrument_token.to_list()

    for instrument in instrument_tokens:
        data = pd.DataFrame(kite.historical_data(instrument, date + timedelta(hours=9,
                        minutes=21), date + timedelta(hours=15, minutes=21), "3minute", oi=True))


        data['ema21'] = EMA(data.close, timeperiod = 21)
        data['oidata'] = (1/data.oi)
        data['oiwap'] = VolumeWeightedAveragePrice(
            data.high, data.low, data.close, data.oidata, window=21).volume_weighted_average_price()
    

        open_position = False
        profit = 0
        overall = 0
        trails = []
        last_tick = ""

        for index, row in data.iterrows():
            if not open_position:
                if row.close > row.oiwap:
                    open_position = True
                    buy_price = row.close
                    last_tick = row
                    trails = []
            elif open_position:
                # if row.close < row.ema21:
                #     # print(row.close - buy_price, trails)
                    # profit += row.close - buy_price
                    # open_position = False
                if row.low < last_tick.low:
                    print(row.close - buy_price, max(trails))
                    profit += row.close - buy_price
                    open_position = False

                else:
                    last_tick = row
                    trails.append(row.close - buy_price)
            
        print(profit)
