from urllib.parse import urlparse, parse_qs
import requests
from fyers_api import fyersModel
from fyers_api import accessToken
import traceback
import json

# FILL YOU DETAILS IN BELOW HIGHLIGHTED FIELDS

client_id = ""
secret_key = ""
redirect_uri = "http://localhost:8080"
response_type = "code"
grant_type = "authorization_code"
state = "None"
nonce = "private"

input = {"fyers_id":"","password":"","pan_dob":"","app_id":"","redirect_uri":"http://localhost:8080","appType":"100","code_challenge":"","state":"None","scope":"","nonce":"","response_type":"code","create_cookie":True}


session = session=accessToken.SessionModel(client_id=client_id,
secret_key='',redirect_uri='http://localhost:8080',
response_type='code', grant_type='authorization_code',state= None )
response = session.generate_authcode()
print("Response from Try-Catch 1 is - \n", response)

headers = {
        "accept": "*/*",
        "accept-language": "en-IN,en-US;q=0.9,en;q=0.8",
        "content-type": "application/json; charset=UTF-8",
        "sec-ch-ua" :'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
}

result = requests.post("https://api.fyers.in/api/v2/token",
                           headers=headers, json=input, allow_redirects=True)
var = json.loads(result.content)
URL = var["Url"]
print(URL)
parsed = urlparse(URL)
parsedlist = parse_qs(parsed.query)['auth_code']
auth_code = parsedlist[0]
session.set_token(auth_code)
response = session.generate_token()
access_token = response["access_token"]
print(access_token)


fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path="/Users/dedula/code/pycharmprojects/stocks/daydata")

print(fyers.get_profile())

data = {"symbol":"NSE:SBIN-EQ","resolution":"1","date_format":"0","range_from":"1629695667","range_to":"1629710067","cont_flag":"1"}


print(fyers.history(data))


print(fyers.orderbook())