Skip to content

Instantly share code, notes, and snippets.



Forked from jat001/
Created Feb 22, 2020
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
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():
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('')
# 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('', 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 ='', 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.')
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.')
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)
except Exception as e:
prin(e, file=sys.stderr)
i += 1
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment