import requests # pip install requests import json import base64 import hashlib import hmac import os import time #for nonce class BitfinexClient(object): BASE_URL = "https://api.bitfinex.com/" KEY = "6ccbcfc02d524c4d18183c89b6ee03dd92a7d120940" SECRET = "3f18b1113f4f06494764cae7167b467c456ad65e686" def _nonce(self): # Returns a nonce # Used in authentication return str(int(round(time.time() * 10000))) def _headers(self, path, nonce, body): secbytes = self.SECRET.encode(encoding='UTF-8') signature = "/api/" + path + nonce + body sigbytes = signature.encode(encoding='UTF-8') h = hmac.new(secbytes, sigbytes, hashlib.sha384) hexstring = h.hexdigest() return { "bfx-nonce": nonce, "bfx-apikey": self.KEY, "bfx-signature": hexstring, "content-type": "application/json" } def req(self, path, params = {}): nonce = self._nonce() body = params rawBody = json.dumps(body) headers = self._headers(path, nonce, rawBody) url = self.BASE_URL + path print(rawBody) resp = requests.post(url, headers=headers, data=rawBody, verify=True) return resp def active_orders(self): # Fetch active orders response = self.req("v2/auth/r/orders") if response.status_code == 200: return response.json() else: print('error, status_code = ', response.status_code) return '' def wallets(self): response = self.req("v2/auth/r/wallets") if response.status_code == 200: return response.json() else: print('error, status_code = ', response.status_code) return '' def get_btc_amount(self): wallets = self.wallets() btc_wallet = None for wallet in wallets: if wallet[1] == "TESTBTC": btc_wallet = wallet break else: print("Error, no BTC wallet found") return -1, -1 btc_amount = btc_wallet[4] return btc_amount def sell_all_btc(self): btc_amount = self.get_btc_amount() params = { "type": "EXCHANGE MARKET", "symbol": "tTESTBTC:TESTUSD", "amount": "-" + str(btc_amount), #"price": "1000", } response = self.req("v2/auth/w/order/submit", params=params) print(response) print(response.text) return response client = BitfinexClient() result = client.wallets() for r in result: print(r) result = client.get_btc_amount() print(result) result = client.sell_all_btc() print(result)