Skip to content

Instantly share code, notes, and snippets.

@meoww-bot meoww-bot/namebase.py

forked from jat001/namebase.py
Created Feb 22, 2020
Embed
What would you like to do?
Sell HNS automatically
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from decimal import Decimal
from datetime import datetime
try:
import requests
import simplejson as json
except ImportError:
raise ImportError('You must install requests and simplejson first!')
namebase_cookie = 's:'
btc_address = 'bc1q3hkc265vxqu8dk4dkk68sf607086vmckwm2z6e'
# The unit of expect_prices is mBTC! 1 BTC = 1,000 mBTC. the smallest unit of mBTC is 1e−5
expect_prices = [
# min unit price (mBTC per HNS), max unit price (mBTC per HNS), the amount of HNS to sell
('0.02', 999, 5000),
(0, '0.005', 3000),
('0.018', '0.01999', 2000),
]
reserve_amount = 500
def time():
return datetime.now().isoformat()
def normalize(d):
return '{:f}'.format(d.normalize())
def prin(*args, **kwargs):
args = [normalize(arg) if isinstance(arg, Decimal) else arg for arg in args]
return print(time(), *args, **kwargs)
def get_hns_balance(s):
r = s.get('https://www.namebase.io/api/user')
# Format: str Unit: μHNS
balance = Decimal(r.json()['hns_balance']) / 1000 / 1000
prin('You have', balance, 'HNS.')
return balance
def get_current_price(s, p):
r = s.get('https://www.namebase.io/api/exchange/sell', timeout=2)
# Format: float Unit: BTC
price = r.json(use_decimal=True)['price'] * 1000
if p:
prin('Current price is', price, 'mBTC.')
return price
def sell_hns(amount, s):
r = s.post('https://www.namebase.io/api/exchange/trade/hns/btc', json={
'address': btc_address,
'amount': normalize(amount * 1000 * 1000),
})
# {'success': bool, 'txHash': str, 'baseAmount': str HNS, 'quoteAmount': str BTC, 'user': {'hns_balance': str μHNS}}
# {'errorCode': str, 'errorData': dict}
res = r.json()
if 'success' in res and res['success']:
balance = Decimal(res['user']['hns_balance']) / 1000 / 1000
prin('Sold', Decimal(res['baseAmount']), 'HNS for', Decimal(res['quoteAmount']) / 1000, 'mBTC.',
'You have', balance, 'HNS left.')
else:
prin('Sell HNS failed:', 'errorCode' in res and res['errorCode'] or 'UnknownError', file=sys.stderr)
balance = get_hns_balance(s)
return balance
def run():
with requests.Session() as s:
requests.utils.add_dict_to_cookiejar(s.cookies, {
'namebase-main': namebase_cookie,
})
balance = get_hns_balance(s)
reserved = Decimal(reserve_amount)
i = 0
while True:
if balance <= reserved:
prin('The reserve amount is', reserved, 'HNS, but you only have', balance, 'HNS.')
break
try:
price = get_current_price(s, i % 10 == 0)
for inx, (min_price, max_price, amount) in enumerate(expect_prices):
if Decimal(min_price) <= price <= Decimal(max_price):
amount = Decimal(amount)
if amount > balance:
amount = balance
if balance - amount < reserved:
amount = balance - reserved
prin('Selling', amount, 'HNS for', price, 'mBTC each.')
balance = sell_hns(amount, s)
expect_prices.pop(inx)
break
except Exception as e:
prin(e, file=sys.stderr)
i += 1
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.