def getQuote(tradingSymbol, isFnO=False):
     broker = Controller.getBrokerName()
     brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
     quote = None
     if broker == "zerodha":
         key = ('NFO:' +
                tradingSymbol) if isFnO == True else ('NSE:' +
                                                      tradingSymbol)
         bQuoteResp = brokerHandle.quote(key)
         bQuote = bQuoteResp[key]
         # convert broker quote to our system quote
         quote = Quote(tradingSymbol)
         quote.tradingSymbol = tradingSymbol
         quote.lastTradedPrice = bQuote['last_price']
         quote.lastTradedQuantity = bQuote['last_quantity']
         quote.avgTradedPrice = bQuote['average_price']
         quote.volume = bQuote['volume']
         quote.totalBuyQuantity = bQuote['buy_quantity']
         quote.totalSellQuantity = bQuote['sell_quantity']
         ohlc = bQuote['ohlc']
         quote.open = ohlc['open']
         quote.high = ohlc['high']
         quote.low = ohlc['low']
         quote.close = ohlc['close']
         quote.change = bQuote['net_change']
         quote.oiDayHigh = bQuote['oi_day_high']
         quote.oiDayLow = bQuote['oi_day_low']
         quote.lowerCiruitLimit = bQuote['lower_circuit_limit']
         quote.upperCircuitLimit = bQuote['upper_circuit_limit']
     else:
         # The logic may be different for other brokers
         quote = None
     return quote
 def getOrderManager():
   orderManager = None
   brokerName = Controller.getBrokerName()
   if brokerName == "zerodha":
     orderManager = ZerodhaOrderManager()
   #elif brokerName == "fyers": # Not implemented
   return orderManager
Exemple #3
0
 def getStrikePrice(tradingSymbol):
     broker = Controller.getBrokerName()
     brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
     quote = None
     if broker == "zerodha":
         key = 'NSE:' + tradingSymbol
         bQuoteResp = brokerHandle.quote(key)
         quote = bQuoteResp[key]
         if quote:
             return quote['last_price']
         else:
             return 0
     else:
         # The logic may be different for other brokers
         quote = None
     return quote
Exemple #4
0
	def start():
		pygame.init()		
		window = Window(title = "Main Display")

		controller = Controller(window)

		clock = pygame.time.Clock()

		while not GameCycle.gameEnd():

			
			controller.prepareNextStep()
			window.update()

			clock.tick(60)

		pygame.quit()
  def run():
    if Utils.isTodayHoliday():
      logging.info("Cannot start TradeManager as Today is Trading Holiday.")
      return

    if Utils.isMarketClosedForTheDay():
      logging.info("Cannot start TradeManager as Market is closed for the day.")
      return

    Utils.waitTillMarketOpens("TradeManager")

    # check and create trades directory for today`s date
    serverConfig = getServerConfig()
    tradesDir = os.path.join(serverConfig['deployDir'], 'trades')
    TradeManager.intradayTradesDir =  os.path.join(tradesDir, Utils.getTodayDateStr())
    if os.path.exists(TradeManager.intradayTradesDir) == False:
      logging.info('TradeManager: Intraday Trades Directory %s does not exist. Hence going to create.', TradeManager.intradayTradesDir)
      os.mkdirs(TradeManager.intradayTradesDir)

    # start ticker service
    brokerName = Controller.getBrokerName()
    if brokerName == "zerodha":
      TradeManager.ticker = ZerodhaTicker()
    #elif brokerName == "fyers" # not implemented
    # ticker = FyersTicker()

    TradeManager.ticker.startTicker()
    TradeManager.ticker.registerListener(TradeManager.tickerListener)

    # sleep for 2 seconds for ticker connection establishment
    time.sleep(2)

    # Load all trades from json files to app memory
    TradeManager.loadAllTradesFromFile()

    # track and update trades in a loop
    while True:
      if Utils.isMarketClosedForTheDay():
        logging.info('TradeManager: Stopping TradeManager as market closed.')
        break

      try:
        # Fetch all order details from broker and update orders in each trade
        TradeManager.fetchAndUpdateAllTradeOrders()
        # track each trade and take necessary action
        TradeManager.trackAndUpdateAllTrades()
      except Exception as e:
        logging.exception("Exception in TradeManager Main thread")

      # save updated data to json file
      TradeManager.saveAllTradesToFile()
      
      # sleep for 30 seconds and then continue
      time.sleep(30)
      logging.info('TradeManager: Main thread woke up..')
Exemple #6
0
 def getCMP(tradingSymbol):
     brokerLogin = Controller.getBrokerLogin()
     brokerHandle = brokerLogin.getBrokerHandle()
     quote = None
     if brokerLogin.broker == "zerodha":
         quote = brokerHandle.quote(tradingSymbol)
         if quote:
             return quote[tradingSymbol]['last_price']
         else:
             return 0
     else:
         # The logic may be different for other brokers
         return 0
