def orderbook(pair='btcusd', limit_orders=50, group=True, limit_bids=None, limit_asks=None): # limit_bids/limit_asks optional, overrides limit_orders return get_json(url=_make_url('book', pair))
def candlestick(pair='btccny', period='15m'): period_translations = { '1m': '001', '5m': '005', '15m': '015', '30m': '030', '60m': '060', '1d': '100', '1w': '200', '1mo': '300', '1y': '400' } if period not in period_translations: raise ValueError url = DATA_API_URL + _convert_pair( pair) + '_kline_' + period_translations[period] + '_json.js' def process(data): return [{ 't': c[0], 'open': c[1], 'high': c[2], 'low': c[3], 'close': c[4], 'volume': c[5] } for c in data] return get_json(url=url).addCallback(process)
def lendbook(currency='usd', limit_orders=50, group=True, limit_bids=None, limit_asks=None): # semantically broken to pass currency as pair, but it does what is needed return get_json(url=_make_url('lendbook', currency))
def trades(pair='btcusd', limit_orders=50, timelimit=None, limit_bids=None, limit_asks=None): d = get_json(url=_make_url('trades', pair)) return d.addCallback(simpleschema.remap, [{'tid': 'id'}])
def update(self): if not self._should_update(): return defer.succeed(None) elif not self.can_update: return defer.succeed(None) d = utils.get_json(self.url) def process(data): if 'rates' in data: self.rates = data['rates'] self.last_updated = int(data['timestamp']) return self.rates else: log.info("Could not retrieve OER forex data") def handle_err(failure): failure.trap(errors.HTTPError) http_code = failure.value.code if 500 > int(http_code) >= 400: log.warn(( "Bad status code when updating OpenExchangeRates data: {}. " "Disabling updating from this data source." ).format(http_code)) self.can_update = False return d.addCallbacks(process, handle_err)
def ticker(pair='btcusd'): # api fails with code 200 and {u'error': u'Invalid method', u'success': 0} def process(data): new = data[_convert_pair(pair)] return simpleschema.remap(new, {'buy': 'bid', 'sell': 'ask', 'updated': 'timestamp', 'vol': 'volume', 'vol_cur': 'basis_volume', 'avg': 'mid'}) return get_json(url=_make_url('ticker', pair)).addCallback(process)
def orderbook(pair='btcusd', limit_orders=150): def process(data): new = data[_convert_pair(pair)] new['bids'] = [{'price': b[0], 'amount': b[1]} for b in new['bids']] new['asks'] = [{'price': a[0], 'amount': a[1]} for a in new['asks']] return new return get_json(url=_make_url('depth', pair)).addCallback(process)
def orderbook(pair="btccny"): def process(data): data["bids"] = [{"price": price, "amount": amount} for price, amount in data["bids"]] data["asks"] = [{"price": price, "amount": amount} for price, amount in data["asks"]] return data return get_json(url=_create_url("depth", pair)).addCallback(process)
def trades(pair='btcusd', limit_trades=150): def process(data): new = data[_convert_pair(pair)] for trade in new: trade['direction'] = bool(trade.pop('type') == 'bid') return simpleschema.remap(new, [{'tid': 'id'}]) return get_json(url=_make_url('trades', pair)).addCallback(process)
def update(self): if not self._should_update(): return defer.succeed(None) elif not self.can_update: return defer.succeed(None) d = utils.get_json(self.url) def process(data): if "rates" in data: self.rates = data["rates"] self.last_updated = int(data["timestamp"]) return self.rates else: log.info("Could not retrieve OER forex data") def handle_err(failure): failure.trap(errors.HTTPError) http_code = failure.value.code if 500 > int(http_code) >= 400: log.warn( ( "Bad status code when updating OpenExchangeRates data: {}. " "Disabling updating from this data source." ).format(http_code) ) self.can_update = False return d.addCallbacks(process, handle_err)
def eur_usd(): """ Get the Bitstamp EUR/USD conversion rate. Keys: buy - conversion rate when buying sell - conversion rate when selling """ return get_json(url=_make_url('eur_usd'))
def ticker(pair="btccny"): def process(data): data.update(data["ticker"]) data.pop("ticker") return data d = get_json(url=_create_url("ticker", pair)).addCallback(process) d.addCallback(simpleschema.remap, {"time": "timestamp", "buy": "bid", "sell": "ask", "vol": "volume"}) return d
def orderbook(pair='btccny'): def process(data): data['bids'] = [{ 'price': price, 'amount': amount } for price, amount in data['bids']] data['asks'] = [{ 'price': price, 'amount': amount } for price, amount in data['asks']] return data return get_json(url=_create_url('depth', pair)).addCallback(process)
def update(self): if not self._should_update(): return defer.succeed(None) d = utils.get_json(self.url) def process(data): if "rates" in data: self.rates = data["rates"] self.last_updated = utils.now_in_utc_secs() return self.rates else: log.info("Could not retrieve ECB forex data") return d.addCallback(process)
def ticker(pair='btccny'): def process(data): data.update(data['ticker']) data.pop('ticker') return data d = get_json(url=_create_url('ticker', pair)).addCallback(process) d.addCallback(simpleschema.remap, { 'time': 'timestamp', 'buy': 'bid', 'sell': 'ask', 'vol': 'volume' }) return d
def update(self): if not self._should_update(): return defer.succeed(None) d = utils.get_json(self.url) def process(data): if 'rates' in data: self.rates = data['rates'] self.last_updated = utils.now_in_utc_secs() return self.rates else: log.info("Could not retrieve ECB forex data") return d.addCallback(process)
def ticker(pair='btcusd'): # api fails with code 200 and {u'error': u'Invalid method', u'success': 0} def process(data): new = data[_convert_pair(pair)] return simpleschema.remap( new, { 'buy': 'bid', 'sell': 'ask', 'updated': 'timestamp', 'vol': 'volume', 'vol_cur': 'basis_volume', 'avg': 'mid' }) return get_json(url=_make_url('ticker', pair)).addCallback(process)
def update(self): if not self._should_update(): return defer.succeed(None) d = utils.get_json(self.url) def process(data): rates = dict() for quote in data["list"]["resources"]: quote = quote["resource"]["fields"] currency = quote["symbol"].split("=")[0] rates[currency] = Decimal(quote["price"]) self.rates = rates self.last_updated = utils.now_in_utc_secs() return rates return d.addCallback(process)
def update(self): if not self._should_update(): return defer.succeed(None) d = utils.get_json(self.url) def process(data): rates = dict() for quote in data['list']['resources']: quote = quote['resource']['fields'] currency = quote['symbol'].split('=')[0] rates[currency] = Decimal(quote['price']) self.rates = rates self.last_updated = utils.now_in_utc_secs() return rates return d.addCallback(process)
def ticker(pair='btcusd'): """ Get the Bitstamp ticker, which includes data on the last 24 hours. :rtype: defer.Deferred Keys: timestamp - time the data was generated volume - 24h volume vwap - 24h volume-weighted average price bid - highest bid ask - lowest ask last - last trade price low - lowest price in last 24h high - highest price in last 24h """ return get_json(url=_make_url('ticker', pair))
def candlestick(pair="btccny", period="15m"): period_translations = { "1m": "001", "5m": "005", "15m": "015", "30m": "030", "60m": "060", "1d": "100", "1w": "200", "1mo": "300", "1y": "400", } if period not in period_translations: raise ValueError url = DATA_API_URL + _convert_pair(pair) + "_kline_" + period_translations[period] + "_json.js" def process(data): return [{"t": c[0], "open": c[1], "high": c[2], "low": c[3], "close": c[4], "volume": c[5]} for c in data] return get_json(url=url).addCallback(process)
def trades(pair='btcusd', timeframe='minute'): """ Get recent Bitstamp transactions. :param timeframe: time duration to get trades for. Options: 'minute' and 'hour'. :type timeframe: str :rtype: defer.Deferred :raises ValueError: on invalid timeframe Keys: date - timestamp of trade tid - transaction ID price - price the trade executed at amount - amount of BTC that the trade executed for """ valid_timeframes = ('minute', 'hour') if timeframe not in valid_timeframes: raise ValueError("Invalid timeframe {}", timeframe) data = get_json(url=_make_url('transactions', pair), params={'time': timeframe}) return data.addCallback(simpleschema.remap, [{'tid': 'id', 'date': 'timestamp'}])
def orderbook(pair='btcusd', group=True): """ Get the full Bitstamp orderbook. :param group: whether to group orders with the same price. :type group: bool :rtype: defer.Deferred Keys: bids - list of bids asks - list of asks timestamp - when the orderbook data was created/returned """ raw = get_json(url=_make_url('order_book', pair), params={'group': int(group)}) def reflow(book): book['bids'] = [{'price': b[0], 'amount': b[1]} for b in book['bids']] book['asks'] = [{'price': a[0], 'amount': a[1]} for a in book['asks']] return book return raw.addCallback(reflow)
def detail(pair='btccny'): def process(data): data.pop('top_buy') data.pop('top_sell') data['trades'] = _convert_detail_trades(data['trades']) return data d = get_json(url=_create_url('detail', pair)) d.addCallback( simpleschema.remap, { 'p_new': 'last', 'p_open': 'open', 'p_last': 'close', 'p_high': 'high', 'p_low': 'low', 'amount': 'volume', 'total': 'basis_volume', 'level': 'change_pct', 'sells': 'asks', 'buys': 'bids' }) return d.addCallback(process)
def trades(pair='btcusd', timeframe='minute'): """ Get recent Bitstamp transactions. :param timeframe: time duration to get trades for. Options: 'minute' and 'hour'. :type timeframe: str :rtype: defer.Deferred :raises ValueError: on invalid timeframe Keys: date - timestamp of trade tid - transaction ID price - price the trade executed at amount - amount of BTC that the trade executed for """ valid_timeframes = ('minute', 'hour') if timeframe not in valid_timeframes: raise ValueError("Invalid timeframe {}", timeframe) data = get_json(url=_make_url('transactions', pair), params={'time': timeframe}) return data.addCallback(simpleschema.remap, [{ 'tid': 'id', 'date': 'timestamp' }])
def detail(pair="btccny"): def process(data): data.pop("top_buy") data.pop("top_sell") data["trades"] = _convert_detail_trades(data["trades"]) return data d = get_json(url=_create_url("detail", pair)) d.addCallback( simpleschema.remap, { "p_new": "last", "p_open": "open", "p_last": "close", "p_high": "high", "p_low": "low", "amount": "volume", "total": "basis_volume", "level": "change_pct", "sells": "asks", "buys": "bids", }, ) return d.addCallback(process)
def pairs(): """Get a list of valid pairs.""" return get_json(url=_make_url('symbols'))
def pair_info(pair='btcusd'): return get_json(url=_make_url('info', pair))
def ticker(pair='btcusd'): d = get_json(url=_make_url('pubticker', pair)) return d.addCallback(simpleschema.remap, {'last_price': 'last'})
def lends(currency='usd', limit_entries=50, timelimit=None, limit_bids=None, limit_asks=None): return get_json(url=_make_url('lends', currency))
def pairs_detailed(): """Get a list of valid pairs with additional info on them.""" return get_json(url=_make_url('symbols_details'))
def stats(pair='btcusd'): return get_json(url=_make_url('stats', pair))