# -*- coding: utf-8 -*-
# Author:	t0pep0
# e-mail:	<EMAIL>
# Jabber:	<EMAIL>
# BTC   :	1ipEA2fcVyjiUnBqUx7PVy5efktz2hucb
# donate free =)
# Forked and modified by <NAME>
# Compatible Python3

import hmac
import hashlib
import time
import urllib.request, urllib.parse, urllib.error
import json


class Api(object):
    __username = ''
    __api_key = ''
    __api_secret = ''
    __nonce_v = ''
    # Init class
    def __init__(self, username, api_key, api_secret):
        self.__username = username
        self.__api_key = api_key
        self.__api_secret = api_secret

    # get timestamp as nonce
    def __nonce(self):
        self.__nonce_v = '{:.10f}'.format(time.time() * 1000).split('.')[0]

    # generate signature
    def __signature(self):
        byte_secret = bytes(self.__api_secret, "ascii")
        string = self.__nonce_v + self.__username + self.__api_key  # create string
        encode_string = string.encode ('utf-8')
        signature = hmac.new(byte_secret, encode_string, digestmod=hashlib.sha256).hexdigest().upper()  # create signature
        return signature

    def __post(self, url, param):  # Post Request (Low Level API call)
        post_url = url
        header = { 'User-agent': 'bot-cex.io-' }
        params = urllib.parse.urlencode(param)
        post_data = params.encode( "ascii")
        req = urllib.request.Request(url = post_url, data = post_data, headers = header)
        page = urllib.request.urlopen(req).read()
        return page

    def api_call(self, method, param={}, private=0, couple=''):  # api call (Middle level)
        url = 'https://cex.io/api/' + method + '/'  # generate url
        if couple != '':
            url = url + couple + '/'  # set couple if needed
        if private == 1:  # add auth-data if needed
            self.__nonce()
            param.update({
                'key': self.__api_key,
                'signature': self.__signature(),
                'nonce': self.__nonce_v})
        answer = self.__post(url, param)  # Post Request
        a = answer.decode("utf-8")
        #return json.loads(answer)  # generate dict and return
        return a                    # generates a valid json output

    def ticker(self, couple='MHC/BTC'):
        return self.api_call('ticker', {}, 0, couple)

    def tickers(self, couple='USD'):
        return self.api_call('tickers', {}, 0, couple)

    def ohlcv(self, end_date, couple='BTC/USD'):
        return self.api_call('ohlcv/hd/'+str(end_date), {}, 0, couple)

    def order_book(self, couple='MHC/BTC'):
        return self.api_call('order_book', {}, 0, couple)

    def trade_history(self, since=1, couple='MHC/BTC'):
        return self.api_call('trade_history', {"since": str(since)}, 0, couple)

    def balance(self):
        return self.api_call('balance', {}, 1)

    def current_orders(self, couple='MHC/BTC'):
        return self.api_call('open_orders', {}, 1, couple)

    def cancel_order(self, order_id):
        return self.api_call('cancel_order', {"id": order_id}, 1)

    def place_order(self, ptype='buy', amount=1, price=1, couple='MHC/BTC'):
        return self.api_call('place_order', {"type": ptype, "amount": str(amount), "price": str(price)}, 1, couple)

    def archived_orders(self, couple='XLM/USD'):
        return self.api_call('archived_orders', {}, 1, couple)

    def price_stats(self, last_hours, max_resp_arr_size, couple='MHC/BTC'):
        return self.api_call(
                'price_stats',
                {"lastHours": last_hours, "maxRespArrSize": max_resp_arr_size},
                0, couple)

# -*- coding: utf-8 -*-
# Author:	t0pep0
# e-mail:	<EMAIL>
# Jabber:	<EMAIL>
# BTC   :	1ipEA2fcVyjiUnBqUx7PVy5efktz2hucb
# donate free =)
# Forked and modified by <NAME>
# Compatible Python3

import hmac
import hashlib
import time
import urllib.request, urllib.parse, urllib.error
import json


class Api(object):
    __username = ''
    __api_key = ''
    __api_secret = ''
    __nonce_v = ''
    # Init class
    def __init__(self, username, api_key, api_secret):
        self.__username = username
        self.__api_key = api_key
        self.__api_secret = api_secret

    # get timestamp as nonce
    def __nonce(self):
        self.__nonce_v = '{:.10f}'.format(time.time() * 1000).split('.')[0]

    # generate signature
    def __signature(self):
        byte_secret = bytes(self.__api_secret, "ascii")
        string = self.__nonce_v + self.__username + self.__api_key  # create string
        encode_string = string.encode ('utf-8')
        signature = hmac.new(byte_secret, encode_string, digestmod=hashlib.sha256).hexdigest().upper()  # create signature
        return signature

    def __post(self, url, param):  # Post Request (Low Level API call)
        post_url = url
        header = { 'User-agent': 'bot-cex.io-' }
        params = urllib.parse.urlencode(param)
        post_data = params.encode( "ascii")
        req = urllib.request.Request(url = post_url, data = post_data, headers = header)
        page = urllib.request.urlopen(req).read()
        return page

    def api_call(self, method, param={}, private=0, couple=''):  # api call (Middle level)
        url = 'https://cex.io/api/' + method + '/'  # generate url
        if couple != '':
            url = url + couple + '/'  # set couple if needed
        if private == 1:  # add auth-data if needed
            self.__nonce()
            param.update({
                'key': self.__api_key,
                'signature': self.__signature(),
                'nonce': self.__nonce_v})
        answer = self.__post(url, param)  # Post Request
        a = answer.decode("utf-8")
        #return json.loads(answer)  # generate dict and return
        return a                    # generates a valid json output

    def ticker(self, couple='MHC/BTC'):
        return self.api_call('ticker', {}, 0, couple)

    def tickers(self, couple='USD'):
        return self.api_call('tickers', {}, 0, couple)

    def ohlcv(self, end_date, couple='BTC/USD'):
        return self.api_call('ohlcv/hd/'+str(end_date), {}, 0, couple)

    def order_book(self, couple='MHC/BTC'):
        return self.api_call('order_book', {}, 0, couple)

    def trade_history(self, since=1, couple='MHC/BTC'):
        return self.api_call('trade_history', {"since": str(since)}, 0, couple)

    def balance(self):
        return self.api_call('balance', {}, 1)

    def current_orders(self, couple='MHC/BTC'):
        return self.api_call('open_orders', {}, 1, couple)

    def cancel_order(self, order_id):
        return self.api_call('cancel_order', {"id": order_id}, 1)

    def place_order(self, ptype='buy', amount=1, price=1, couple='MHC/BTC'):
        return self.api_call('place_order', {"type": ptype, "amount": str(amount), "price": str(price)}, 1, couple)

    def archived_orders(self, couple='XLM/USD'):
        return self.api_call('archived_orders', {}, 1, couple)

    def price_stats(self, last_hours, max_resp_arr_size, couple='MHC/BTC'):
        return self.api_call(
                'price_stats',
                {"lastHours": last_hours, "maxRespArrSize": max_resp_arr_size},
                0, couple)

# -*- coding: utf-8 -*- # Author:	t0pep0 # e-mail:	<EMAIL> # Jabber:	<EMAIL> # BTC   :	1ipEA2fcVyjiUnBqUx7PVy5efktz2hucb # donate free =) # Forked and modified by <NAME> # Compatible Python3 # Init class # get timestamp as nonce # generate signature # create string # create signature # Post Request (Low Level API call) # api call (Middle level) # generate url # set couple if needed # add auth-data if needed # Post Request #return json.loads(answer)  # generate dict and return # generates a valid json output