Skip to content

Instantly share code, notes, and snippets.

@umrysh
Last active October 1, 2016 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umrysh/316a20966754d4a2eb9fbfdc4f53b155 to your computer and use it in GitHub Desktop.
Save umrysh/316a20966754d4a2eb9fbfdc4f53b155 to your computer and use it in GitHub Desktop.
Dashboard for Tompool.org that also transfers and sells coins
import requests
import json
import subprocess as sp
import time
from bittrex import Bittrex
import hmac
import urllib
import hashlib
import base64
import sys
import eventlet
eventlet.monkey_patch()
####################################################################################
## Requires the awesome python-bittrex script from:
## https://github.com/ericsomdahl/python-bittrex/blob/master/bittrex/bittrex.py
####################################################################################
####################################################################################
## Also borrowed code from this forum post:
## https://www.cryptopia.co.nz/Forum/Thread/262?postId=1518
####################################################################################
# TomPool.org API Key
apiKey = 'api_key'
# Bittrex
bittrex = Bittrex(api_key = 'api_key', api_secret = 'api_secret')
bittrexTxFee = 0.00020000
# Cryptopia
API_KEY = 'api_key'
API_SECRET = 'api_secret'
transferLimit = 0.2
sellValueMin = 0.0005
bitcoinWallet = 'wallet_address'
def api_query( method, req = None ):
if not req:
req = {}
#print "def api_query( method = " + method + ", req = " + str( req ) + " ):"
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip","SubmitWithdraw" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
with eventlet.Timeout(20):
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data)
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
with eventlet.Timeout(20):
r = requests.post( url, data = post_data, headers = headers )
response = r.text
#print "( Response ): " + response
#return response.replace("false","False").replace("true","True").replace('":null','":None' )
return r.text
tmp = sp.call('clear',shell=True)
print "Loading..."
executions = ""
while(True):
comment = ""
totalValue = 0.0
response = requests.get('https://www.cryptopia.co.nz/api/GetMarkets')
if response.status_code==200:
cryptopia = response.json()
if cryptopia["Success"] == True:
cryptopia = cryptopia["Data"]
else:
cryptopia = json.loads("{}")
else:
cryptopia = json.loads("{}")
response = requests.post('http://tompool.org/ws/account/balance', json={'apiKey':apiKey})
if response.status_code==200:
data = response.json()
#print "%s" % response.json()
if data["error"] == "None":
comment += "{'error':'%s'}" % str(data["error"])
else:
try:
response = requests.get('https://api.quadrigacx.com/v2/ticker?book=btc_cad')
except Exception as e:
cadvalue = 0.0
pass
if response.status_code==200:
cadvalue = response.json()
cadvalue = float(cadvalue["last"])
else:
cadvalue = 0.0
comment = "%s | BTC/CAD: $%s\n\nBalances at Tompool\n\n" % (time.strftime("%Y-%m-%d %H:%M:%S"),cadvalue)
comment += "{0:6} {1:15} {2:15} {3:15} {4:15} {5:12} {6:18}".format("Coin","Pending","Balance","Price","Value","CAD Value","Market")
comment += "\n--------------------------------------------------------------------------------------------------"
for coins in data["balance"]:
if float(coins["balance"]) != 0.0 or float(coins["unconfirmedBalance"]) != 0.0:
getValue = json.loads(json.dumps(bittrex.get_ticker("BTC-%s" % coins["coinTypeCode"].upper())))
if(getValue["success"] == True):
comment += "\n{0:6} {1:15.10f} {2:15.10f} {3:15.10f} {4:15.10f} ${5:.2f} {6:18}".format(coins["coinTypeCode"].upper(),float(coins["unconfirmedBalance"]),float(coins["balance"]),getValue["result"]["Last"],getValue["result"]["Last"]*float(coins["balance"]),getValue["result"]["Last"]*float(coins["balance"])*cadvalue,"Bittrex.com")
totalValue = totalValue + getValue["result"]["Last"]*float(coins["balance"])*cadvalue
# If we are over the value we should transfer to exchange
if (getValue["result"]["Last"]*float(coins["balance"])*cadvalue) > transferLimit:
response = requests.post('http://tompool.org/ws/account/manualpayout', json={'apiKey':apiKey,"coinTypeCode":coins["coinTypeCode"]})
if response.status_code==200:
transferResult = response.json()
if transferResult["error"] == "None":
executions += "\n[%s] {'error':'%s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(transferResult["error"]))
else:
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),transferResult["message"])
else:
executions += "\n[%s] {'error':'code: %s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(response.status_code))
else:
# remove last two letters and try again
getValue = json.loads(json.dumps(bittrex.get_ticker("BTC-%s" % coins["coinTypeCode"][:3].upper())))
if(getValue["success"] == True):
comment += "\n{0:6} {1:15.10f} {2:15.10f} {3:15.10f} {4:15.10f} ${5:.2f} {6:18}".format(coins["coinTypeCode"].upper(),float(coins["unconfirmedBalance"]),float(coins["balance"]),getValue["result"]["Last"],getValue["result"]["Last"]*float(coins["balance"]),getValue["result"]["Last"]*float(coins["balance"])*cadvalue,"Bittrex.com")
totalValue = totalValue + getValue["result"]["Last"]*float(coins["balance"])*cadvalue
# If we are over the value we should transfer to exchange
if (getValue["result"]["Last"]*float(coins["balance"])*cadvalue) > transferLimit:
response = requests.post('http://tompool.org/ws/account/manualpayout', json={'apiKey':apiKey,"coinTypeCode":coins["coinTypeCode"]})
if response.status_code==200:
transferResult = response.json()
if transferResult["error"] == "None":
executions += "\n[%s] {'error':'%s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(transferResult["error"]))
else:
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),transferResult["message"])
else:
executions += "\n[%s] {'error':'code: %s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(response.status_code))
else:
found = False
for curCryptopia in cryptopia:
if curCryptopia["Label"] == "%s/BTC" % coins["coinTypeCode"].upper():
comment += "\n{0:6} {1:15.10f} {2:15.10f} {3:15.10f} {4:15.10f} ${5:.2f} {6:18}".format(coins["coinTypeCode"].upper(),float(coins["unconfirmedBalance"]),float(coins["balance"]),curCryptopia["LastPrice"],curCryptopia["LastPrice"]*float(coins["balance"]),curCryptopia["LastPrice"]*float(coins["balance"])*cadvalue,"Cryptopia.co.nz")
totalValue = totalValue + curCryptopia["LastPrice"]*float(coins["balance"])*cadvalue
# If we are over the value we should transfer to exchange
if (curCryptopia["LastPrice"]*float(coins["balance"])*cadvalue) > transferLimit:
response = requests.post('http://tompool.org/ws/account/manualpayout', json={'apiKey':apiKey,"coinTypeCode":coins["coinTypeCode"]})
if response.status_code==200:
transferResult = response.json()
if transferResult["error"] == "None":
executions += "\n[%s] {'error':'%s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(transferResult["error"]))
else:
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),transferResult["message"])
else:
executions += "\n[%s] {'error':'code: %s'}" % (time.strftime("%Y-%m-%d %H:%M:%S"),str(response.status_code))
found = True
break
if not found:
comment += "\n{0:6} {1:15.10f} {2:15.10f}".format(coins["coinTypeCode"].upper(),float(coins["unconfirmedBalance"]),float(coins["balance"]))
comment += "\n ---------"
comment += "\n ${0:.2f}".format(totalValue)
else:
comment += "{'error':'code: %s'}" % str(response.status_code)
exchangeBalances = ""
exchangeBalances += "\n{0:9} {1:15} {2:15} {3:12} {4:18}".format("Coin","Balance","Pending","Available","Market")
exchangeBalances += "\n---------------------------------------------------------------"
# Check bittrex for balances
data = json.loads(json.dumps(bittrex.get_balances()))
if(data["success"] == True):
for coins in data["result"]:
if float(coins["Balance"]) != 0.0 or float(coins["Pending"]) != 0.0:
exchangeBalances += "\n{0:6} {1:15.10f} {2:15.10f} {3:15.10f} {4:18}".format(coins["Currency"],coins["Balance"],coins["Pending"],coins["Available"],"Bittrex.com")
# Do I sell for BTC?
if float(coins["Available"]) != 0.0 and coins["Currency"].upper() != "BTC":
# Get the current price
getValue = json.loads(json.dumps(bittrex.get_ticker("BTC-%s" % coins["Currency"].upper())))
if(getValue["success"] == True) and (float(getValue["result"]["Last"])*float(coins["Available"]) > sellValueMin):
soldData = json.loads(json.dumps(bittrex.sell_limit( "BTC-%s" % coins["Currency"].upper(), coins["Available"], getValue["result"]["Last"])))
if(soldData["message"] != ""):
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),soldData["message"])
if(soldData["success"] == True):
executions += "\n[%s] Sold %s %s at %.10f [Bittrex.com]" % (time.strftime("%Y-%m-%d %H:%M:%S"),coins["Available"],coins["Currency"].upper(),getValue["result"]["Last"])
elif float(coins["Available"]) > 0.01 and coins["Currency"].upper() == "BTC":
# Transfer BTC out of exchange
getValue = json.loads(json.dumps(bittrex.withdraw("BTC", float("{0:.7f}".format(float(coins["Available"]) - bittrexTxFee)), bitcoinWallet)))
if(getValue["success"] == True):
if(getValue["message"] != ""):
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),getValue["message"])
else:
executions += "\n[%s] Transfered %s BTC from Bittrex.com" % (time.strftime("%Y-%m-%d %H:%M:%S"),float("{0:.7f}".format(float(coins["Available"]) - bittrexTxFee)))
# Check Cryptopia for balances
try:
data = json.loads(api_query("GetBalance"))
except Exception as e:
data = {'Success': False, 'Error': 'Could not access API'}
pass
if(data["Success"] == True):
for coins in data["Data"]:
if float(coins["Total"]) != 0.0 or float(coins["Unconfirmed"]) != 0.0:
exchangeBalances += "\n{0:6} {1:15.10f} {2:15.10f} {3:15.10f} {4:18}".format(coins["Symbol"],coins["Total"],coins["Unconfirmed"],coins["Available"],"Cryptopia.co.nz")
# Do I sell for BTC?
if float(coins["Available"]) != 0.0 and coins["Symbol"].upper() != "BTC":
# Get the current price
for curCryptopia in cryptopia:
if curCryptopia["Label"] == "%s/BTC" % coins["Symbol"].upper() and (float(curCryptopia["BidPrice"])*float(coins["Available"]) > sellValueMin):
# sell the coins
try:
soldData = json.loads(api_query("SubmitTrade", {'Market':'%s/BTC' % coins["Symbol"].upper(),'Type':'Sell','Rate':curCryptopia["BidPrice"],'Amount':coins["Available"]} ))
except Exception as e:
soldData = {'Success': False, 'Error': 'Could not access API'}
pass
if(soldData["Success"] == True):
executions += "\n[%s] Sold %s %s at %.10f [Cryptopia.co.nz]" % (time.strftime("%Y-%m-%d %H:%M:%S"),coins["Available"],coins["Symbol"].upper(),curCryptopia["BidPrice"])
else:
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),soldData["Error"])
break
elif float(coins["Available"]) > 0.01 and coins["Symbol"].upper() == "BTC":
# Transfer BTC out of exchange
try:
getValue = json.loads(api_query("SubmitWithdraw", {'Currency':'BTC','Address': bitcoinWallet,'Amount':float("{0:.7f}".format(coins["Available"]))} ))
except Exception as e:
getValue = {'Success': False, 'Error': 'Could not access API'}
pass
if(getValue["Success"] == True):
executions += "\n[%s] Transfered %s BTC from Cryptopia.co.nz" % (time.strftime("%Y-%m-%d %H:%M:%S"),float("{0:.7f}".format(coins["Available"])))
else:
executions += "\n[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"),getValue["Error"])
tmp = sp.call('clear',shell=True)
print comment
print ""
print "Balances at the Exchanges"
print exchangeBalances
print ""
print executions
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment