import pandas as pd
from jugaad_trader import Zerodha
from datetime import datetime, timedelta
from dateutil.tz import tzoffset
import talib
from ta.volatility import DonchianChannel

kite = Zerodha()

kite.set_access_token()

today = datetime.today()


def get_timestamp():
    return datetime.now(tzoffset(None, 19800)).isoformat(' ', 'seconds')


def get_ltp(instrument_token):
    return kite.ltp(instrument_token)[str(instrument_token)]['last_price']



# Tickertape: {9957378: 'BANKNIFTY2170835000CE', 9957634: 'BANKNIFTY2170835000PE'}
historical_data = pd.DataFrame(kite.historical_data(
    9957378, "2021-07-02 09:15:00", "2021-07-02 15:30:00", "minute", oi=True))

historical_data["oiema21"] = talib.EMA(historical_data.oi, timeperiod = 21)
historical_data['don'] = talib.MIN(historical_data.oi, timeperiod = 21)


open_position = False
prev_candle = ""
buy_price = 0
sell_price = 0

profit = 0
pnl = []



for index, data in historical_data.iterrows():
    prev_candle = historical_data.iloc[index-1]

    if not open_position:
        if prev_candle.don > data.oi:
            open_position = True
            buy_price = data.close
            print("Trade opened", data.close)
            


    if open_position:
        if prev_candle.don < data.oi:
            open_position = False
            sell_price = data.close 
            profit += sell_price - buy_price
            print("Trade closed", data.close)
            print("PNL:", sell_price - buy_price, pnl)
            

            buy_price=0
            sell_price=0
            pnl = []
        elif prev_candle.don > data.oi:
            pnl.append(data.close - buy_price)
    prev_oi = data.oi

print(profit)



# oi = historical_data.oi.tolist()
# prev_oi = 0
# counter = 0
# for oi_value in oi:
#     if oi_value < prev_oi:
#         counter+=1
#     prev_oi = oi_value

# print(counter)
