Ejemplo n.º 1
0
Archivo: utils.py Proyecto: ynzheng/uxs
def resolve_ohlcv_times(timeframe='1m', since=None, limit=None, shift=1, as_pydt=False):
    """
    :type since: int, datetime.datetime
    :param shift:
        Used if only `limit` is given
        `1` rounds to the end of tf unit ('1m'->to the end of current minute) [default]
        `0` rounds to its start
    :param as_pydt: if `True` the returned types is datetime.datetime
    
    :returns: [since, end) range in millistamps
    """
    tf_millisecs = parse_timeframe(timeframe, 'ms')
    end = None
    if since is None:
        if limit is not None:
            tf_unit_seconds = ccxt.Exchange.parse_timeframe('1'+timeframe[-1])
            end = timestamp_ms(dt_round(dt.utcnow(), tf_unit_seconds, shift=shift))
            since = int(end - limit*tf_millisecs)
    elif limit is not None:
        if not isinstance(since, (int, float)):
            since = timestamp_ms(since)
        end = int(since + limit*tf_millisecs)
    
    if as_pydt:
        if since is not None and isinstance(since, (int,float)):
            since = pydt_from_ms(since)
        if end is not None and isinstance(end, (int,float)):
            end = pydt_from_ms(end)
    
    return since, end
Ejemplo n.º 2
0
 def on_order(self, rr):
     tlogger.debug(rr)
     #rr = r['result']
     id = rr['clientOrderId']
     status = rr['status']
     rtype = rr['reportType']
     o = None
     try: o = self.orders[id]
     except KeyError: pass
     symbol = self.convert_symbol(rr['symbol'],0)
     side = rr['side']
     amount = float(rr['quantity'])
     filled = float(rr['cumQuantity'])
     remaining = amount-filled if status not in ('canceled','filled','suspended','expired') else 0
     if o is None:
         #(status == "new")
         #"2017-10-20T12:29:43.166Z"
         dto = parsedate(rr['createdAt']).replace(tzinfo=None)
         ts = timestamp_ms(dto)
         price = float(rr['price'])
         self.add_order(id=id, symbol=symbol, side=side, price=price, amount=amount, timestamp=ts,
                        remaining=remaining, filled=filled, params={'info': rr})
     else:
         # Can the server send "canceled"/replaced message twice, in response
         # to both cancelOrder/cancelReplaceOrder and subscribeReports?
         # Worse yet, the "expired" may arrive sooner than update,
         # thus have to check that remaining is smaller than previous, and filled larger
         remaining = min(remaining, o['remaining'])
         filled = max(filled, o['filled'])
         if status in ('canceled','filled','suspended','expired'):
             self.update_order(id, 0, filled, params={'info': rr})
             #self.log_error('received unregistered order {}'.format(id))
         elif status in ('partiallyFilled','new'):
             self.update_order(id, remaining, filled, params={'info': rr})
         else:
             #order 
             self.log_error('received unknown order status. r: {}'.format(rr))
     
     if rtype == 'trade':
         tid = rr['tradeId']
         tprice = float(rr['tradePrice'])
         tamount = float(rr['tradeQuantity'])
         tdto = parsedate(rr['updatedAt']).replace(tzinfo=None)
         tts = timestamp_ms(tdto)
         #fee is negative when we are paid the rebate
         #NB! fee is always in payout currency
         fee = float(rr['tradeFee'])
         self.add_fill(id=tid, symbol=symbol, side=side, price=tprice, amount=tamount,
                       timestamp=tts, order=id, fee=fee, params={'info': rr.copy()})
Ejemplo n.º 3
0
 def on_fill(self, item):
     #["t", 12345, "0.03000000", "0.50000000", "0.00250000", 0, 6083059, "0.00000375", "2018-09-08 05:54:09"]
     #['t', 9394539, '0.00057427', '0.00000476', '0.00000000', 0, 274547887461]
     #["t", <trade ID>, "<rate>", "<amount>", "<fee multiplier>", <funding type>, <order number>, <total fee>, <date>, "<clientOrderId>", "<trade total>"]
     #funding_type: 0 (exchange wallet), 1 (borrowed funds), 2 (margin funds), or 3 (lending funds).
     _, tid, price, amount, fee_rate, funding_type, oid = item[:7]
     tid, oid = str(tid), str(oid)
     price = float(price)
     amount = float(amount)
     fee_rate = float(fee_rate)
     total_fee = float(item[7]) if len(item) > 7 else None
     dto = parsedate(item[8]) if len(item) > 8 else dt.utcnow()
     if dto.tzinfo is not None:
         logger2.error(
             'POLONIEX HAS CHANGED THEIR DATE FORMAT: {}, {}'.format(
                 item[8], dto))
     ts = timestamp_ms(dto.replace(tzinfo=None))
     self.add_fill(id=tid,
                   symbol=None,
                   side=None,
                   price=price,
                   amount=amount,
                   fee_rate=fee_rate,
                   timestamp=ts,
                   order=oid)