Exemple #7
0
 def fetchInstrumentsFromServer():
     instrumentsList = []
     try:
         brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
         logging.info('Going to fetch instruments from server...')
         instrumentsList = brokerHandle.instruments('NSE')
         instrumentsListFnO = brokerHandle.instruments('NFO')
         # Add FnO instrument list to the main list
         instrumentsList.extend(instrumentsListFnO)
         logging.info('Fetched %d instruments from server.',
                      len(instrumentsList))
     except Exception as e:
         logging.exception(
             "Exception while fetching instruments from server")
     return instrumentsList
    def fetchInstruments():
        brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
        if Instruments.instrumentsList:
            return Instruments.instrumentsList

        logging.info('Going to fetch instruments...')
        instrumentsList = brokerHandle.instruments('NSE')
        Instruments.symbolToInstrumentMap = {}
        Instruments.tokenToInstrumentMap = {}
        for isd in instrumentsList:
            tradingSymbol = isd['tradingsymbol']
            instrumentToken = isd['instrument_token']
            # logging.info('%s = %d', tradingSymbol, instrumentToken)
            Instruments.symbolToInstrumentMap[tradingSymbol] = isd
            Instruments.tokenToInstrumentMap[instrumentToken] = isd

        logging.info('Fetching instruments done. Instruments count = %d',
                     len(instrumentsList))
        Instruments.instrumentsList = instrumentsList  # assign the list to static variable
        return instrumentsList
    def run():
        if Utils.isTodayHoliday():
            logging.info(
                "Cannot start TradeManager as Today is Trading Holiday.")
            return

        if Utils.isMarketClosedForTheDay():
            logging.info(
                "Cannot start TradeManager as Market is closed for the day.")
            return

        Utils.waitTillMarketOpens("TradeManager")

        # start ticker service
        brokerName = Controller.getBrokerName()
        if brokerName == "zerodha":
            TradeManager.ticker = ZerodhaTicker()
        #elif brokerName == "fyers" # not implemented
        # ticker = FyersTicker()

        TradeManager.ticker.startTicker()
        TradeManager.ticker.registerListener(TradeManager.tickerListener)

        # track and update trades in a loop
        while True:
            if Utils.isMarketClosedForTheDay():
                logging.info(
                    'TradeManager: Stopping TradeManager as market closed.')
                break

            # Fetch all order details from broker and update orders in each trade
            TradeManager.fetchAndUpdateAllTradeOrders()

            # track each trade and take necessary action
            TradeManager.trackAndUpdateAllTrades()

            time.sleep(60 * 1000)  # sleep for 60 seconds
Exemple #10
0
 def get(self):
     brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
     positions = brokerHandle.positions()
     logging.info('User positions => %s', positions)
     return json.dumps(positions)
Exemple #11
0
#!/usr/bin/python -B
# -*- coding: UTF-8 -*-
from core.Controller import Controller
from core.Exceptions import InitializationException, ClosingException, GuiException

import wx
from gui.MainGui import MainGui

__author__ = "kitru"


if __name__ == "__main__":
    app = wx.App(False)
    controller = Controller()
    MainGui(None, "AstroLab", controller)
    controller.initialization()
    app.MainLoop()
    controller.freeResources()
Exemple #12
0
 def __init__(self, broker):
     self.broker = broker
     self.brokerLogin = Controller.getBrokerLogin()
     self.ticker = None
     self.tickListeners = []
import subprocess
import sys


## A helper function for installing modules for this program if they are not existing.
#
#  \param packageName Name of the package that shall be installed.
def maybeInstall(packageName):
    if importlib.util.find_spec(packageName) is None:
        subprocess.check_call(
            [sys.executable, "-m", "pip", "install", packageName])


if __name__ == "__main__":
    # Update pip.
    #subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade",  "pip"])
    # For file exchange with Git

    from PyQt5.QtWidgets import *
    from PyQt5 import QtCore
    app = QApplication(sys.argv)
    app.setApplicationVersion("1.0.0")

    from gui.MainWindow import MainWindow
    from core.Controller import Controller
    controller = Controller()
    window = MainWindow(controller)
    window.show()
    sys.exit(app.exec_())
 def get(self):
     brokerHandle = Controller.getBrokerLogin().getBrokerHandle()
     holdings = brokerHandle.holdings()
     logging.info('User holdings => %s', holdings)
     return json.dumps(holdings)
 def get(self):
     redirectUrl = Controller.handleBrokerLogin(request.args)
     return redirect(redirectUrl, code=302)
 def __init__(self, broker):
     self.broker = broker
     self.brokerHandle = Controller.getBrokerLogin().getBrokerHandle()