Example #1
0
    def Stop(self):

        mes = toMessage("stop5sec", None)
        self.gui.toWat.put(mes)
        for items in self.activeStocks:
            toTWS = toMessage('Stop5SecWatch', items)
            self.gui.toTws.put(toTWS)
Example #2
0
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        """ Marks the ending of the historical bars reception. """
        #msg=toMessage('DownloadFinish')
        #self.toGui.put(msg)

        EWrapper.historicalDataEnd(self, reqId, start, end)

        #translate back
        #print("translate back",reqId,self.nextIDconID[reqId])
        conID=self.nextIDconID[reqId]
        #print('reqId after transalation ',conID)

        if self.downloadHistInfo[conID].whatToDownload=='histnew5secOneTime':
            msg = toMessage('5secHist')
            #we must send the reaId besides the list
            msg.obj =[conID,self.downloadHistInfo[conID]]
            self.toWat.put(msg) # we send to watch,

            print('histnew5secOneTime - finished',conID)

            #must clear the downloadHistInfo
            self.downloadHistInfo.pop(conID)
            ## maybe we should send some message to gui too to inform the user that we are ready

            return

        ret=self.dbLite.addOneStock(self.downloadHistInfo[conID])

        start = self.downloadHistInfo[conID].oneStock.bars1min[0].date

        del self.downloadHistInfo[conID].oneStock.bars1min[:]

        if ret=='stop': #we don't need to download anymore in case of a newhist

            if self.downloadHistInfo[conID].whatToDownload=='histnewLevel1':
                msg=toMessage('histnewLevel1End')
                msg.obj=conID
                self.toGui.put(msg) #let's anounce that we can go to level 2
                #print('hist new Level1 end')
            self.downloadHistInfo.pop(conID)  # removed from dictionary - no sens to stay there
            print('finish new download')
            return

        #delete all the bars
        self.downloadHistInfo[conID].count += 1

        if self.downloadHistInfo[conID].count>=10 and self.downloadHistInfo[conID].whatToDownload=='histold':
            #we already download 60 for history so do not send anymore messages

            self.downloadHistInfo.pop(conID)
            return

        self.downloadHistInfo[conID].dateToDownload = start
        msg=toMessage('HistFinish')
        msg.obj=self.downloadHistInfo[conID]
        self.toGui.put(msg)
        return
Example #3
0
    def Start(self):
        disLog(
            getframeinfo(currentframe()).filename + ":" +
            sys._getframe().f_code.co_name + ":" +
            str(getframeinfo(currentframe()).lineno), "start in watch")

        if self.activeStocks == None:
            self.activeStocks = self.gui.dbLite.getActive()
        #let's verify if the 1 min data is update in the last 60 minute otherwise don't start the watch

        mes = toMessage("CreatePorfolio", self.activeStocks)
        self.gui.toWat.put(mes)

        for item in self.activeStocks:
            dt = self.gui.dbLite.getMaxDateTime(item.contractID)

            FMT1 = '%Y%m%d  %H:%M:%S'
            s1 = datetime.strftime(datetime.now(), FMT1)

            tdelta = datetime.strptime(s1, FMT1) - datetime.strptime(dt, FMT1)

            #we need to have download 1 minute less than 1 hours 3600 seconds
            #we set to 3400 because the download of 5 seconds can take some time
            if tdelta.seconds > 3000:
                print(
                    "you don't have enough data on 1 minute, please download 1 minute first"
                )
                return
            else:
                print('start sending to load 1 min', item.contractID)
                #toGui = toMessage('load1min', item.contractID)
                #self.gui.toGui.put(toGui)

                self.gui.load1min(item.contractID)
                time.sleep(1)

        time.sleep(3)
        print('I finish to upload 1 min')

        #        mes = toMessage("start5sec", self.activeStocks)
        #        self.gui.toWat.put(mes)

        #print(len(self.activeStocks),self.activeStocks[0].symbol)

        for item in self.activeStocks:
            toTWS = toMessage('Start5SecWatch', item)
            self.gui.toTws.put(toTWS)
            #break

        time.sleep(5)  #we need time to be able to have continuous series

        for item in self.activeStocks:
            toTWS = toMessage('histnew5secOneTime', item)
            self.gui.toTws.put(toTWS)
Example #4
0
    def realtimeBar(self, reqId: TickerId, time:int, open_: float, high: float, low: float, close: float,
                             volume: int, wap: float, count: int):
             super().realtimeBar(reqId, time, open_, high, low, close, volume, wap, count)
             #print("TickerId:", reqId, "time:",datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"), "Open: ", open_, "Jigh: ",high,
             #      "Low: ", low, "Close: ", close, "volume: ",volume, "Wap:", wap,"Count: ", count)
             #onetick=OneTickWithInfo(reqId,OneTick(time, open_, high, low, close, volume, wap,count))

             #we need to put two spaces between date and time to be consistent with historical data format
             #onetick = OneTickWithInfo(reqId, OneTick(datetime.datetime.fromtimestamp(time).strftime("%Y%m%d  %H:%M:%S"), open_, high, low, close, volume, wap, count))

             # translate back
             #print("translate back", reqId, self.nextIDconID[reqId])
             conID = self.nextIDconID[reqId]
             #print('reqId after transalation ', conID)

             oneBar=BarData()
             oneBar.date=datetime.datetime.fromtimestamp(time).strftime("%Y%m%d  %H:%M:%S")
             oneBar.open=open_
             oneBar.high=high
             oneBar.low=low
             oneBar.close=close
             oneBar.volume=volume
             oneBar.average=wap
             oneBar.barCount=count
             msg=toMessage('5sec')
             #msg.obj=onetick
             msg.obj=[conID,oneBar]
             self.toWat.put(msg)
Example #5
0
 def exit(self):
     msg=toMessage('exit')
     self.toGui.put(msg)
     """
     Exit from the application
     """
     self.done = True
     self._onStop()
Example #6
0
    def Activate(self):
        self.timeframe = self.eTimeFrame.get().split(",")

        if self.gui.dbLite == None:
            print("load the database")
            return

        mes = toMessage("timeframe", self.timeframe)
        self.gui.toWat.put(mes)

        if self.activeStocks == None:
            self.activeStocks = self.gui.dbLite.getActive()

        mes = toMessage("CreatePorfolio", self.activeStocks)
        self.gui.toWat.put(mes)

        self.GridPanel = tk.PanedWindow(self.gui.tab_watch,
                                        height="500",
                                        width="700",
                                        bg='blue')
        self.GridPanel.place(x=10, y=50)
        maxrow = 30
        maxcol = 1
        self.activeStocks = self.gui.dbLite.getActive()
        OnePanel.master = self.GridPanel
        OnePanel.height = 20
        OnePanel.width = 300

        row = 1
        col = 1
        for item in self.activeStocks:
            pn = OnePanel(row, col, self.gui, self.timeframe)
            row += 1
            if row > maxrow:
                col += 1
                row = 1

            if row > maxrow and col > maxcol:
                print("too many items")
                break

            pn.create(item)
            #print('item.contractID in activate',item.contractID)
            self.Panels[item.contractID] = pn
Example #7
0
    def load1min(self, item):
        if self.dbLite == None:
            print('Database is not loaded - load1min')
            return

        if isinstance(item, int) == True:
            item = self.dbLite.getItem(item)
            print('item is integer', item)
        else:
            print('item is item')

        #let's verify if we really need data
        dt = self.dbLite.getMaxDateTime(item.contractID)
        print('load1min in gui', dt)
        FMT1 = '%Y%m%d  %H:%M:%S'
        s1 = datetime.datetime.strftime(datetime.datetime.now(), FMT1)

        tdelta = datetime.datetime.strptime(
            s1, FMT1) - datetime.datetime.strptime(dt, FMT1)
        if tdelta.seconds > 3000:
            print('load1min', 'we need to take the 1 minute data in level1')
            toTWS = toMessage('histnewLevel1', item)
            self.toTws.put(toTWS)
        else:
            print('load1min', 'we have the data load and go level2')
            #let's download only 3000 bars

            #oneMin:OneStock=self.dbLite.getOneStock2(item.contractID,3000)
            #panda1min=self.dbLite.getOneStockPandas(item.contractID,3000)
            if item.sectype == 'FUT':
                RTH = 'NO'
            else:
                RTH = 'YES'
            print('security type', item.sectype)
            dic1min = self.dbLite.getOneStockDic(item.contractID, 3000, RTH)

            #mes=toMessage('data1min',[item.contractID,oneMin,panda1min])
            mes = toMessage('data1min', [item.contractID, dic1min])
            self.toWat.put(mes)

            time.sleep(1)  # not sure if necessary
            self.watch.Panels[item.contractID].panelQue.put(
                toMessage('level2'))
Example #8
0
    def error(self, reqId: TickerId, errorCode: int, errorString: str):
        """This event is called when there is an error with the
        communication or when TWS wants to send a message to the client."""
        EWrapper.error(self, reqId, errorCode, errorString)

        #self.tws2gui.put(f'ERROR {errorCode}: {errorString}')
        # Error messages with codes (2104, 2106, 2107, 2108) are not real errors but information messages
        if errorCode not in (2104, 2106, 2107, 2108,2158):
            msg=toMessage('ERROR')
            msg.obj=str(errorCode)+':'+str(errorString)
            #self.toGui.put(f'ERROR {errorCode}: {errorString}')
            self.toGui.put(msg)
Example #9
0
    def tickByTickBidAsk(self, reqId: int, time: int, bidPrice: float, askPrice: float,
                         bidSize: int, askSize: int, tickAttribBidAsk: TickAttribBidAsk):
        #EWrapper.tickByTickBidAsk(reqId, time, bidPrice, askPrice,bidSize, askSize, tickAttribBidAsk)
        super().tickByTickBidAsk(reqId, time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk)
        #print("tickByTickBidAsk ReqId:", reqId, "Time:", datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"), "askPrice:",
        #          askPrice, "askSize:", askSize, "bidPrice:", bidPrice, "bidSize:", bidSize,"tickAttribBidAsk:",tickAttribBidAsk )
        self.realTickData[self.nextIDconID[reqId]].append([datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),bidPrice,askPrice])

        return
        msg = toMessage('tickbytick')
        # msg.obj=onetick
        msg.obj = [self.nextIDconID[reqId],datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),askPrice,bidPrice ]
        self.toWat.put(msg)
Example #10
0
    def ex(self):
        print('exit now')
        self.watch.StopPanelEngines()
        mes = toMessage("exit", None)
        #self.watch.myQueue.queue.clear()
        #self.watch.myQueue.clear()
        self.dlQueToLimit.put(mes)
        time.sleep(1)

        self.toTws.put(mes)
        self.toWat.put(mes)
        self.exit = True
        #time.sleep(1)
        self.root.destroy()
Example #11
0
 def loaddb(self):
     dbname = self.eLoadDB.get()
     self.dbLite = DB(dbname)
     #self.dbLite.connect()
     rows = self.dbLite.populateContract()
     for row in rows:
         # print(row[0])
         self.contract.treeContracts.insert("",
                                            "end",
                                            row[0],
                                            text="",
                                            values=row)
     toTWS = toMessage('database', dbname)
     self.toTws.put(toTWS)
Example #12
0
 def marketdata(self):
     item = self.treeContracts.selection()
     if not item:
         print("nothing selected")
     else:
         id = self.treeContracts.item(item)['values'][0]
         ct = OneContract(self.eCurrency.get(), self.eSymbol.get(),
                          self.eExpire.get(), self.cbExchange.get(),
                          self.cbSecType.get(), self.cbBarSize.get(),
                          self.cbWhatToShow.get(), self.cbActive.get(), id)
         #mrkdt=toTWSMarketData(ct)
         #toTWS = self.gui.toTws('marketdata',id)
         toTWS = toMessage('marketdata', id)
         # print(self.dbLite.getDateTimeToDownload())
         self.gui.toTws.put(toTWS)
Example #13
0
 def stopWatch(self):
     item = self.treeContracts.selection()
     if not item:
         print("nothing selected")
     else:
         conID = self.treeContracts.item(item)['values'][0]
         ct = OneContract(self.eCurrency.get(), self.eSymbol.get(),
                          self.eExpire.get(), self.cbExchange.get(),
                          self.cbSecType.get(), self.cbBarSize.get(),
                          self.cbWhatToShow.get(), self.cbActive.get(),
                          self.eOrderSize.get(), self.eStopSize.get(),
                          self.eOrderExtra.get(), conID)
         #toTWS = self.gui.toTws('stopStart', ct)
         toTWS = toMessage('watchStop', ct)
         # print(self.dbLite.getDateTimeToDownload())
         self.gui.toTws.put(toTWS)
Example #14
0
    def doOrder(self, action, instrument: OneStock):
        contract = Contract()
        contract.symbol = instrument.contract.symbol
        contract.secType = instrument.contract.sectype
        contract.currency = instrument.contract.currency
        contract.exchange = instrument.contract.exchange
        contract.lastTradeDateOrContractMonth = instrument.contract.expire

        #print(contract.symbol, contract.secType, contract.currency, contract.exchange,
        #      contract.lastTradeDateOrContractMonth)

        order = Order()
        #order.action = "BUY"
        order.action = action
        # order.orderType = "LMT"
        order.orderType = "MKT"
        #order.totalQuantity = 1
        ordersize = int(instrument.contract.ordersize)

        if instrument.order['Position'] == 0:
            order.totalQuantity = ordersize
            if action == 'BUY':
                instrument.order['Position'] = ordersize
            else:
                instrument.order['Position'] = -ordersize
        elif instrument.order['Position'] == ordersize and action == 'SELL':
            order.totalQuantity = ordersize * 2
            instrument.order['Position'] = -ordersize
        elif instrument.order['Position'] == -ordersize and action == 'BUY':
            order.totalQuantity = ordersize * 2
            instrument.order['Position'] = ordersize
        else:
            return  #nothing to do
        # order.lmtPrice = 100
        # order.account="U146642"

        print("action=", action, "size=", order.totalQuantity, ordersize,
              "symbol=", contract.symbol, 'Position=',
              instrument.order['Position'])
        toTWS = toMessage('PlaceOrder', ['Nothing', contract, order])
        # print(self.dbLite.getDateTimeToDownload())
        self.toTws.put(toTWS)
Example #15
0
    def placeOrder(self):
        print("this place order")
        item = self.treeContracts.selection()
        if not item:
            print("nothing selected")
        else:
            val = (item[0], self.eCurrency.get(), self.eSymbol.get(),
                   self.eExpire.get(), self.cbExchange.get(),
                   self.cbSecType.get(), self.cbBarSize.get(),
                   self.cbWhatToShow.get(), self.cbActive.get(),
                   self.eOrderSize.get(), self.eStopSize.get(),
                   self.eOrderExtra.get())
            print(val)
            contract = Contract()
            contract.symbol = self.eSymbol.get()
            contract.secType = self.cbSecType.get()
            contract.currency = self.eCurrency.get()
            contract.exchange = self.cbExchange.get()
            contract.lastTradeDateOrContractMonth = self.eExpire.get()
            print(contract.symbol, contract.secType, contract.currency,
                  contract.exchange, contract.lastTradeDateOrContractMonth)

            order = Order()
            order.action = "BUY"
            #order.orderType = "LMT"
            order.orderType = "MKT"
            order.totalQuantity = 1
            #order.lmtPrice = 100
            #order.account="U146642"

            print(int(item[0]))

            toTWS = toMessage('PlaceOrder', [int(item[0]), contract, order])
            # print(self.dbLite.getDateTimeToDownload())
            self.gui.toTws.put(toTWS)

        return
Example #16
0
 def cancelmarketdata(self):
     #toTWS = self.gui.toTws('cancelmarketdata')
     toTWS = toMessage('cancelmarketdata')
     self.gui.toMessage.put(toTWS)
Example #17
0
 def StopPanelEngines(self):
     for key, value in self.Panels.items():
         print(key, value.x, value.y)
         msg = toMessage('exit')
         value.panelQue.put(msg)
Example #18
0
 def Start1min(self):
     self.activeStocks = self.gui.dbLite.getActive()
     for item in self.activeStocks:
         toTWS = toMessage('histnew', item)
         self.gui.toTws.put(toTWS)
