diff --git a/__pycache__/bittrex.cpython-35.pyc b/__pycache__/bittrex.cpython-35.pyc new file mode 100644 index 0000000..46f17d2 Binary files /dev/null and b/__pycache__/bittrex.cpython-35.pyc differ diff --git a/bitbottest.py b/bitbottest.py new file mode 100644 index 0000000..0a46b3a --- /dev/null +++ b/bitbottest.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""BotTest using bittrex.py. + +This program gets the balance of your portfolio. +Reviews the price of Bitcoin, Bitcoin Cash, Litecoin, Ether, Omisego. +Makes a suggestion for a new portfolio rebalance. +""" +from bittrex import Bittrex + +import os + +import sys + +module_path = os.path.abspath(os.path.join('..')) +if module_path not in sys.path: + sys.path.append(module_path) + +from helpers.exchange_helpers import BittrexHelpers + +DEBUG = True +count = 10 +# Get these from https://bittrex.com/Account/ManageApiKey +exchange = None # 'Bittrex' +# Get these from https://bittrex.com/Account/ManageApiKey +if(exchange == 'Bittrex'): + bh = BittrexHelpers() + bh.get_account_data() + key = bh.get_key() + secret = bh.get_secret() +else: + key = 'key' + secret = 'secret' + +api = Bittrex(key, secret) + + +# Market coins to assess +currencies = ['BTC', 'BCC', 'LTC', 'ETH', 'OMG'] +market = '{0}-{1}'.format(currencies[0], currencies[1]) +if (DEBUG): + print('DEBUG: Market: {}, type {}'.format(market, type(market))) + +# public api methods +result = api.getmarkets() +if (DEBUG): + print('DEBUG: getmarkets (size {})'.format(len(result))) + # print(result) + for res in result[:count]: + print('Market: {0:>10}, MinTradeSize: {1:15.4f}'.format( + res['MarketName'], res['MinTradeSize'])) + +# result = api.getcurrencies() +# if (DEBUG): +# print('DEBUG: getcurrencies') +# print(result) + +# result = api.getticker(market) +# if (DEBUG): +# print('DEBUG: getticker') +# print(result) + +# result = api.getmarketsummaries() +# if (DEBUG): +# print('DEBUG: getmarketsummaries') +# # print(result) +# for marketSummary in result: +# print('Market: {0:>10}, Volume: {1:15.4f}'.format( +# marketSummary['MarketName'], marketSummary['Volume'])) + +# result = api.getmarketsummary(market) +# if (DEBUG): +# print('DEBUG: getmarketsummary') +# print(result) + +# result = api.getorderbook(market, 'both') +# if (DEBUG): +# print('DEBUG: getorderbook') +# print(result) + +result = api.getmarkethistory(market) +if (DEBUG): + print('DEBUG: marketHistory {} size {}'.format(market, len(result))) + for marketHistory in result[:count]: + print('Qty: {0:8.4f}, Price: {1:10.5f}, Type: {2:>6}, Time: {3}'. + format(marketHistory['Quantity'], marketHistory['Price'], + marketHistory['OrderType'], marketHistory['TimeStamp'])) + +# market: getopenorders + +# account: getbalances diff --git a/bittrex.py b/bittrex.py index 63a0f6e..6a3f909 100644 --- a/bittrex.py +++ b/bittrex.py @@ -1,111 +1,177 @@ -#!/usr/bin/env python -#import urllib -#import urllib2 -from urllib.parse import urlencode -import urllib.request +#!/usr/bin/env python3 +"""Bittrex Module. + +This is a module of helper functions to access the Bittrex API +using Python. + +Requires Python 3.x +""" +# import urllib +# import urllib2 +import hashlib +import hmac import json import time -import hmac -import hashlib +import urllib.request +from urllib.parse import urlencode + + +class Bittrex(object): + """Bittrex class object. + + The bittrex API methods are grouped into: public, market, and account + methods. Public methods do not require keys, however market and account + methods require a Bitrex public and private key pair. + + The Bittrex python class converts python style queries into API url + queries and returns the result in JSON format. + """ -class bittrex(object): - def __init__(self, key, secret): + """__init__ method for bittrex class. + + Define pubic and private key. Group API methods as Public, Market, + or Account. + """ self.key = key self.secret = secret - self.public = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries', 'getmarketsummary', 'getorderbook', 'getmarkethistory'] - self.market = ['buylimit', 'buymarket', 'selllimit', 'sellmarket', 'cancel', 'getopenorders'] - self.account = ['getbalances', 'getbalance', 'getdepositaddress', 'withdraw', 'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory'] - - + self.public = ['getmarkets', 'getcurrencies', 'getticker', + 'getmarketsummaries', 'getmarketsummary', + 'getorderbook', 'getmarkethistory'] + self.market = ['buylimit', 'buymarket', 'selllimit', 'sellmarket', + 'cancel', 'getopenorders'] + self.account = ['getbalances', 'getbalance', 'getdepositaddress', + 'withdraw', 'getorder', 'getorderhistory', + 'getwithdrawalhistory', 'getdeposithistory'] + def query(self, method, values={}): + """Create URL for API method call and return bittrex response.""" if method in self.public: url = 'https://bittrex.com/api/v1.1/public/' elif method in self.market: url = 'https://bittrex.com/api/v1.1/market/' - elif method in self.account: + elif method in self.account: url = 'https://bittrex.com/api/v1.1/account/' else: return 'Something went wrong, sorry.' - + url += method + '?' + urlencode(values) - + if method not in self.public: url += '&apikey=' + self.key url += '&nonce=' + str(int(time.time())) - signature = hmac.new(self.secret, url, hashlib.sha512).hexdigest() + signature = hmac.new(bytearray(self.secret.encode('UTF-8')), + url.encode('UTF-8'), + hashlib.sha512).hexdigest() headers = {'apisign': signature} else: headers = {} - + req = urllib.request.Request(url, headers=headers) - response = json.loads(urllib.request.urlopen(req).read()) - - if response["result"]: + response = json.loads(urllib.request.urlopen(req).read(). + decode('utf-8')) + + if response["success"]: return response["result"] else: return response["message"] - - + def getmarkets(self): + """Get all open and available trading markets at Bittrex. + + Other meta data: MarketCurrency, BaseCurrency, MarketCurrencyLong, + BaseCurrencyLong, MinTradeSize, MarketName, IsActive, Created + Public method. + """ return self.query('getmarkets') - + def getcurrencies(self): + """Do what(?) returns what. Public method.""" return self.query('getcurrencies') - + def getticker(self, market): + """Do what(?) returns what. Public method.""" return self.query('getticker', {'market': market}) - + def getmarketsummaries(self): + """Do what(?) returns what. Public method.""" return self.query('getmarketsummaries') - + def getmarketsummary(self, market): + """Do what(?) returns what. Public method.""" return self.query('getmarketsummary', {'market': market}) - - def getorderbook(self, market, type, depth=20): - return self.query('getorderbook', {'market': market, 'type': type, 'depth': depth}) - - def getmarkethistory(self, market, count=20): - return self.query('getmarkethistory', {'market': market, 'count': count}) - + + def getorderbook(self, market, type): + """Do what(?) returns what. Public method. + + Also, I have removed obsolete depth parameter from this method. + """ + return self.query('getorderbook', {'market': market, 'type': type}) + + def getmarkethistory(self, market): + """Do what(?) returns what. Public method.""" + return self.query('getmarkethistory', {'market': market}) + def buylimit(self, market, quantity, rate): - return self.query('buylimit', {'market': market, 'quantity': quantity, 'rate': rate}) - + """Do what(?) returns what. Market method.""" + return self.query('buylimit', {'market': market, + 'quantity': quantity, 'rate': rate}) + def buymarket(self, market, quantity): - return self.query('buymarket', {'market': market, 'quantity': quantity}) - + """Do what(?) returns what. Market method.""" + return self.query('buymarket', {'market': market, + 'quantity': quantity}) + def selllimit(self, market, quantity, rate): - return self.query('selllimit', {'market': market, 'quantity': quantity, 'rate': rate}) - + """Do what(?) returns what. Market method.""" + return self.query('selllimit', {'market': market, + 'quantity': quantity, 'rate': rate}) + def sellmarket(self, market, quantity): - return self.query('sellmarket', {'market': market, 'quantity': quantity}) - + """Do what(?) returns what. Market method.""" + return self.query('sellmarket', {'market': market, + 'quantity': quantity}) + def cancel(self, uuid): + """Do what(?) returns what. Market method.""" return self.query('cancel', {'uuid': uuid}) - + def getopenorders(self, market): + """Do what(?) returns what. Market method.""" return self.query('getopenorders', {'market': market}) - + def getbalances(self): + """Do what(?) returns what. Account method.""" return self.query('getbalances') - + def getbalance(self, currency): + """Do what(?) returns what.Account method.""" return self.query('getbalance', {'currency': currency}) - + def getdepositaddress(self, currency): + """Do what(?) returns what. Account method.""" return self.query('getdepositaddress', {'currency': currency}) - + def withdraw(self, currency, quantity, address): - return self.query('withdraw', {'currency': currency, 'quantity': quantity, 'address': address}) - + """Do what(?) returns what. Account method.""" + return self.query('withdraw', {'currency': currency, + 'quantity': quantity, 'address': address}) + def getorder(self, uuid): + """Do what(?) returns what. Account method.""" return self.query('getorder', {'uuid': uuid}) - + def getorderhistory(self, market, count): - return self.query('getorderhistory', {'market': market, 'count': count}) - + """Do what(?) returns what. Account method.""" + return self.query('getorderhistory', {'market': market, + 'count': count}) + def getwithdrawalhistory(self, currency, count): - return self.query('getwithdrawalhistory', {'currency': currency, 'count': count}) - + """Do what(?) returns what. Account method.""" + return self.query('getwithdrawalhistory', {'currency': currency, + 'count': count}) + def getdeposithistory(self, currency, count): - return self.query('getdeposithistory', {'currency': currency, 'count': count}) + """Do what(?) returns what. Account method.""" + return self.query('getdeposithistory', {'currency': currency, + 'count': count}) diff --git a/data/data.json b/data/data.json new file mode 100644 index 0000000..bcd06c6 --- /dev/null +++ b/data/data.json @@ -0,0 +1,13 @@ +{ + "parameters": { + "basecurrency": "BTC", + "fiat": "USD", + "history_length": 1000, + "history_period_seconds": 180, + "exchange": "bittrex" + }, + "keys": { + "public": "2c76546df0324d04ae5d2ae2c382ea86", + "private": "8a596b19bbc54373ab0c26c9f7a42038" + } +} \ No newline at end of file diff --git a/example.py b/example.py index a51429a..a27ef8c 100644 --- a/example.py +++ b/example.py @@ -1,9 +1,33 @@ #!/usr/bin/env python -# This program buys some Dogecoins and sells them for a bigger price -from bittrex import bittrex +"""Example program. +This program buys some Dogecoins and sells them for a bigger price. +""" +from bittrex import Bittrex + +import os + +import sys + +module_path = os.path.abspath(os.path.join('..')) +if module_path not in sys.path: + sys.path.append(module_path) + +from helpers.exchange_helpers import BittrexHelpers + + +exchange = None # 'Bittrex' # Get these from https://bittrex.com/Account/ManageApiKey -api = bittrex('key', 'secret') +if(exchange == 'Bittrex'): + bh = BittrexHelpers() + bh.get_account_data() + key = bh.get_key() + secret = bh.get_secret() +else: + key = 'key' + secret = 'secret' + +api = Bittrex(key, secret) # Market to trade at trade = 'BTC' @@ -17,21 +41,29 @@ # Getting the BTC price for DOGE dogesummary = api.getmarketsummary(market) dogeprice = dogesummary[0]['Last'] -print 'The price for {0} is {1:.8f} {2}.'.format(currency, dogeprice, trade) +print('The price for {0} is {1:.8f} {2}.'.format(currency, dogeprice, trade)) # Buying 100 DOGE for BTC -print 'Buying {0} {1} for {2:.8f} {3}.'.format(amount, currency, dogeprice, trade) -api.buylimit(market, amount, dogeprice) +# print('Buying {0} {1} for {2:.8f} {3}.'.format(amount, currency, dogeprice, +# trade)) +# api.buylimit(market, amount, dogeprice) -# Multiplying the price by the multiplier -dogeprice = round(dogeprice*multiplier, 8) +# # Multiplying the price by the multiplier +# dogeprice = round(dogeprice * multiplier, 8) -# Selling 100 DOGE for the new price -print 'Selling {0} {1} for {2:.8f} {3}.'.format(amount, currency, dogeprice, trade) -api.selllimit(market, amount, dogeprice) +# # Selling 100 DOGE for the new price +# print('Selling {0} {1} for {2:.8f} {3}.'.format(amount, currency, dogeprice, +# trade)) +# api.selllimit(market, amount, dogeprice) # Gets the DOGE balance dogebalance = api.getbalance(currency) -print "Your balance is {0} {1}.".format(dogebalance['Available'], currency) +try: + print("Your balance is {0} {1}.".format(dogebalance['Available'], + currency)) +except TypeError: + print("Error in API call to getbalance: {}".format(dogebalance)) + -# For a full list of functions, check out bittrex.py or https://bittrex.com/Home/Api +# For a full list of functions, check out: +# bittrex.py or https://bittrex.com/Home/Api