Skip to content

Instantly share code, notes, and snippets.

@rhnvrm
Created January 18, 2019 07:31
Show Gist options
  • Save rhnvrm/f1a047ed786ed8415dadbd6fc3b797ad to your computer and use it in GitHub Desktop.
Save rhnvrm/f1a047ed786ed8415dadbd6fc3b797ad to your computer and use it in GitHub Desktop.
Kite Trade CLI Chart Example
import logging
import os
import sys
from kiteconnect import KiteConnect, KiteTicker
from math import cos
from math import sin
from math import pi
from math import floor
from math import ceil
KITE_TRADE_API_KEY = ""
KITE_TRADE_API_SECRET = ""
# https://github.com/kroitor/asciichart/blob/master/asciichartpy/__init__.py
def plot(series, cfg={}):
minimum = cfg['minimum'] if 'minimum' in cfg else min(series)
maximum = cfg['maximum'] if 'maximum' in cfg else max(series)
interval = abs(float(maximum) - float(minimum))
offset = cfg['offset'] if 'offset' in cfg else 3
padding = cfg['padding'] if 'padding' in cfg else ' '
height = cfg['height'] if 'height' in cfg else interval
ratio = height / interval
min2 = floor(float(minimum) * ratio)
max2 = ceil(float(maximum) * ratio)
intmin2 = int(min2)
intmax2 = int(max2)
rows = abs(intmax2 - intmin2)
width = len(series) + offset
placeholder = cfg['format'] if 'format' in cfg else '{:8.2f} '
result = [[' '] * width for i in range(rows + 1)]
# axis and labels
for y in range(intmin2, intmax2 + 1):
label = placeholder.format(float(maximum) - ((y - intmin2) * interval / rows))
result[y - intmin2][max(offset - len(label), 0)] = label
result[y - intmin2][offset - 1] = '┼' if y == 0 else '┤'
y0 = int(series[0] * ratio - min2)
result[rows - y0][offset - 1] = '┼' # first value
for x in range(0, len(series) - 1): # plot the line
y0 = int(round(series[x + 0] * ratio) - intmin2)
y1 = int(round(series[x + 1] * ratio) - intmin2)
if y0 == y1:
result[rows - y0][x + offset] = '─'
else:
result[rows - y1][x + offset] = '╰' if y0 > y1 else '╭'
result[rows - y0][x + offset] = '╮' if y0 > y1 else '╯'
start = min(y0, y1) + 1
end = max(y0, y1)
for y in range(start, end):
result[rows - y][x + offset] = '│'
return '\n'.join([''.join(row) for row in result])
logging.basicConfig(level=logging.DEBUG)
def main():
if len(sys.argv) != 3:
print("usage: python kite-cli.py <Stock Name> <StockID>")
print("eg: python kite-cli.py IDFCFIRSTB 2863105")
return
STOCKNAME = sys.argv[1]
STOCKID = sys.argv[2]
print("Starting...")
print(STOCKNAME, STOCKID)
# Initialise
kite = KiteConnect(api_key=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.
print("Login:", kite.login_url())
print("Enter request token: ")
req_token = input()
data = kite.generate_session(req_token, api_secret=API_SECRET)
kws = KiteTicker(API_KEY, data["access_token"])
data = []
def on_ticks(ws, ticks):
# Callback to receive ticks.
data.append(ticks[0]['last_price'])
if len(data) > 3:
os.system("printf '\033c'")
columns, rows = os.get_terminal_size(0)
print(STOCKNAME)
try:
print(plot(data[-columns+12:], cfg={
"height": rows - 5,
}))
except:
pass
def on_connect(ws, response):
# Callback on successful connect.
print("Loading", STOCKNAME)
ws.subscribe([int(STOCKID)])
# Set RELIANCE to tick in `full` mode.
ws.set_mode(ws.MODE_FULL, [int(STOCKID)])
def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
kws.connect()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment