Esempio n. 1
0
def getKiteClient(kite_api_key):
    kite = KiteConnect(api_key=kite_api_key)
    if "access_token" in session:
        kite.set_access_token(session["access_token"])
    return kite
Esempio n. 2
0
Created on Oct 20, 2016

@author: apte
'''
from selenium import webdriver
from kiteconnect import KiteConnect
from urlparse import urlparse, parse_qs
import Constants
import time
import requests.packages
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import datetime

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

kite = KiteConnect(api_key=Constants.API_KEY)
login_data = None


def login():
    m_attempt = 0
    try:
        url = kite.login_url()
        driver = webdriver.Chrome()
        driver.get(url)

        driver.find_element_by_xpath('//*[@id="inputone"]').send_keys(
            Constants.USER1_ID)
        driver.find_element_by_xpath('//*[@id="inputtwo"]').send_keys(
            Constants.USER1_LP)
        driver.find_element_by_xpath(
import accountingLogic as accounts
import instrumentLogic as instrument
import watchlistLogic as watchlist
import lendingLogic as lending
import datetime
import appData
from kiteconnect import KiteConnect
import pandas as pd
import numpy as np
import routes
from pprint import pprint
import threading
import time

kiteObj = KiteConnect(api_key="7harnllatioi70jm")
kiteObj.set_access_token("mk4rkeQ4IOksda1DnXV8NNr8tl4xq754")


def initKite(data):
    access_token = data['access_token']
    kiteObj.set_access_token(access_token)
    return dailyDataUpdate()


def dailyDataUpdate():
    ret = {}
    print("inside daily data update function")
    fetchUpdatedInstrumentListFromKite()
    ret.update(instrument.dailyDataUpdate())
    ret.update(watchlist.dailyDataUpdate())
    ret.update({"updatedLoans": lending.dailyDataUpdate()})
Esempio n. 4
0
 def __init__(self):
     self.browser_config()
     self.kite = KiteConnect(api_key=self.config.key)
     self.orders_placed = {}
Esempio n. 5
0
import pandas as pd
import datetime as dt
import Connection as con
import numpy as np
import datetime
from datetime import datetime
from kiteconnect import KiteConnect

cursor = con.sqlit.cursor()
access_token = open("access_token.txt", 'r').read()
key_secret = open("api_key.txt", 'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
kite.set_access_token(access_token)

upward_sma_dir = False
downward_sma_dir = False
signal = []
""" get margin for individual stock given by broker"""


def getMargin(ticker):
    try:
        Margin = pd.read_csv("Margin.csv")
        Margin = Margin[Margin.tradingsymbol == ticker]
        return Margin.iloc[0]["mis_multiplier"]
    except:
        print("error encountered while fetching Margin")


# # a=getMargin("HDFC")
# # print(a)
Esempio n. 6
0
# https://kite.trade/connect/login?api_key=noigj9bflpwesql0

from kiteconnect import KiteConnect

kite = KiteConnect(api_key="noigj9bflpwesql0")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.

data = kite.request_access_token("request_token_here",
                                 secret="k0qb58ntbk1mpe8ohp392ym8768jnou9")
kite.set_access_token(data["access_token"])

# Place an order
try:
    order_id = kite.order_place(tradingsymbol="INFY",
                                exchange="NSE",
                                transaction_type="BUY",
                                quantity=1,
                                order_type="MARKET",
                                product="NRML")

    print("Order placed. ID is", order_id)
except Exception as e:
    print("Order placement failed", e.message)

# Fetch all orders
kite.orders()
import logging
from kiteconnect import KiteConnect

logging.basicConfig(level=logging.DEBUG)

kite = KiteConnect(api_key="your_api_key")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.

data = kite.generate_session("request_token_here", secret="your_secret")
kite.set_access_token(data["access_token"])

# Fetch margin detail for order/orders
try:
    # Fetch margin detail for single order
    order_param_single = [{
        "exchange": "NSE",
        "tradingsymbol": "INFY",
        "transaction_type": "BUY",
        "variety": "regular",
        "product": "MIS",
        "order_type": "MARKET",
        "quantity": 2
    }]

    margin_detail = kite.order_margins(order_param_single)
    logging.info(
Esempio n. 8
0
def kiteconnect(api_key, access_token):
    """Init Kite connect object."""
    return KiteConnect(api_key=api_key, access_token=access_token)
Esempio n. 9
0
def account(): #kite connect obj
    myAccount = KiteConnect(api_key=api_key)
    myAccount.set_access_token(access_token)
    return myAccount
Esempio n. 10
0
import requests
from requests.exceptions import ReadTimeout
from kiteconnect import exceptions

import datetime, time, os, random

trd_portfolio = {10970370: "NIFTY1971112000CE"}
overall_profit = 0

api_k = "dysoztj41hntm1ma"
# api_key
api_s = "rzgyg4edlvcurw4vp83jl5io9b610x94"
# api_secret
access_token = "klPpjqOG29Ijg5aFoBeyL1TCeCv0pBNZ"
kws = KiteTicker(api_k, access_token)
self = KiteConnect(api_key=api_k, access_token=access_token)


def positions(token):
    pos = self.positions()
    day_pos = pos['day']
    posdf = pd.DataFrame(day_pos)
    if posdf.empty:
        return 0
    else:
        total_pos = posdf.loc[posdf['instrument_token'] == token, ['quantity']]
        if total_pos.empty:
            return 0
        else:
            current_pos = total_pos.iloc[0, 0]
            maxquantity = min(current_pos, 5000)
Esempio n. 11
0
def get_zerodha_client(creds):
    zerodha = KiteConnect(api_key=creds["API_KEY"])
    zerodha.set_access_token(creds["ACCESS_TOKEN"])
    return zerodha

def max_dd(DF):
    "function to calculate max drawdown"
    df = DF.copy()
    df["cum_return"] = (1 + df["ret"]).cumprod()
    df["cum_roll_max"] = df["cum_return"].cummax()
    df["drawdown"] = df["cum_roll_max"] - df["cum_return"]
    df["drawdown_pct"] = df["drawdown"] / df["cum_roll_max"]
    max_dd = df["drawdown_pct"].max()
    return max_dd


logging.basicConfig(level=logging.DEBUG)

kite = KiteConnect(api_key="b1nuuiufnmsbhwxx")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.

#data = kite.generate_session("j5baS4PWcm9djWUGnooW0CcDqhBrBsan", api_secret="3azcz6fawz1bzet7bqe8624t7c9mkchp")
kite.set_access_token("IpDeZM5KJyxYFR8sktcrbCPFrraJy1Bk")

tickers = [
    "ICICIBANK", "SBIN", "WIPRO", "TATAMOTORS", "IOC", "INFRATEL", "ITC",
    "ZEEL", "ONGC", "NTPC"
]
tickers_to_insid = dict()
Esempio n. 13
0
def initial_setup():
    global s, u, data, kws, loop

    try:
        logged_in = False

        stored_api_key = read_key_from_settings('api_key')
        stored_access_token = read_key_from_settings('access_token')
        if stored_access_token is not None and stored_api_key is not None:
            print(
                'You already have a stored access token: [%s] paired with API key [%s]'
                % (stored_access_token, stored_api_key))

            try:
                u = KiteConnect(api_key=stored_api_key)
                u.set_access_token(stored_access_token)
                kws = KiteTicker(stored_api_key, stored_access_token)
                u.profile()
                logged_in = True
            except KiteException.TokenException as e:
                print('Sorry, there was an error [%s]. Let'
                      's start over\n\n' % e)

        if logged_in is False:

            stored_api_key = read_key_from_settings('api_key')
            if stored_api_key is None:
                stored_api_key = input('What is your app'
                                       's API key [%s]:  ' % stored_api_key)
            write_key_to_settings('api_key', stored_api_key)

            stored_api_secret = read_key_from_settings('api_secret')
            if stored_api_secret is None:
                stored_api_secret = input('What is your app'
                                          's API secret [%s]:  ' %
                                          stored_api_secret)
            write_key_to_settings('api_secret', stored_api_secret)

            stored_redirect_uri = read_key_from_settings('redirect_uri')
            if stored_redirect_uri is None:
                stored_redirect_uri = input('What is your app'
                                            's redirect_uri [%s]:  ' %
                                            stored_redirect_uri)
            write_key_to_settings('redirect_uri', stored_redirect_uri)

            stored_username = read_key_from_settings('username')
            if stored_username is None:
                stored_username = input('What is your Zerodha username:  '******'username', stored_username)

            stored_password = read_key_from_settings('password')
            if stored_password is None:
                stored_password = input('What is your Zerodha password:  '******'password', stored_password)

            stored_password2fa = read_key_from_settings('password2fa')
            if stored_password2fa is None:
                stored_password2fa = input('What is your Zerodha Pin:  ')
            write_key_to_settings('password2fa', stored_password2fa)

            u = KiteConnect(api_key=stored_api_key)

            print('URL: %s\n' % u.login_url())

            try:
                print("Trying to authenticate")
                token = authenticate(u.login_url(), stored_username,
                                     stored_password, stored_password2fa)
                print("Token: {0}".format(token))
            except SystemError as se:
                print('Uh oh, there seems to be something wrong. Error: [%s]' %
                      se)
                return

            print("Api secret: {0}".format(stored_api_secret))
            data = u.generate_session(token, api_secret=stored_api_secret)
            print("Data: {0}".format(data))
            write_key_to_settings('access_token', data['access_token'])
            u.set_access_token(data['access_token'])
            kws = KiteTicker(stored_api_key, data['access_token'])

        # kws = KiteTicker(stored_api_key, stored_access_token)
        # kws.on_ticks = on_ticks
        kws.on_connect = on_connect
        kws.on_close = on_close

        kws.connect(threaded=True)

        while True:

            def on_ticks(ws, ticks):
                print("Ticks= {}".format(ticks))
                helper_method(ticks)

            def helper_method(ticks):
                print("Inside helper function")
                filename = os.path.join(os.path.dirname(__file__),
                                        "Zerodha Instruments.xlsx")
                pythoncom.CoInitialize()
                app = xw.App(visible=False)
                wb = app.books.open(filename)

                ws = wb.sheets['Watchlist']
                df = pd.read_excel(filename, sheet_name='Watchlist')
                instrument_tokens_list = df['instrument_token'].tolist()
                for tick in ticks:
                    if tick['instrument_token'] in instrument_tokens_list:
                        pos = instrument_tokens_list.index(
                            tick['instrument_token'])
                        cell = 'E' + str(pos + 2)
                        ws.range(cell).value = tick['last_price']

                        # Code to place an order
                        # transact_type_cell = 'N' + str(pos + 2)
                        # transact_type = ws.range(transact_type_cell).value
                        # trading_symbol_cell = 'C' + str(pos + 2)
                        # trading_symbol = ws.range(trading_symbol_cell).value
                        # quantity_cell = 'O' + str(pos + 2)
                        # quantity = ws.range(quantity_cell).value
                        #
                        # if transact_type == 'buy':
                        #     if trading_symbol == 'NSE':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE,
                        #                       transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'BSE':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_BSE,
                        #                       transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'MCX':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_MCX,
                        #                       transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'NFO':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NFO,
                        #                       transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        # elif transact_type == 'sell':
                        #     if trading_symbol == 'NSE':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE,
                        #                       transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'BSE':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE,
                        #                       transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'MCX':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_MCX,
                        #                       transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        #     elif trading_symbol == 'NFO':
                        #         u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NFO,
                        #                       transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity,
                        #                       order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML)
                        #
                        # ws.range(transact_type_cell).value = ""
                        # ws.range(quantity_cell).value = ""
                wb.save(filename)
                app.quit()

            kws.on_ticks = on_ticks
    except Exception as error:
        print("Error {0}".format(str(error)))
        exit(0)
Esempio n. 14
0
"""
File:           websocket.py
Author:         Dibyaranjan Sathua
Created on:     04/04/21, 4:55 pm
"""
from kiteconnect import KiteConnect, KiteTicker
from kite_api.config import Config

kite = KiteConnect(api_key=Config.API_KEY)
# Login url
# https://kite.trade/connect/login?api_key=<api_key>&v=3
# print(kite.login_url())
data = kite.generate_session(Config.REQUEST_TOKEN,
                             api_secret=Config.API_SECRET)
kite.set_access_token(data["access_token"])
kite_ticker = KiteTicker(Config.API_KEY, data["access_token"])
instruments = kite.instruments('NFO')
# name should be "NIFTY" or "BANKNIFTY"
for contract in instruments:
    if "NIFTY" in contract['tradingsymbol']:
        token_detail = {
            'token': contract['instrument_token'],
            'symbol': contract['tradingsymbol'],
            'strike': contract['strike'],
            'type': contract['instrument_type'],
            'name': contract['name'],
            'LTP': contract['last_price'],
            'expiry': contract['expiry'],
            'exchange': contract['exchange']
        }
        if contract['instrument_token'] == 11220226:
Esempio n. 15
0
import queue
import os
import pandas as pd
import json
import pdb
import utilities as util
from yahoo_finance_api import YahooFinance as yf
import strategy as st
from pytz import timezone
import asyncio
import orders as ord

# Enter the user api_key and the access_token generated for that day
credentials = {'api_key': util.api_key, 'access_token': util.access_token}

kite = KiteConnect(api_key=credentials['api_key'])
kite.set_access_token(credentials['access_token'])

inst_list = kite.instruments('NSE')

infy_rec = util.get_instrument_details_by_name('INFY', inst_list)
sbin_rec = util.get_instrument_details_by_name('SBIN', inst_list)

sbin1m = yf('SBIN.NS', result_range='1d', interval='1m', dropna='True').result
sbin5m = yf('SBIN.NS', result_range='1d', interval='5m', dropna='True').result
print(sbin1m.tail())
print(sbin5m.tail())
sbin1m = sbin1m[:-1]
sbin5m = sbin5m[:-1]

print(' ---------------- After removing last row ------------------')
Esempio n. 16
0
def ticker(): #kite ticker obj
    myAccount = KiteConnect(api_key=api_key)
    myAccount.set_access_token(access_token)
    kws = KiteTicker(api_key, access_token)
    return kws
Esempio n. 17
0
configs = {
    "api_key": "lgrjz3jrxt20ldwt",
    "api_secret": "wk3ztbnna4r3gjjpp23z0l6dwkstqrqq"
}

low = sys.argv[1]
int_low = int(low)
high = sys.argv[2]
int_high = int(high)

open_time = time(10, 44, 0).strftime("%H:%M:%S")
execute_time = time(10, 44, 40).strftime("%H:%M:%S")
exit_time = time(15, 15, 0).strftime("%H:%M:%S")

kite = KiteConnect(api_key=configs["api_key"])


@app.route("/")
def hello():
    return redirect("http://*****:*****@app.route("/login")
def login():
    return redirect(kite.login_url(), code=302)


@app.route('/login/callback')
def get_request_token():
    request_token = request.args.get('request_token')
    time.sleep(7)

    urls = appscript.app('Google Chrome').windows.tabs.URL()

    strng = urls[0][-1]
    sess_id = strng.partition('request_token=')[2]

    sess_id = sess_id.partition('&action')[0]
    print(sess_id)
    return sess_id


# Initialise

kite = KiteConnect(api_key="API_KEY")

data = kite.generate_session(get_sess_id(), api_secret="API_SECRET")
tokens = [54922503, 55168263]

kws = KiteTicker("API_KEY", data['access_token'])

# tokens = [10973954, 14451970]

TradeTableDF = pd.DataFrame(columns=[
    'Time', 'Action', 'SpreadValue', 'zscore', 'nearLTP', 'farLTP',
    'ExactSpread', 'AdverseSpread'
])

position = 0
Esempio n. 19
0
def start(name, date, access_token, interval):
    # print("Starting Trading Engine...", flush=True)
    config = configparser.ConfigParser()
    # path = os.getcwd()
    path = '/home/ubuntu/APT/APT/Live_Trading'
    config_path = path + '/config.ini'
    config.read(config_path)
    api_key = config['API']['API_KEY']

    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)
    os.chdir(path)
    print("Connection Successful")

    scrip_dict = {
        'ADANIPORTS': '3861249',
        'ASIANPAINT': '60417',
        'AXISBANK': '1510401',
        'BAJAJ-AUTO': '4267265',
        'BAJFINANCE': '81153',
        'BAJAJFINSV': '4268801',
        'BPCL': '134657',
        'BHARTIARTL': '2714625',
        'INFRATEL': '7458561',
        'BRITANNIA': '140033',
        'CIPLA': '177665',
        'COALINDIA': '5215745',
        'DRREDDY': '225537',
        'EICHERMOT': '232961',
        'GAIL': '1207553',
        'GRASIM': '315393',
        'HCLTECH': '1850625',
        'HDFCBANK': '341249',
        'HEROMOTOCO': '345089',
        'HINDALCO': '348929',
        'HINDUNILVR': '356865',
        'HDFC': '340481',
        'ICICIBANK': '1270529',
        'ITC': '424961',
        'IBULHSGFIN': '7712001',
        'IOC': '415745',
        'INDUSINDBK': '1346049',
        'INFY': '408065',
        'JSWSTEEL': '3001089',
        'KOTAKBANK': '492033',
        'LT': '2939649',
        'M&M': '519937',
        'MARUTI': '2815745',
        'NTPC': '2977281',
        'ONGC': '633601',
        'POWERGRID': '3834113',
        'SBIN': '779521',
        'SUNPHARMA': '857857',
        'TCS': '2953217',
        'TATAMOTORS': '884737',
        'TATASTEEL': '895745',
        'TECHM': '3465729',
        'TITAN': '897537',
        'UPL': '2889473',
        'ULTRACEMCO': '2952193',
        'VEDL': '784129',
        'WIPRO': '969473',
        'YESBANK': '3050241',
        'ZEEL': '975873',
        'RELIANCE': '738561'
    }

    def prev_weekday(adate):
        adate -= timedelta(days=1)
        while adate.weekday() > 4:
            adate -= timedelta(days=1)
        return adate

    prev_date = prev_weekday(
        datetime.datetime.strptime(date, "%Y-%m-%d").date())
    data = kite.historical_data(instrument_token=int(scrip_dict[name]),
                                from_date=date,
                                to_date=date,
                                interval=interval)
    data = pd.DataFrame(data)

    prev_day_data = kite.historical_data(instrument_token=int(
        scrip_dict[name]),
                                         from_date=prev_date,
                                         to_date=prev_date,
                                         interval='day')
    prev_day_data = pd.DataFrame(prev_day_data)
    prev_day_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
    prev_day_data.to_csv("previous_day_data_" + name + '.csv')

    for i in range(len(data)):
        single_candle = data.iloc[[i]]
        single_candle.to_csv('ohlc_data_' + name + '.csv', index=False)
        print(single_candle, flush=True)
        time.sleep(60)
Esempio n. 20
0
def get_login(api_k):
    global kws, kite
    kite = KiteConnect(api_key=api_k)
    return kite.login_url()
Esempio n. 21
0
def start(name, token, access_token, timeframe):
    # print("Starting Trading Engine...", flush=True)
    config = configparser.ConfigParser()
    # path = os.getcwd()
    path = '/home/ubuntu/APT/APT/Paper_Trading'
    config_path = path + '/config.ini'
    config.read(config_path)
    api_key = config['API']['API_KEY']

    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)
    # Get previous day candle
    def prev_weekday(adate):
        holiday_list=['2019-10-02','2019-10-08','2019-10-08','2019-11-12','2019-12-25']
        adate -= timedelta(days=1)
        if adate.strftime('%Y-%m-%d') in holiday_list:
            adate -= timedelta(days=1)
        while adate.weekday() > 4:
            adate -= timedelta(days=1)
        return adate
    date_from = prev_weekday(date.today())
    date_to = date_from
    interval = 'day'
    previous_day_data = kite.historical_data(instrument_token=token[0], from_date=date_from, to_date=date_to, interval=interval)
    previous_day_data = pd.DataFrame(previous_day_data)
    previous_day_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
    previous_day_data.to_csv("previous_day_data_"+ name +'.csv')

    # Sleep till 9:15
    time_now = datetime.now()
    sleep_time = 60 - time_now.second
    time.sleep(sleep_time)
    time_now = datetime.now()
    print('Script Started at ' + str(time_now),flush=True)

    # Initialise
    print("Initialising Kite Ticker")
    kws = KiteTicker(api_key, access_token)
    start.tick_df = pd.DataFrame(columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([]))
    start.last_saved_time = 10


    def on_ticks(ws, ticks):
        # Callback to receive ticks.
        # print(ticks)
        # print(ticks[0]['timestamp'] >= datetime.now().replace(hour= 9,minute= 15, second = 0,microsecond = 0))
        # print(ticks[0]['timestamp'] >= datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S'))
        if ticks[0]['timestamp'] >= datetime.now().replace(hour= 3,minute= 45, second = 0,microsecond = 0):
        # if ticks[0]['timestamp'] >= datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S'):
            print(ticks)
            start.tick_df = start.tick_df.append({'Token': ticks[0]['instrument_token'], 'Timestamp': ticks[0]['timestamp'], 'LTP': ticks[0]['last_price']}, ignore_index=True)
            if (start.tick_df['Timestamp'][len(start.tick_df) - 1].minute % 5 == 0) and (start.tick_df['Timestamp'][len(start.tick_df) - 1].minute != start.last_saved_time):
                # save the last minute
                start.last_saved_time = start.tick_df['Timestamp'][len(start.tick_df) - 1].minute

                # drop last row
                start.tick_df.drop(start.tick_df.tail(1).index, inplace=True)
                print(len(start.tick_df))

                # set timestamp as index
                start.tick_df = start.tick_df.set_index(['Timestamp'])
                start.tick_df['Timestamp'] = pd.to_datetime(start.tick_df.index, unit='s')

                # convert to OHLC format
                data_ohlc = start.tick_df['LTP'].resample(timeframe).ohlc()
                print(data_ohlc)
                # save the dataframe to csv
                data_ohlc.to_csv('ohlc_data_' + name +'.csv')
                print("Printed at " + str(datetime.now()))

                # initialize the dataframe
                start.tick_df = pd.DataFrame(columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([]))
                print(len(data_ohlc))

    def on_connect(ws, response):
        # Callback on successful connect.
        # Subscribe to a list of instrument_tokens
        ws.subscribe(token)
        # Set TITAN to tick in `full` mode.
        ws.set_mode(ws.MODE_FULL, token)

    # Callback when current connection is closed.
    def on_close(ws, code, reason):
        logging.info("Connection closed: {code} - {reason}".format(code=code, reason=reason))


    # Callback when connection closed with error.
    def on_error(ws, code, reason):
        logging.info("Connection error: {code} - {reason}".format(code=code, reason=reason))


    # Callback when reconnect is on progress
    def on_reconnect(ws, attempts_count):
        logging.info("Reconnecting: {}".format(attempts_count))


    # Callback when all reconnect failed (exhausted max retries)
    def on_noreconnect(ws):
        logging.info("Reconnect failed.")


    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_close = on_close
    kws.on_error = on_error
    kws.on_connect = on_connect
    kws.on_reconnect = on_reconnect
    kws.on_noreconnect = on_noreconnect
    print("Callbacks assigned")


    # Infinite loop on the main thread. Nothing after this will run.
    # You have to use the pre-defined callbacks to manage subscriptions.
    kws.connect()
    print("KWS disconnected")
from kiteconnect import KiteConnect
api_key="Your API KEY"
api_secret="Your API Secret"
kite=KiteConnect(api_key,api_secret)
kite.request_access_token('Your Access Token',api_secret)
kite.place_order(tradingsymbol='SBIN',quantity=1,exchange='NSE',order_type='MARKET',transaction_type='BUY',product='CNC')
import TradingScripts.Utils as util
from kiteconnect import KiteConnect

kite = KiteConnect(api_key=util.KITE_API_KEY)

# https://kite.trade/connect/login?api_key=453dipfh64qcl484&v=3
access_token = kite.generate_session('jAwDHADC3cEJDuIgfyX27WqFklb4UxMp',
                                     util.KITE_API_SECRET)["access_token"]
print('Received access_token: %s' % access_token)
open(util.KITE_LATEST_ACCESS_CODE_FILE, 'w+').close()
with open(util.KITE_LATEST_ACCESS_CODE_FILE, 'a') as the_file:
    the_file.write(access_token)
Esempio n. 24
0
import logging
from kiteconnect import KiteConnect

logging.basicConfig(level=logging.DEBUG)

kite = KiteConnect(api_key="yu4viu4fusp4ofql")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.
# https://kite.zerodha.com/connect/login?v=3&api_key=yu4viu4fusp4ofql

data = kite.generate_session(request_token="4k5xWxu640JIT52ESMRaPYEgcg7gVPlL",
                             api_secret="b610n7lnsgaxvk139zw2motqnmz00iuq")
kite.set_access_token(data["access_token"])
''' 
# Place an order
try:
    order_id = kite.place_order(
        variety=kite.VARIETY_REGULAR,
        exchange=kite.EXCHANGE_NSE,
        tradingsymbol="INFY",
        transaction_type=kite.TRANSACTION_TYPE_BUY,
        quantity=1,
        product=kite.PRODUCT_NRML,
        order_type=kite.ORDER_TYPE_MARKET
    )

    logging.info("Order placed. ID is: {}".format(order_id))