Ejemplo n.º 4
0
 def on_new_order(self, item):
     #["n", 148, 6083059, 1, "0.03000000", "2.00000000", "2018-09-08 04:54:09", "2.00000000", None]
     #["n", <currency pair id>, <order number>, <order type>, "<price>", "<amount>", "<date>", "<original amount ordered>" "<clientOrderId>"]
     _, pair_id, oid, otype, price, remaining, tstr, amount, clientOrderId = item[:
                                                                                  9]
     #Convert to string because api.create_order returns id as string
     oid = str(oid)
     symbol = self.id_to_symbol(pair_id)
     side = 'buy' if otype == 1 else 'sell'
     price = float(price)
     amount = float(amount)
     dto = parsedate(tstr)
     if dto.tzinfo is not None:
         logger2.error(
             'POLONIEX HAS CHANGED THEIR DATE FORMAT: {}, {}'.format(
                 tstr, dto))
     ts = timestamp_ms(dto.replace(tzinfo=None))
     remaining = float(remaining)
     #print('on_order:',oid,symbol,side,price,amount,ts,remaining,filled,payout)
     try:
         self.orders[oid]
     except KeyError:
         #set filled to 0 because filled (and payout) is updated by trades
         self.add_order(id=oid,
                        symbol=symbol,
                        side=side,
                        price=price,
                        amount=amount,
                        timestamp=ts,
                        remaining=remaining,
                        filled=0)
     else:
         self.update_order(id=oid, remaining=remaining)
Ejemplo n.º 5
0
    def on_ticker(self, r):
        #first response:
        #[<id>, 1]
        #following responses:
        #[<id>, null, [
        # <currency pair id>, "<last trade price>", "<lowest ask>", "<highest bid>", "<percent change in last 24 hours>",
        # "<base currency volume in last 24 hours>", "<quote currency volume in last 24 hours>", <is frozen>,
        #"<highest trade price in last 24 hours>", "<lowest trade price in last 24 hours>" ], ... ]
        data = []
        now = dt.utcnow()
        now_str = '{}Z'.format(now.isoformat()[:23])
        now_ms = timestamp_ms(now)

        for pair_data in r[2:]:
            pair_id = pair_data[0]
            symbol = self.id_to_symbol(pair_id)
            last_trade_price, lowest_ask, highest_bid = [
                float(x) for x in pair_data[1:4]
            ]
            percent_change_24, base_cy_vol_24, quote_cy_vol_24 = [
                float(x) for x in pair_data[4:7]
            ]
            is_frozen = pair_data[7]
            H_24, L_24 = [float(x) for x in pair_data[8:]]
            change = last_trade_price * (percent_change_24 / 100)
            vwap = quote_cy_vol_24 / base_cy_vol_24 if base_cy_vol_24 else last_trade_price

            data.append({
                'symbol': symbol,
                'timestamp': now_ms,
                'datetime': now_str,
                'last': last_trade_price,
                'high': H_24,
                'low': L_24,
                'open': None,
                'close': None,
                'bid': highest_bid,
                'bidVolume': None,
                'ask': lowest_ask,
                'askVolume': None,
                'baseVolume': base_cy_vol_24,
                'quoteVolume': quote_cy_vol_24,
                'previousClose': None,
                'change': change,
                'percentage': percent_change_24,
                'average': None,
                'vwap': vwap,
                'active': not is_frozen
            })

        self.update_tickers(data)
        self.change_subscription_state({'_': 'all_tickers'}, 1)
Ejemplo n.º 6
0
def test_calc_log_y():
    assert lL.calc_y(timestamp_ms(dt(2000, 1, 1, 2)), precision=6) == 1000
Ejemplo n.º 7
0
def test_trendline_calc_y():
    assert L.calc_y(timestamp_ms(dt(2000, 1, 1, 12))) == 1120
Ejemplo n.º 8
0
 def __init__(self, x, y):
     """timetamp is in milliseconds"""
     if isinstance(x, dt):
         x = timestamp_ms(x)
     super().__init__(int(x), y)
     self.datetime = ccxt.Exchange.iso8601(self.x)
Ejemplo n.º 9
0
Archivo: poll.py Proyecto: ynzheng/uxs
def encode_filename(exchange, type, date):
    type_str = _type_str(type)
    return '[{}]_{}_{}'.format(exchange.lower(), type_str, timestamp_ms(date))