If you would like to onboard with your wallet private key and generate a set of API key and secrets programmatically instead of from the frontend, you can retrieve your account API key and secret by calling the onboarding endpoint and signing a message with your wallet private key. However, note that this method is generally not recommended. Github example here.
Your wallet private key is used to onboard and retrieve a set of API key and secrets.
First call the /onboarding endpoint such as in the example below. Save the response API key and secret to be used for signing private endpoint requests.
expires must be less than or equal to 600 seconds.
from eth_account.messages import encode_defunct
from hexbytes import HexBytes
from web3.auto import w3
from datetime import datetime
import requests
onboarding_message = 'Welcome to Bfx!\n\nClick to sign in and on-board your wallet for trading perpetuals.\n\nThis request will not trigger a blockchain transaction or cost any gas fees. This signature only proves you are the true owner of this wallet.\n\nBy signing this message you agree to the terms and conditions of the exchange.'
url = 'https://api.bfx.trade'
private_key = '<YOUR WALLET PRIVATE KEY>'
wallet = '<YOUR WALLET ADDRESS>'
expires = 600
session = requests.Session()
def _expiration_timestamp():
return int(datetime.now().timestamp() + expires)
def _header() -> dict:
expiration_timestamp = _expiration_timestamp()
return {'RBT-TS': str(expiration_timestamp), 'EID':'bfx'}
def hex2bytes(value: str) -> bytes:
if value.startswith('0x'):
value = value[2:]
return bytes.fromhex(value)
def metamask_sign(message, timestamp: int, private_key: str):
private_key = hex2bytes(private_key)
metamask_message = f'{message}\n{timestamp}'
message = encode_defunct(metamask_message.encode())
signed_message = w3.eth.account.sign_message(message, private_key=private_key)
return signed_message.signature.hex()
def _prepare_signature(private_key) -> str:
expiration_timestamp = _expiration_timestamp()
signature = metamask_sign(onboarding_message, expiration_timestamp, private_key)
signature = bytearray(hex2bytes(signature))
signature[-1] = signature[-1] % 27
return '0x' + signature.hex()
def onboard(private_key: str) -> dict:
signature = _prepare_signature(private_key)
data = dict(wallet=wallet, signature=signature, isClient=False)
resp = session.post(f'{url}/onboarding', json=data, headers=_header()).json()
return resp
if __name__ == '__main__':
onboarding_resp = onboard(private_key)
api_secret = onboarding_resp['result'][0]['apiSecret']['Secret']
Note: onboarding message
Welcome to Bfx!\n\nClick to sign in and on-board your wallet for trading perpetuals.\n\nThis request will not trigger a blockchain transaction or cost any gas fees. This signature only proves you are the true owner of this wallet.\n\nBy signing this message you agree to the terms and conditions of the exchange.