Source code for bitfinex.utils

"""Module for rest and websocket utilities"""
import re
import time
from datetime import datetime
import logging
from enum import Enum

[docs]class Operation(Enum): NEW = 1 UPDATE = 2 CANCEL = 3 MULTI_CANCEL = 4
OPERATION_CODE = { Operation.NEW: "on", Operation.UPDATE: "ou", Operation.CANCEL: "oc", Operation.MULTI_CANCEL: "oc_multi" }
[docs]def create_cid(): """Create a new Client order id. Based on timestamp multiplied to 10k to make it improbable that two actions are assigned the same cid. Returns ------- int A integer number equal to the current timestamp * 10 thousend. """ now = datetime.utcnow() epoch = datetime.utcfromtimestamp(0) return int((now - epoch).total_seconds() * 10000)
[docs]def cid_to_date(cid): """Converts a cid to date string YYYY-MM-DD Parameters ---------- cid : int A cid as it is generated by the function ``utils.create_cid()`` Returns ------- str A string formated date (e.g. YYYY-MM-DD, 2018-10-01) """ return datetime.utcfromtimestamp( cid/10000.0 ).strftime("%Y-%m-%d")
[docs]def get_nonce(multiplier): """Returns a nonce used in authentication. Nonce must be an increasing number. If other frameworks have used higher numbers you might need to increase the nonce_multiplier. """ return str(float(time.time()) * multiplier)
TRADE_SYMBOL_MISSING = re.compile(r"^[a-zA-Z]{6}$") """Regular expression used to match trade symbols without a leading t (e.g. BTCUSD)""" FUNDING_SYMBOL_MISSING = re.compile(r"^[a-zA-Z]{3}$") """Regular expression used to match financing symbols without a leading f (e.g. BTC)"""
[docs]def order_symbol(symbol, capital=True): """Convinience function for skipping t or f before symbols for trade and funding orders. Parameters ---------- symbol : str Symbol as a string. For example BTCUSD for trades or BTC for funding. capital : bool Boolean to capitalize trading and funding symbols. Capilat symbols are required in v2 of the Bitfinex API. Default: True """ if capital: _symbol = symbol.upper() else: _symbol = symbol if TRADE_SYMBOL_MISSING.match(symbol): return "t{}".format(_symbol) elif FUNDING_SYMBOL_MISSING.match(symbol): return "f{}".format(_symbol) return symbol
[docs]def get_bitfinex_logger(name): """ Utility method for class specific logging """ logger = logging.getLogger(name) logger.setLevel(logging.INFO) logger.propagate = True if not logger.handlers: # Add console log console = logging.StreamHandler() formatter_console = logging.Formatter( '%(asctime)s %(levelname) -10s %(name) -10s' ' %(funcName) -10s %(lineno) -5d %(message)s' ) console.setFormatter(formatter_console) console.setLevel(logging.INFO) logger.addHandler(console) return logger