Ejemplo n.º 1
0
 def setPath(self):
     """
     Define current path with Browser (utils)
     """
     file = Browser()
     self.get('dirname').set(file.get())
Ejemplo n.º 2
0
class SATANG:
    """
    Official Documentation for Satang Pro APIs
    https://docs.satang.pro

    ~~~ wtf(p)!!!, where to find (python)!!!
    """
    def __init__(self, debug=False):
        self._api = 'https://api.satang.pro/api'
        self._uid = os.getenv('SATANG_USER_ID', '')
        self._key = os.getenv('SATANG_API_KEY', '')
        self._secret = os.getenv('SATANG_API_SECRET', '').encode('utf-8')

        self._debug = debug
        self._browser = Browser(debug=self._debug)

    ##########
    # --- public api ---
    # Get ticker information.
    def get_bids_asks(self, sym='btc_thb'):
        """
        :return: {
         'asks': [[rate, amount], [174629, 0.00010107], ...],
         'bids': [[rate, amount], [174629, 0.00010107], ...]
        }
        """
        payload = {'url': self._api + f'/orders/?pair={sym.lower()}'}
        return self._resp_order(self._resp(self._browser.get(**payload)))

    ##########
    # --- private api ---
    # User
    def user(self):
        payload = {
            'url': self._api + f'/users/:{self._uid}',
            'headers': self._build_headers()
        }
        return self._resp(self._browser.get(**payload))

    # Create a buy order.
    def buy(self, pair, price, amount, typ='limit'):
        data = {
            'pair': pair.lower(),
            'price': price,
            'amount': amount,
            'side': 'buy',
            'type': ('limit' if typ == 'limit' else 'market'),
            'nonce': nonce()
        }
        print(data)
        return self._create_orders(**data)

    # Create a sell order.
    def sell(self, pair, price, amount, typ='limit'):
        data = {
            'pair': pair.lower(),
            'price': price,
            'amount': amount,
            'side': 'sell',
            'type': ('limit' if typ == 'limit' else 'market'),
            'nonce': nonce()
        }
        return self._create_orders(**data)

    def _create_orders(self, **kwargs):
        data = self._concatenate_params(**kwargs)
        payload = {
            'url': self._api + '/orders/',
            'headers': self._build_headers(data),
            'data': data
        }
        return self._resp(self._browser.post(**payload))

    ##########
    # utility
    def _build_headers(self, s=''):
        return {
            'Authorization': 'TDAX-API ' + self._key,
            'Signature': hmac.new(self._secret, s.encode('utf-8'), hashlib.sha512).hexdigest(),
        }

    def _resp(self, resp):
        if resp.status_code == 200:
            return resp.json()
        if self._debug:  # catch error !?
            raise Exception(resp)

    @staticmethod
    def _resp_order(o):
        return {
            'bids': [[_['price'], _['amount']] for _ in o['bid']],
            'asks': [[_['price'], _['amount']] for _ in o['ask']]
        }

    @staticmethod
    def _concatenate_params(**p):
        print(p)
        return'&'.join(sorted(['{}={}'.format(_, p[_]) for _ in p])) if p else ''
Ejemplo n.º 3
0
class BITKUB:
    """
    Official Documentation for Bitkub APIs
    https://github.com/bitkub/bitkub-official-api-docs
    """
    def __init__(self, debug=False):
        self._api = 'https://api.bitkub.com/api'
        self._key = os.getenv('BITKUB_API_KEY', '')
        self._secret = os.getenv('BITKUB_API_SECRET', '').encode()

        self._debug = debug
        self._browser = Browser(debug=self._debug)

    ##########
    # --- public api ---
    # Get ticker information.
    def ticker(self, sym=''):
        sym = '' if sym == '' else f'?sym={sym.upper()}'
        payload = {'url': self._api + f'/market/ticker{sym}'}
        return self._resp(self._browser.get(**payload))

    # List open (bids/asks) orders.
    def get_bids_asks(self, sym='THB_BTC', lmt=10):
        """
        :return: {
         'asks': [[rate, amount], [174629, 0.00010107], ...],
         'bids': [[rate, amount], [174629, 0.00010107], ...]
        }
        """
        payload = {
            'url': self._api + f'/market/depth?sym={sym.upper()}&lmt={lmt}'
        }
        return self._resp(self._browser.get(**payload))

    # List open buy(bids) orders.
    def get_bids(self, sym='THB_BTC', lmt=10):
        """
        :return: [[rate, volume, amount], [174629, 17.65, 0.00010107], ...]
        """
        payload = {
            'url': self._api + f'/market/bids?sym={sym.upper()}&lmt={lmt}'
        }
        return self._resp_order(self._resp(self._browser.get(**payload)))

    # List open sell(asks) orders.
    def get_asks(self, sym='THB_BTC', lmt=10):
        """
        :return: [[rate, volume, amount], [175500, 928.14, 0.00528859], ...]
        """
        payload = {
            'url': self._api + f'/market/asks?sym={sym.upper()}&lmt={lmt}'
        }
        return self._resp_order(self._resp(self._browser.get(**payload)))

    ##########
    # --- private api ---
    # Get balances info
    def balance(self):
        payload = {
            'url': self._api + '/market/balances',
            'headers': self._build_headers(),
            'data': self._build_sign({})
        }
        return self._resp(self._browser.post(**payload))

    # Create a sell order.
    def sell(self, **kwargs):
        """
        :param kwargs: sym, amt, rat, typ
        """
        payload = {
            'url': self._api + '/market/place-ask',
            'headers': self._build_headers(),
            'data': self._build_sign(self._data_rules(**kwargs))
        }
        return self._resp(self._browser.post(**payload))

    # Create a buy order.
    def buy(self, **kwargs):
        """
        :param kwargs: sym, amt, rat, typ
        """
        payload = {
            'url': self._api + '/market/place-bid',
            'headers': self._build_headers(),
            'data': self._build_sign(self._data_rules(**kwargs))
        }
        return self._resp(self._browser.post(**payload))

    ##########
    # utility
    def _build_headers(self):
        return {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-BTK-APIKEY': self._key,
        }

    def _build_sign(self, data):
        data['ts'] = nonce()
        data['sig'] = hmac.new(self._secret,
                               self._json_encode(data).encode(),
                               hashlib.sha256).hexdigest()
        return self._json_encode(data)

    @staticmethod
    def _data_rules(**kwargs):
        params = {}
        if 'sym' in kwargs:  # symbol is upper case
            params['sym'] = kwargs['sym'].upper()
        if 'amt' in kwargs:  # 0.10000000 is invalid, 0.1 is ok
            params['amt'] = format_float(kwargs['amt'])
        if 'rat' in kwargs:  # (e.g 1000.00 is invalid, 1000 is ok)
            params['rat'] = format_float(kwargs['rat'])
        if 'typ' in kwargs:  # limit or market
            params['typ'] = ('market'
                             if kwargs['typ'] == 'market' else 'limit')
        return params

    def _resp(self, resp):
        if resp.status_code == 200:
            if resp.json().get('error') == 0:
                return resp.json()['result']
            return resp.json()
        if self._debug:  # catch error !?
            raise Exception(resp)

    @staticmethod
    def _resp_order(o):
        # idx, timestamp, volume, rate, amount
        return [[r, v, a] for i, t, v, r, a in o]

    @staticmethod
    def _json_encode(data):
        return json.dumps(data, separators=(',', ':'), sort_keys=True)