# This script is a WebSocket client connects to a stock broker's server # using their library KiteConnect. # I have added few rules to send notifications to the Slack channel # when it satisfies. The rest of the part is managed manually at the moment # and working on the automation part yet. The data is stored in MongoDB to # visualize the data in charts. import logging import json import datetime from time import gmtime, strftime import pymongo from pymongo import MongoClient import pdb; import pathlib import csv import redis_tokens from dateutil.relativedelta import relativedelta, FR, TH import os from slackclient import SlackClient from kiteconnect import KiteConnect from kiteconnect import KiteTicker ###################### pid = str(os.getpid()) pidfile = "/tmp/notifier.pid" currentFile = open(pidfile, 'w') currentFile.write(pid) currentFile.close() ###################### logging.basicConfig(level=logging.DEBUG) # Initialise pathlib.Path('data/unstructured/live/bank_nifty').mkdir(parents=True, exist_ok=True) def myconverter(o): if isinstance(o, datetime.datetime): return o.__str__() kws = KiteTicker("username_goes_here", redis_tokens.user_token) sc = SlackClient("token_goes_here") client = pymongo.MongoClient("mongo_creds_goes_here") old_vol = 0 prev_price = 0 prev_buy_qty = 0 prev_sell_qty = 0 def notify(ltt, last_price, buy_qty, sell_qty, new_vol=1000): global old_vol global prev_price global prev_buy_qty global prev_sell_qty if datetime.datetime(2013, 1, 31, 9, 15).time() == ltt.time(): old_vol = 0 prev_price = 0 prev_buy_qty = 0 prev_sell_qty = 0 # logging.debug(old_vol) vall = new_vol - old_vol logging.debug(vall) market_buy_or_sell = "None" # market_buy_or_sell logic goes here if vall >= 4000: db = client.brain db.bnf_vol.insert( { "item" : "vol_change", "stock": "BNF OCT FUT", "vol_change" : vall, "prev_price" : prev_price, "last_price" : last_price, "prev_buy_qty": prev_buy_qty, "buy_qty":buy_qty, "prev_sell_qty":prev_sell_qty, "sell_qty":sell_qty, "created_at": datetime.datetime.now() } ) print('notifying...') sc.api_call( "chat.postMessage", channel="channel_id", username="Future", text="Volume change(BNF OCT FUT) - {} | Price: ({} to {}) | Buys: ({} to {}) | Sells: ({} to {})".format(vall, prev_price, last_price, prev_buy_qty, buy_qty, prev_sell_qty, sell_qty) ) # raise alarm, there's a new huge volume in market, let's check if we can follow their path to profit old_vol = new_vol prev_price = last_price prev_buy_qty = buy_qty prev_sell_qty = sell_qty def on_ticks(ws, ticks): try: # Callback to receive ticks. notify(ticks[0]['last_trade_time'], ticks[0]['last_price'], ticks[0]['buy_quantity'], ticks[0]['sell_quantity'], ticks[0]['volume']) md_buy_arr = [] md_buy = ticks[0]['depth']['buy'] for tick in md_buy: data = [tick['quantity'], tick['price'], tick['orders']] md_buy_arr.append(data) md_sell_arr = [] md_sell = ticks[0]['depth']['sell'] for tick in md_sell: data = [tick['quantity'], tick['price'], tick['orders']] md_sell_arr.append(data) row = [ticks[0]['last_price'], ticks[0]['last_quantity'], ticks[0]['volume'],myconverter(ticks[0]['last_trade_time']), ticks[0]['average_price'],ticks[0]['buy_quantity'], ticks[0]['sell_quantity'],md_buy_arr,md_sell_arr] with open('data/unstructured/live/bank_nifty/live_full-' + "{}".format(datetime.datetime.today().strftime('%d-%m-%Y')) + '.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row) csvFile.close() except: print("something wrong") # pdb.set_trace() # logging.debug("Ticks: {}".format(ticks)) def on_connect(ws, response): # Callback on successful connect. # Subscribe to a list of instrument_tokens (RELIANCE and ACC here). ws.subscribe([14627842]) # Set RELIANCE to tick in `full` mode. ws.set_mode(ws.MODE_FULL, [14627842]) 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()