Example #19
0
    def updateOneStock(self, tickID, item: BarData):
        '''
        dt=self.oneportfolio.stocks[tickID].bars1min[len(self.oneportfolio.stocks[tickID].bars1min) - 1].date
        dt_obj=datetime.strptime(dt, '%Y%m%d  %H:%M:%S')
        dt_obj+=timedelta(seconds=60)
        dt=dt_obj.strftime("%Y%m%d  %H:%M:%S")
        '''

        #print('updateOneStock- is 1minUpToDate?',self.oneportfolio.stocks[tickID].is1minUpToDate)
        d = self.oneportfolio.stocks[tickID].data
        symbol = self.oneportfolio.stocks[tickID].contract.symbol
        #print('symbol=', symbol)
        if (self.oneportfolio.stocks[tickID].is1minUpToDate == False):
            #res=convertToHigherBarData(self.oneportfolio.stocks[tickID].bars5sec,'1min')
            #convert from 5sec to 1 min
            print('is1minUpToDate is false')
            convertToHigherBarDataDic(d, '5sec', '1min')
            for item in self.timeframe:
                if item not in ['1min', 'info', 'info2']:
                    #print('item in update one stock',item)
                    convertToHigherBarDataDic(d, '1min', item)

            self.oneportfolio.stocks[tickID].is1minUpToDate = True

            #let's find the open on one minute
            find = False
            i = -1
            while find == False:
                if d['D1min'][i][
                        10:] == '06:30:00':  # we can find the end of previous day but ZS is not ending at 13:00
                    #print('find open ',d['D1min'][i][10:],d['O1min'][i])
                    d['Open'] = float(d['C1min'][i])
                    find = True
                i -= 1

            #lets do WT
            start = time.time()
            end = time.time()

            #next time we don't want to repopulate everything

        else:
            #print('do 5 sec',item)
            self.add_one_bar_to_dict(item, d, "1min")
            calculateWT2(self.oneportfolio.stocks[tickID].data, "1min")
            for key in self.timeframe:
                if key not in ['1min', 'info', 'info2']:
                    #print('i add one item to dictionary', key)
                    self.add_one_bar_to_dict(item, d, key)
                    calculateWT2(d, key)
            '''
            self.add_one_bar_to_dict(item,d,1)
            self.add_one_bar_to_dict(item, d, 5)
            self.add_one_bar_to_dict(item, d, 30)
            calculateWT2(self.oneportfolio.stocks[tickID].data, "1min")
            calculateWT2(self.oneportfolio.stocks[tickID].data, "5min")
            calculateWT2(self.oneportfolio.stocks[tickID].data, "30min")
            '''

            today_change = float(item.close) - d['Open']
            diclabel = {}
            #print('position ',self.oneportfolio.stocks[tickID].order['Position'])
            for key in self.timeframe:
                if key == 'info':
                    diclabel[key] = [
                        str(item.close) + " " + item.date[15:], 'white'
                    ]
                elif key == 'info2':
                    diclabel[key] = [
                        "{:+.2f}".format(today_change),
                        "green" if today_change > 0 else "red"
                    ]
                else:
                    str2 = str(d['WT2val' + key][0]) + " " + "{:.2f}".format(
                        abs(d['WT2val' + key][1] - d['WT2val' + key][2]))

                    if key == self.oneportfolio.stocks[
                            tickID].contract.orderextra:
                        #print("key ",key)
                        if d['WT2val' + key][0] == 1 and d['WT2col' +
                                                           key] == 'lime':
                            self.doOrder("BUY",
                                         self.oneportfolio.stocks[tickID])
                            print('buy')

                        elif d['WT2val' + key][0] == 1 and d['WT2col' +
                                                             key] == 'pink':
                            print('sell')
                            self.doOrder("SELL",
                                         self.oneportfolio.stocks[tickID])
                    '''
                    if key in ["1min","5min","10min"]:
                         if d['WT2val' + key][0]==1 and d['WT2col'+key]=='lime':
                            if d['position'+key]==-100:
                                str1='buy at '+key+' tickID=' + str(tickID)+' price= '+str(item.close)+' datetime= '+item.date+' position=0'
                                print(str1)
                                self.writetofile(symbol+key,str1)
                                d['position'+key] = 0
                            if d['position'+key]==0:
                                str1='buy at ' + key + ' tickID='+ str(tickID)+ ' price= '+ str(item.close)+ ' datetime= '+ item.date+ ' position=100'
                                print(str1)
                                self.writetofile(symbol+key, str1)
                            d['position'+key] = 100

                        elif  d['WT2val' + key][0] == 1 and d['WT2col' + key] == 'pink':
                            if d['position'+key]==100:
                                str1='sell at '+key+' tickID='+str(tickID)+' price= '+str(item.close)+' datetime= '+item.date+' position=0'
                                print(str1)
                                self.writetofile(symbol+key, str1)
                                d['position'+key] = 0
                            if d['position'+key]==0:
                                str1='sell at ' + key + ' tickID='+ str(tickID)+ ' price= '+ str(item.close)+ ' datetime= '+ item.date+ ' position=-100'
                                print(str1)
                                self.writetofile(symbol+key, str1)
                            d['position'+key] = -100
                    '''

                    diclabel[key] = [str2, d['WT2col' + key]]

            toGui = toMessage('UpdatePanels', [tickID, diclabel])
            '''        
            toGui = toMessage('UpdatePanels', [tickID,\
                    [d['WT2val30min'],d['WT2col30min']],
                    [d['WT2val5min'],d['WT2col5min']],
                    [d['WT2val1min'],d['WT2col1min']],[str(item.close)+" "+item.date[15:],'white'],
                                               ["{:+.2f}".format(today_change),"green" if today_change>0  else "red"]])
            '''
            #20201201 07:24:12
            self.toGui.put(toGui)
Example #20
0
 def disconnect(self):
     to_tws = toMessage("disconnect", None)
     self.toTws.put(to_tws)
     print('i disconect')