def spin(coinbase_account, organisation_id, key, secret, dry_run): host = 'https://api2.nicehash.com' private_api = nicehash.private_api(host, organisation_id, key, secret, True) my_btc_account = private_api.get_accounts_for_currency("BTC") nh_balance = float(my_btc_account['available']) logger.info("Nicehash confirmed balance: %f mBTC", nh_balance * 1000) # Make withdrawl to coinbase withdraw_request_id = None if (nh_balance > 0.002): # Get address ids withdrawal_addresses = private_api.get_withdrawal_addresses( "BTC", 100, 0) print(withdrawal_addresses) for wa in withdrawal_addresses['list']: if wa["type"]["code"] == "COINBASE" and wa[ "address"] == coinbase_account: logger.info("Transferring %f BTC, to coinbase account: %s", nh_balance, coinbase_account) if (dry_run): break res = private_api.withdraw_request(wa["id"], nh_balance, "BTC") print(res) break
def getPaymentData(accounts): data = [] for account in secrets.accounts: orgId = account[0] try: private_api = nicehash.private_api('https://api2.nicehash.com', account[0], account[1], account[2]) response = private_api.request('GET', '/main/api/v2/mining/rigs/payouts', 'page=&size=100000', '') payments = response['list'] for p in payments: paymentid = p["id"] paymenttimestamp = p["created"] paymentamount = float(p["amount"]) paymentfee = float(p["feeAmount"]) total = paymentamount - paymentfee # print("ID {} - Date {} - Amount {:.8f} - Fee {:.8f} - Total {:.8f}".format(paymentid, paymenttimestamp, # paymentamount, paymentfee, # total)) data.append( "payouts,orgid={orgId} paymentid=\"{paymentid}\",paymentamount={paymentamount:.8f},paymentfee={paymentfee:.8f},total={total:.8f} {timestamp}" .format(orgId=orgId, paymentid=paymentid, paymentamount=paymentamount, paymentfee=paymentfee, total=total, timestamp=paymenttimestamp)) except Exception as int: print(int) return data
def __init__(self): self.api = private_api( 'https://api2.nicehash.com', nicehash_config['org_id'], nicehash_config['key'], nicehash_config['secret'] ) self.notification_text = ''
def API(start, end): api = nicehash.private_api(host="https://api2.nicehash.com", key=API_KEY, secret=API_SECRET, organisation_id=ORG_ID) params = "rigId=" + RIG_ID + "&algorithm=" + str(ALGO_CODE) + "&afterTimestamp=" + \ str(int(start.timestamp() * 1000)) + \ "&beforeTimestamp=" + str(int(end.timestamp() * 1000)) response = api.request( method="GET", path="/main/api/v2/mining/rig/stats/algo", query=params, body="") return response["data"]
pushover_client.send_message("Starting transfer from NiceHash to CoinSpot", title="Starting NiceHash to CoinSpot Transfer") atd.clear() next_run_date = (datetime.datetime.now().replace( day=1, hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(days=32)).replace(day=1) backup_job = atd.at("python3 /nicehash_auto_withdraw/nicehash_to_coinspot.py", next_run_date) pushover_client.send_message("Set backup job in case of crash", title="Backup Job") private_api = nicehash.private_api(config['nicehash']['host'], config['nicehash']['organisation_id'], config['nicehash']['api_key'], config['nicehash']['api_secret'], config['nicehash'].getboolean('verbose')) my_btc_account = private_api.get_accounts_for_currency("BTC") nh_balance = float(my_btc_account['available']) # print(nh_balance) pushover_client.send_message("NiceHash confirmed balance: " + str(nh_balance) + " BTC", title="NiceHash Balance") next_run = 30 success = False if nh_balance > config['nicehash'].getfloat('transfer_limit'):
#Starting web server print("Starting web server") processThread = threading.Thread(target=thread_second) # <- note extra ',' processThread.start() #Getting env variables apiKey = os.environ["api_key"] apiSecret = os.environ["api_secret"] organizationId = os.environ["organization_id"] print("Apikey :" +apiKey) print("apiSecret :" +apiSecret) print("organizationId :" +organizationId) host = "https://api2.nicehash.com" #setting up scrape time scrapeInterval = "15" #golder to save data scrapped from the api dataPath="data" #path of the request in the api path = "/main/api/v2/mining/rigs2" print("generating private_api session") private_api = nicehash.private_api(host, organizationId, apiKey, apiSecret) while True: print("Getting api result for :" + path) response = private_api.request("GET", path , '' , None ) result=json.dumps(response, indent=4, sort_keys=True) write_file(pathsys,"rig.json",result) time.sleep(scrapeInterval)
print(global_active_orders) # Buy info buy_info = public_api.buy_info() print(buy_info) # Get multialgo info multialgo_info = public_api.get_multialgo_info() print(multialgo_info) ############################################ # PRIVATE FUNCTIONS # Create private api object private_api = nicehash.private_api(host, organisation_id, key, secret, True) # Get balance for all currencies my_accounts = private_api.get_accounts() print(my_accounts) # Get balance for BTC address my_btc_account = private_api.get_accounts_for_currency(currencies['currencies'][0]['symbol']) print(my_btc_account) # Get my active hashpower orders my_top_active_x16r_eu_orders = private_api.get_my_active_orders('X16R', 'EU', 10) print(my_top_active_x16r_eu_orders) # Create pool new_pool = private_api.create_pool('My best pool', 'X16R', 'the.best.pool.com', 3333, 'mybestcoinaddress', 'x')
#!/usr/bin/python3 import requests import nicehash import time from pprint import pprint from nh_config import * nh_api = nicehash.private_api('https://api2.nicehash.com', nh_org_id, nh_api_key_code, nh_api_secret_key_code) def get_btc_to_local(local_currency): r = requests.get('https://paxful.com/rest/v1/currencies/' + local_currency).json() return r['data']['rate']['btc'] btc_price = get_btc_to_local(currency) def get_mining_info(): r = nh_api.request('GET', '/main/api/v2/mining/rigs2', '', '') totalRigs = r['totalRigs'] activeRigs = r['minerStatuses']['MINING'] btc_profitability = r['totalProfitability'] local_profitability = round( btc_profitability * btc_price - unmanaged_daily_electricity_cost, 2) return "%{u#fba342}%{+u}Rigs: " + f"{activeRigs}/{totalRigs}" + "%{O10}" + f"Profit: {local_profitability} {currency} / day" + "%{-u}"
sheet = service.spreadsheets() global row row = 7 global date date = datetime.date.today() #binance keys apikey = "APIKEY" secretkey = "SECRETKEY" #nicehash keys and declarations niceapikey = 'NICEHASHPUBLICKEY' nicesecretkey = 'NICEHASHPRIVATEKEY' host = 'https://api2.nicehash.com' private_api = nicehash.private_api(host, '', niceapikey, nicesecretkey, True) btcbalance = private_api.get_accounts_for_currency('BTC')['totalBalance'] global fbalance client = Client(apikey, secretkey) fbalance = client.futures_account_balance()[0]['balance'] #use historical trade data, write to sheet and calculate average pNl per trade, maybe median? some kind of averadgeing. weighted average? def req(client,priv): global row global date global fbalance #requests price r = requ.get('https://api.coindesk.com/v1/bpi/currentprice.json', auth=('user','pass')) i = json.loads(r.text) price = i['bpi']['USD']['rate_float']
def updateDisplay(config,pricestack,whichcoin,fiat,other): """ Takes the price data, the desired coin/fiat combo along with the config info for formatting if config is re-written following adustment we could avoid passing the last two arguments as they will just be the first two items of their string in config """ days_ago=int(config['ticker']['sparklinedays']) symbolstring=currency.symbol(fiat.upper()) if fiat=="jpy" or fiat=="cny": symbolstring="¥" pricenow = pricestack[-1] currencythumbnail= 'currency/'+whichcoin+'.bmp' tokenfilename = os.path.join(picdir,currencythumbnail) sparkbitmap = Image.open(os.path.join(picdir,'spark.bmp')) ATHbitmap= Image.open(os.path.join(picdir,'ATH.bmp')) # Check for token image, if there isn't one, get on off coingecko, resize it and pop it on a white background if os.path.isfile(tokenfilename): logging.info("Getting token Image from Image directory") tokenimage = Image.open(tokenfilename).convert("RGBA") else: logging.info("Getting token Image from Coingecko") tokenimageurl = "https://api.coingecko.com/api/v3/coins/"+whichcoin+"?tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false" rawimage = requests.get(tokenimageurl).json() tokenimage = Image.open(requests.get(rawimage['image']['large'], stream=True).raw).convert("RGBA") resize = 100,100 tokenimage.thumbnail(resize, Image.ANTIALIAS) new_image = Image.new("RGBA", (120,120), "WHITE") # Create a white rgba background with a 10 pixel border new_image.paste(tokenimage, (10, 10), tokenimage) tokenimage=new_image tokenimage.thumbnail((100,100),Image.ANTIALIAS) tokenimage.save(tokenfilename) pricechange = str("%+d" % round((pricestack[-1]-pricestack[0])/pricestack[-1]*100,2))+"%" if pricenow > 1000: pricenowstring =format(int(pricenow),",") else: pricenowstring =str(float('%.5g' % pricenow)) if config['display']['orientation'] == 0 or config['display']['orientation'] == 180 : epd = epd2in13_V2.EPD() epd.init(epd.FULL_UPDATE) image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((110,80),str(days_ago)+"day :",font =font_date,fill = 0) draw.text((110,95),pricechange,font =font_date,fill = 0) # Print price to 5 significant figures draw.text((15,200),symbolstring+pricenowstring,font =font,fill = 0) draw.text((10,10),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0) image.paste(tokenimage, (10,25)) image.paste(sparkbitmap,(10,125)) if config['display']['orientation'] == 180 : image=image.rotate(180, expand=True) if config['display']['orientation'] == 90 or config['display']['orientation'] == 270 : epd = epd2in13_V2.EPD() epd.init(epd.FULL_UPDATE) image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) draw.text((135,85),str(days_ago)+" day : "+pricechange,font =font_date,fill = 0) #mining if config['mining']['enabled'] == True : host = 'https://api2.nicehash.com' #host connection organisation_id = str(config['mining']['organisation']) #organisation string key = str(config['mining']['key']) #public key string secret = str(config['mining']['secret']) #secret key string private_api = nicehash.private_api(host, organisation_id, key, secret) if config['mining']['display'] == "wallet,unpaid" or config['mining']['display'] == "wallet" : accounts = private_api.get_accounts() #get accounts json accountsdata = str(accounts['total']) #grab totals accountslist = accountsdata.split("'") #organize wallet = float(accountslist[7]) #isolate total balance currencydata = str(accounts['currencies']) currencylist = currencydata.split(":") rate = float('{:.8}'.format(currencylist[7])) total = wallet*rate balance = float('{:.2f}'.format(total)) if config['mining']['walletcurrency'] == "btc" : draw.text((100,13),"Wallet: "+str(wallet)+" BTC",font =font_mining2,fill = 0) #draw wallet balance if config['mining']['walletcurrency'] == "cad" : draw.text((100,13),"Wallet: $"+str(balance),font =font_mining,fill = 0) if config['mining']['display'] == "unpaid,wallet" or config['mining']['display'] == "unpaid" : unpaid = private_api.get_unpaid() #get unpaid json strdata = str(unpaid['data']) #grab "data" section and convert to string listdata = strdata.split(",") #organize maybe = float(listdata[2]) #grab total unpaid almost = format(float(maybe), '.8f') #convert form scientific to decimal float working = decimal.Decimal(almost) #convert from float to decimal ok = working * 100000000 #make whole number final = int(ok) #convert to integer to drop decimals draw.text((100,13),"Unpaid NH: "+str(final)+" Sat",font =font_mining,fill = 0) #draw unpaid mining #end mining #. uncomment the line below to show volume # draw.text((110,105),"24h vol : " + human_format(other['volume']),font =font_date,fill = 0) if config['ticker']['coinname'] == True : draw.text((100,100),symbolstring+pricenowstring+"/"+whichcoin,font =fontHorizontal,fill = 0) else: draw.text((135,100),symbolstring+pricenowstring,font =fontHorizontal,fill = 0) if other['ATH']==True: image.paste(ATHbitmap,(190,85)) image.paste(sparkbitmap,(80,25)) image.paste(tokenimage, (0,10)) # draw.text((5,110),"Inretrospect, it was inevitable",font =font_date,fill = 0) draw.text((95,1),str(time.strftime("%H:%M %a %d %b %Y")),font =font_date,fill = 0) if config['display']['orientation'] == 270 : image=image.rotate(180, expand=True) # This is a hack to deal with the mirroring that goes on in 4Gray Horizontal # image = ImageOps.mirror(image) # If the display is inverted, invert the image usinng ImageOps if config['display']['inverted'] == True: image = ImageOps.invert(image) # Send the image to the screen epd.display(epd.getbuffer(image))
def get_price(): data = public_api.get_current_prices() return data["BTCUSDC"] * config.USD_EUR def utc_to_local(utc): epoch = time.mktime(utc.timetuple()) offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch) return utc + offset # Create public api object public_api = nicehash.public_api(False) # Create public api object private_api = nicehash.private_api(False) if config.RUN_EMULATOR: imageEncoding = 'RGB' else: imageEncoding = '1' # Raspberry Pi pin configuration: RST = None # on the PiOLED this pin isnt used # Note the following are only used with SPI: DC = 24 SPI_PORT = 0 SPI_DEVICE = 0 # 128x32 display with hardware SPI: disp = SSD1305.SSD1305_128_32(rst=RST, dc=DC,
def getRigData(accounts): data = [] for account in accounts: orgId = account[0] try: private_api = nicehash.private_api('https://api2.nicehash.com', account[0], account[1], account[2]) response = private_api.request('GET', '/main/api/v2/mining/rigs2', '', '') except Exception as inst: print(inst) continue # j_rigs = json.loads(response.content) rigs = response['miningRigs'] for r in rigs: rigId = r['rigId'] rigName = r['name'] rigProfit = round(Decimal(r['profitability']), 8) rigLocalProfit = round(Decimal(r['localProfitability']), 8) print('Rig {} ({}) - Profit : {} - LocalProfit : {} '.format( rigId, rigName, rigProfit, rigLocalProfit)) rigTotalSpeed = float(0.0) for d in r['devices']: name = d['name'] deviceId = d['id'] vram = d['temperature'] / 65536 gpu = d['temperature'] % 65536 deviceType = d['deviceType']['enumName'] speed = 0.0 speeds = d['speeds'] if len(speeds) == 1: speed = Decimal(speeds[0]['speed']) if speeds[0]['displaySuffix'] == 'MH': speed = speed * 1000000 elif speeds[0]['displaySuffix'] == 'KH': speed = speed * 1000 rigTotalSpeed += float(speed) print('\tCard {} : VRAM {} : GPU {} : Speed: {} '.format( name, vram, gpu, speed)) data.append( "devices,name='{name}',rigid={rigId},deviceid={deviceId},orgid={orgId},devicetype={deviceType} gpu_temperature={gpu},vram_temperature={vram},speed={speed}" .format(name=name.replace(' ', '\ '), rigId=rigId, deviceId=deviceId, orgId=orgId, gpu=gpu, vram=vram, speed=float(speed), deviceType=deviceType)) data.append( "rigs,id={rigId},name={rigName},orgid={orgId} profit={rigProfit},localprofit={rigLocalProfit},totalspeed={rigTotalSpeed}" .format(orgId=orgId, rigId=rigId, rigName=rigName, rigProfit=rigProfit, rigTotalSpeed=rigTotalSpeed, rigLocalProfit=rigLocalProfit)) return data