Path: blob/master/src/instruments/Instruments.py
296 views
import os1import logging2import json34from config.Config import getServerConfig, getTimestampsData, saveTimestampsData5from core.Controller import Controller6from utils.Utils import Utils78class Instruments:9instrumentsList = None10symbolToInstrumentMap = None11tokenToInstrumentMap = None1213@staticmethod14def shouldFetchFromServer():15timestamps = getTimestampsData()16if 'instrumentsLastSavedAt' not in timestamps:17return True18lastSavedTimestamp = timestamps['instrumentsLastSavedAt']19nowEpoch = Utils.getEpoch()20if nowEpoch - lastSavedTimestamp >= 24 * 60* 60:21logging.info("Instruments: shouldFetchFromServer() returning True as its been 24 hours since last fetch.")22return True23return False2425@staticmethod26def updateLastSavedTimestamp():27timestamps = getTimestampsData()28timestamps['instrumentsLastSavedAt'] = Utils.getEpoch()29saveTimestampsData(timestamps)3031@staticmethod32def loadInstruments():33serverConfig = getServerConfig()34instrumentsFilepath = os.path.join(serverConfig['deployDir'], 'instruments.json')35if os.path.exists(instrumentsFilepath) == False:36logging.warn('Instruments: instrumentsFilepath %s does not exist', instrumentsFilepath)37return [] # returns empty list3839isdFile = open(instrumentsFilepath, 'r')40instruments = json.loads(isdFile.read())41logging.info('Instruments: loaded %d instruments from file %s', len(instruments), instrumentsFilepath)42return instruments4344@staticmethod45def saveInstruments(instruments = []):46serverConfig = getServerConfig()47instrumentsFilepath = os.path.join(serverConfig['deployDir'], 'instruments.json')48with open(instrumentsFilepath, 'w') as isdFile:49json.dump(instruments, isdFile, indent=2, default=str)50logging.info('Instruments: Saved %d instruments to file %s', len(instruments), instrumentsFilepath)51# Update last save timestamp52Instruments.updateLastSavedTimestamp()5354@staticmethod55def fetchInstrumentsFromServer():56instrumentsList = []57try:58brokerHandle = Controller.getBrokerLogin().getBrokerHandle()59logging.info('Going to fetch instruments from server...')60instrumentsList = brokerHandle.instruments('NSE')61instrumentsListFnO = brokerHandle.instruments('NFO')62# Add FnO instrument list to the main list63instrumentsList.extend(instrumentsListFnO)64logging.info('Fetched %d instruments from server.', len(instrumentsList))65except Exception as e:66logging.exception("Exception while fetching instruments from server")67return instrumentsList6869@staticmethod70def fetchInstruments():71if Instruments.instrumentsList:72return Instruments.instrumentsList7374instrumentsList = Instruments.loadInstruments()75if len(instrumentsList) == 0 or Instruments.shouldFetchFromServer() == True:76instrumentsList = Instruments.fetchInstrumentsFromServer()77# Save instruments to file locally78if len(instrumentsList) > 0:79Instruments.saveInstruments(instrumentsList)8081if len(instrumentsList) == 0:82print("Could not fetch/load instruments data. Hence exiting the app.")83logging.error("Could not fetch/load instruments data. Hence exiting the app.");84exit(-2)8586Instruments.symbolToInstrumentMap = {}87Instruments.tokenToInstrumentMap = {}88for isd in instrumentsList:89tradingSymbol = isd['tradingsymbol']90instrumentToken = isd['instrument_token']91# logging.info('%s = %d', tradingSymbol, instrumentToken)92Instruments.symbolToInstrumentMap[tradingSymbol] = isd93Instruments.tokenToInstrumentMap[instrumentToken] = isd9495logging.info('Fetching instruments done. Instruments count = %d', len(instrumentsList))96Instruments.instrumentsList = instrumentsList # assign the list to static variable97return instrumentsList9899@staticmethod100def getInstrumentDataBySymbol(tradingSymbol):101return Instruments.symbolToInstrumentMap[tradingSymbol]102103@staticmethod104def getInstrumentDataByToken(instrumentToken):105return Instruments.tokenToInstrumentMap[instrumentToken]106107108