Esempio n. 25
0
from kiteconnect import KiteConnect
from modules import auth
import pandas as pd

userdata = auth.get_userdata()
kite = KiteConnect(api_key=userdata['api_key'])
kite.set_access_token(userdata['access_token'])

dict = {}


def get_all_nse_instruments():
    data = kite.instruments(exchange="NSE")

    df = pd.DataFrame(columns=['instrument_token', 'tradingsymbol', 'name'])
    df = pd.DataFrame.from_dict(data, orient='columns', dtype=None)
    if not df.empty:
        df = df[['instrument_token', 'tradingsymbol', 'name']]

    for ind in df.index:
        tokenName = df['tradingsymbol'][ind]
        tokenNumber = df['instrument_token'][ind]
        dict[tokenName] = tokenNumber


def isNaN(string):
    return string != string


def get_custom_instruments(stocks_list):
    get_all_nse_instruments()
Esempio n. 26
0
import requests

from kiteconnect import KiteConnect
from kiteconnect import KiteTicker
from datetime import datetime, timedelta

logging.basicConfig(level=logging.DEBUG)
print("Opening Range Breakout Code for BANKNIFTY")
symbol = "14350850"
symboltxt = "BANKNIFTY20APRFUT"
#sameer key
#api_key = '7s6e8cjvyjw4bgvo'
#api_secret = 'b8yem58dwlgih4s1u2ryd7ynkj39hxck'
api_key = 'xyipj2fx4akxggck'
api_secret = 'ehzimap1bmhdbmrg2jbysn6jddxmmfr4'
conn = KiteConnect(api_key=api_key)
accToken = 'i2E2K37aqYaBuWBNcC9uDT23Pbq14hYr'
conn.set_access_token(accToken)
high = 0
low = 0
highlowTime = datetime.now()
highlowTime1 = highlowTime.replace(hour=9, minute=29, second=56)
highlowTime2 = highlowTime.replace(hour=9, minute=29, second=59)

print("Get Opening Range High Low")
#url = "https://api.kite.trade/instruments/historical/" + symbol + "/15minute?from=2020-03-24+09:15:00&to=2020-03-24+09:29:59"
dateStr = str(highlowTime.year) + "-" + str("{0:02}".format(
    highlowTime.month)) + "-" + str("{0:02}".format(highlowTime.day))
url = "https://api.kite.trade/instruments/historical/" + symbol + "/15minute?from=" + dateStr + "+09:15:00&to=" + dateStr + "+09:29:58"
headers = {
    "X-Kite-Version": "3",
Esempio n. 27
0
"""
spark-submit --conf spark.sql.shuffle.partitions=4 --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.0 account_stream.py
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
"""
spark = SparkSession \
    .builder \
    .appName("myApp") \
    .getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("ERROR")
spark.conf.set("spark.sql.execution.arrow.enabled", "true")
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])

access_token = 'xom9KKp6yx2eEqv5NAqsxGeuolKUuUqb'
api_key = '7lwrah449p8wk3i0'
kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token=access_token)

account_df = pd.read_csv('tradables.csv')
account_df = account_df
account_df = account_df[['instrument_token', 'symbol', 'margin']]
account_df['position_type'] = None
account_df['position'] = False
account_df['order_id'] = None
account_df['filled_quantity'] = 0
account_df['quantity'] = 0
account_df = account_df.set_index('symbol')

