bkmeneguello
12/8/2015 - 5:06 PM

Uphold autobuy BOT

Uphold autobuy BOT

from uphold import Uphold
from time import sleep, time
from tinydb import TinyDB

api = Uphold()
api.auth_pat(<PAT_KEY>)

db = TinyDB('/tmp/db.json')

usd_card = <USD_CARD_ID>
btc_card = <BTC_CARD_ID>

def wma(count):
  if len(db) >= count:
    return reduce(lambda x,y: x + y['ask'], db.all()[-count::], 0) / count
  elif len(db) > 0:
    return db.all()[-1]['ask']
  else:
    return 0

last_quote = None

while True:
  ticker = api.get_ticker('BTCUSD')
  eid = db.insert({
    'time': int(time() * 1000),
    'ask': float(ticker['ask']),
    'bid': float(ticker['bid']),
    'wma20': wma(20),
    'wma100': wma(100)
  })
  
  quote = db.get(eid=eid)
  if quote['wma20'] > quote['wma100']: #Buy time?
    if last_quote is not None and last_quote['wma20'] <= last_quote['wma100']:
      #Buy time!!!
      amount = api.get_card(usd_card)['available']
      if float(amount) > 0:
        txn_id = api.prepare_txn(usd_card, btc_card, amount, 'USD')
        txn = api.execute_txn(usd_card, txn_id)
        if txn['status'] == 'completed':
          print("%s USD to %s BTC" % (txn['origin']['amount'], txn['destination']['amount']))
        else:
          print("transaction failed!")
  elif quote['wma20'] < quote['wma100']: #Sell time?
    if last_quote is not None and last_quote['wma20'] >= last_quote['wma100']:
      #Sell time!!!
      amount = api.get_card(btc_card)['available']
      if float(amount) > 0:
        txn_id = api.prepare_txn(btc_card, usd_card, amount, 'BTC')
        txn = api.execute_txn(btc_card, txn_id)
        if txn['status'] == 'completed':
          print("%s BTC to %s USD" % (txn['origin']['amount'], txn['destination']['amount']))
        else:
          print("transaction failed!")
          
  last_quote = quote
  
  sleep(60)