<commit_before># -*- coding: utf-8 -*-

import requests
from decimal import Decimal
import time
from cryptotik.common import headers, ExchangeWrapper
import hmac
import hashlib


class Bitstamp(ExchangeWrapper):

    def __init__(self, apikey=None, secret=None, customer_id=None, timeout=None):

        if apikey:
            self._apikey = apikey
            self._secret = secret
            self._customer_id = customer_id

    api_session = requests.Session()

    public_commands = ("ticker", "transactions", "order_book")
    private_commands = ("balance", "user_transactions", "open_orders", "order_status",
                        "cancel_order", "cancel_all_orders", "buy",
                        "sell")

    name = 'bitstamp'
    url = 'https://www.bitstamp.net/'
    trade_url = url + 'api/v2/'
    delimiter = ""
    case = "lower"
    headers = headers
    _markets = 'btcusd, btceur, eurusd, xrpusd, xrpeur, xrpbtc, ltcusd, ltceur, ltcbtc, ethusd, etheur, ethbtc'.split(', ')
    maker_fee, taker_fee = 0.002, 0.002
    try:
        assert timeout is not None
    except:
        timeout = (8, 15)

    def get_nonce(self):
        '''return nonce integer'''

        nonce = getattr(self, '_nonce', 0)
        if nonce:
            nonce += 1
        # If the unix time is greater though, use that instead (helps low
        # concurrency multi-threaded apps always call with the largest nonce).
        self._nonce = max(int(time.time()), nonce)
        return self._nonce

    @classmethod
    def format_pair(cls, pair):
        """format the pair argument to format understood by remote API."""

        pair = pair.replace("-", cls.delimiter)

        if not pair.islower():
            return pair.lower()
        else:
            return pair

    @classmethod
    def api(cls, command):
        """call remote API"""

        result = cls.api_session.get(cls.url + command, headers=cls.headers,
                                     timeout=cls.timeout)

        assert result.status_code == 200, {"error": "http_error: " + str(result.status_code)}

        return result.json()

    def private_api(self, command):
        '''handles private api methods'''

        if not self._customer_id or not self._apikey or not self._secret:
            raise ValueError("A Key, Secret and customer_id required!")

        nonce = str(self.get_nonce())
        message = (nonce + self._customer_id + self._apikey).encode('utf-8')

        sig = hmac.new(self._secret.encode('utf-8'),
                       msg=message,
                       digestmod=hashlib.sha256).hexdigest().upper()

        result = self.api_session.post(self.trade_url+command,
                                       data={'key': self._apikey,
                                             'nonce': nonce,
                                             'signature': sig},
                                       headers=headers,
                                       timeout=self.timeout)

        assert result.status_code == 200, {"error": "http_error: " + str(result.status_code)}

        return result

    @classmethod
    def get_markets(cls):
        '''get all market pairs supported by the exchange'''
<commit_msg>rework Bistamp with proxy support.<commit_after># -*- coding: utf-8 -*-

import requests
from decimal import Decimal
import time
from cryptotik.common import headers, ExchangeWrapper, APIError
import hmac
import hashlib


class Bitstamp(ExchangeWrapper):

    def __init__(self, apikey=None, secret=None, customer_id=None,
                 timeout=None, proxy=None):

        if apikey:
            self._apikey = apikey
            self._secret = secret
            self._customer_id = customer_id

        if proxy:
            assert proxy.startswith('https'), {'Error': 'Only https proxies supported.'}
        self.proxy = {'https': proxy}

        if not timeout:
            self.timeout = (8, 15)
        else:
            self.timeout = timeout

        self.api_session = requests.Session()

    public_commands = ("ticker", "transactions", "order_book")
    private_commands = ("balance", "user_transactions", "open_orders", "order_status",
                        "cancel_order", "cancel_all_orders", "buy",
                        "sell")

    name = 'bitstamp'
    url = 'https://www.bitstamp.net/'
    trade_url = url + 'api/v2/'
    delimiter = ""
    case = "lower"
    headers = headers
    _markets = 'btcusd, btceur, eurusd, xrpusd, xrpeur, xrpbtc, ltcusd, ltceur, ltcbtc, ethusd, etheur, ethbtc'.split(', ')
    maker_fee, taker_fee = 0.002, 0.002

    def get_nonce(self):
        '''return nonce integer'''

        nonce = getattr(self, '_nonce', 0)
        if nonce:
            nonce += 1
        # If the unix time is greater though, use that instead (helps low
        # concurrency multi-threaded apps always call with the largest nonce).
        self._nonce = max(int(time.time()), nonce)
        return self._nonce

    @classmethod
    def format_pair(cls, pair):
        """format the pair argument to format understood by remote API."""

        pair = pair.replace("-", cls.delimiter)

        if not pair.islower():
            return pair.lower()
        else:
            return pair

    def api(self, command):
        """call remote API"""

        try:
            result = self.api_session.get(self.url + command, headers=self.headers,
                                          timeout=self.timeout, proxies=self.proxy)

        assert result.status_code == 200, {"error": "http_error: " + str(result.status_code)}
        return result.json()
        except requests.exceptions.RequestException as e:
            raise APIError(e)

    def private_api(self, command):
        '''handles private api methods'''

        if not self._customer_id or not self._apikey or not self._secret:
            raise ValueError("A Key, Secret and customer_id required!")

        nonce = str(self.get_nonce())
        message = (nonce + self._customer_id + self._apikey).encode('utf-8')

        sig = hmac.new(self._secret.encode('utf-8'),
                       msg=message,
                       digestmod=hashlib.sha256).hexdigest().upper()

        result = self.api_session.post(self.trade_url+command,
                                       data={'key': self._apikey,
                                             'nonce': nonce,
                                             'signature': sig},
                                       headers=headers,
                                       timeout=self.timeout)

        assert result.status_code == 200, {"error": "http_error: " + str(result.status_code)}

        return result

    @classmethod
    def get_markets(cls):
        '''get all market pairs supported by the exchange'''

{'fraction_non_alphanumeric': 0.11057054400707651, 'fraction_numerical': 0.007666224384490638, 'mean_word_length': 1.934256055363322, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 17, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1639961', 'n_tokens_mistral': 1968, 'n_tokens_neox': 1854, 'n_words': 496}