Exemplo n.º 1
0
    def getBars(self, instrument, frequency, timezone=None, fromDateTime=None, toDateTime=None):
        instrument = normalize_instrument(instrument)

        sql = "SELECT bar.timestamp, bar.open, bar.high, bar.low, bar.close, bar.volume, bar.adj_close, bar.frequency" \
              " FROM bar JOIN instrument ON (bar.instrument_id = instrument.instrument_id)" \
              " WHERE instrument.name = ? AND bar.frequency = ?"

        args = [instrument, frequency]

        if fromDateTime is not None:
            sql += " AND bar.timestamp >= ?"
            args.append(dt.datetime_to_timestamp(fromDateTime))

        if toDateTime is not None:
            sql += " AND bar.timestamp <= ?"
            args.append(dt.datetime_to_timestamp(toDateTime))

        ret = []
        sql += " ORDER by bar.timestamp ASC"

        cursor = self.__connection.cursor()
        cursor.execute(sql, args)

        for row in cursor:
            dateTime = dt.timestamp_to_datetime(row[0])

            if timezone:
                dateTime = dt.localize(dateTime, timezone)

            ret.append(bar.BasicBar(dateTime, row[1], row[2], row[3], row[4], row[5], row[6], row[7]))

        cursor.close()

        return ret
Exemplo n.º 2
0
    def testTimeStampConversions(self):
        dateTime = datetime.datetime(2000, 1, 1)
        self.assertEqual(
            dt.timestamp_to_datetime(dt.datetime_to_timestamp(dateTime),
                                     False), dateTime)

        dateTime = dt.as_utc(datetime.datetime(2000, 1, 1, 1, 1))
        self.assertEqual(
            dt.timestamp_to_datetime(dt.datetime_to_timestamp(dateTime), True),
            dateTime)
Exemplo n.º 3
0
    def testTimeStampConversionsWithMicroseconds(self):
        dateTime = datetime.datetime(2000, 1, 1, 1, 1, 1, microsecond=10)
        self.assertEqual(
            dt.timestamp_to_datetime(dt.datetime_to_timestamp(dateTime),
                                     False), dateTime)

        dateTime = dt.as_utc(
            datetime.datetime(2000, 1, 1, 1, 1, 1, microsecond=10))
        self.assertEqual(
            dt.timestamp_to_datetime(dt.datetime_to_timestamp(dateTime), True),
            dateTime)
Exemplo n.º 4
0
    def doGetHistory(self):
        while not self.stopped():
            endTimestamp = dt.datetime_to_timestamp(self.__nextBarClose)
            self.__updateNextBarClose()
            dicts = {}

            try:
                for indentifier in self.__identifiers:
                    response = api.getKLineBar(
                        indentifier, endTimestamp - self.__frequency * 2,
                        self.__period, 100)
                    if response is None:
                        raise Exception("getKLineBar return None!")
                    dicts[indentifier] = response
                break
            except BaseException:
                time.sleep(1)
                continue

        while not self.stopped():
            barDict = {}
            for indentifier in self.__identifiers:
                response = dicts[indentifier]
                if len(response) == 0:
                    break
                barDict[indentifier] = liveBar(response.pop(-1),
                                               self.__frequency)

            if len(barDict) == 0:
                break
            bars = bar.Bars(barDict)
            self.__queue.put((GetBarThread.ON_HISTORY_BARS, bars))
Exemplo n.º 5
0
    def onNewValue(self, dateTime, value):
        technical.EventWindow.onNewValue(self, dateTime, value)

        if value is not None:
            timestamp = dt.datetime_to_timestamp(dateTime)

            if len(self.__timestamps):
                assert (timestamp > self.__timestamps[-1])

            self.__timestamps.append(timestamp)
Exemplo n.º 6
0
    def addBar(self, instrument, bar, frequency):
        instrument = normalize_instrument(instrument)
        instrumentId = self.__getOrCreateInstrument(instrument)
        timeStamp = dt.datetime_to_timestamp(bar.getDateTime())

        try:
            sql = "INSERT INTO bar (instrument_id, frequency, timestamp, open, high, low, close, volume, adj_close) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
            params = [instrumentId, frequency, timeStamp, bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(),
                      bar.getVolume(), bar.getAdjClose()]
            self.__connection.execute(sql, params)
        except sqlite3.IntegrityError:
            sql = "UPDATE bar SET open = ?, high = ?, low = ?, close = ?, volume = ?, adj_close = ?" \
                  " WHERE instrument_id = ? AND frequency = ? AND timestamp = ?"
            params = [bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getAdjClose(),
                      instrumentId, frequency, timeStamp]
            self.__connection.execute(sql, params)
Exemplo n.º 7
0
    def __init__(self, dateTime, frequency):
        super(IntraDayRange, self).__init__()

        assert isinstance(frequency, int)
        assert frequency > 1
        assert frequency < bar.Frequency.DAY

        ts = int(dt.datetime_to_timestamp(dateTime))
        slot = int(ts / frequency)
        slotTs = slot * frequency

        self.__begin = dt.timestamp_to_datetime(
            slotTs, not dt.datetime_is_naive(dateTime))

        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)

        self.__end = self.__begin + datetime.timedelta(seconds=frequency)
Exemplo n.º 8
0
    def doCall(self):
        endTimestamp = dt.datetime_to_timestamp(self.__nextBarClose)
        barDict = {}

        for indentifier in self.__identifiers:
            try:
                response = api.getKLineBar(indentifier,
                                           endTimestamp - self.__frequency,
                                           self.__period)
                if response is None:
                    raise Exception("getKLineBar return None!")
                # logger.debug(response)
                barDict[indentifier] = liveBar(response[-1], self.__frequency)
            except BaseException:
                time.sleep(1)
                return False

        if len(barDict):
            bars = bar.Bars(barDict)
            self.__queue.put((GetBarThread.ON_BARS, bars))
            self.__updateNextBarClose()
            return True
        return False
Exemplo n.º 9
0
def utcToLocal(utcDatetime):
    return timestamp_to_DateTimeLocal(dt.datetime_to_timestamp(utcDatetime))
Exemplo n.º 10
0
 def getValueAt(self, dateTime):
     return self.__getValueAtImpl(dt.datetime_to_timestamp(dateTime))