available_margin = 200000
position_value = 100000
Esempio n. 28
0
import json
import urllib

import requests
import redis
from kiteconnect import KiteConnect

kite = KiteConnect(api_key="<YOUR-API-KEY>", debug=True)
redis_con = redis.Redis(host="<REDIS-HOST>",
                        port=6379,
                        db=11,
                        charset="utf-8",
                        decode_responses=True,
                        password="******")

# def send_message_bot(chat_id, text):
# 	url = 'https://api.telegram.org/<YOUR-BOT-TOKEN>/sendMessage'
# 	r = requests.post(url, {'chat_id': chat_id, 'text': text}).json()


def set_token(request_token):

    data = kite.generate_session(request_token,
                                 api_secret="<ZERODHA-API-SECRET>")
    redis_con.set("my_token", data["access_token"])
    return data["access_token"]


def place_order(received_data, txn_type="BUY"):

    stock_id = [
Esempio n. 29
0
def kiteconnect():
    """Init Kite connect object."""
    kiteconnect = KiteConnect(api_key='<API-KEY>',
                              access_token='<ACCESS-TOKEN>')
    kiteconnect.root = 'http://kite_trade_test'
    return kiteconnect
Esempio n. 30
0
from app.utils import retry, print_message, QueueFullException
from kiteconnect import KiteConnect

# Dummy Keys
from websocket import WebSocketException, WebSocketConnectionClosedException
#
# api_key = "abcd51hdgns"  # API KEY
# user_id = "DR1234"  # USER ID
# public_token = "asljfldlncnl093nnnzc4"  # PUBLIC TOKEN

api_key = "qxlf7e2xdrtkdbk3"  # API KEY
user_id = "ZT6579"  # USER ID
public_token = "btdtrkgobwbyc70u5l59k2v1rjvzanim"  # PUBLIC TOKEN

API_KEY = ''
kite = KiteConnect(api_key=API_KEY)

# o_instr = [738561, 5633]
# instruments = [53397255, 53426439, 53427463, 53426951, 53329415, 53405959]

logging.basicConfig(
    level=logging.DEBUG,
    format='(%(threadName)-10s) %(message)s',
)
logging.getLogger('websocket').setLevel(logging.DEBUG)

LOG = logging.getLogger(__name__)


class ZerodhaWorker(Thread):
    """" ZerodhaWorker - The base class to add instruments for subscription