Convert API - python

Hi to all. I’m creating one simple bot for test purposes, where I would like to be able to convert between predefined cryptos. Like if am doing it manually.
I dont know what an doing wrong but i can not make it work. Funny part is that i have created one simple bot for trading and this works like a charm.
To be more exact, i am unable to convert between lets say, SOL and TRX because there is no pair ( the program is still working on trade logic ) but i can make convert between SOL and USDT because there is such pair available. So, i wont to avoid this trade and make simple convert, like if i would do it manualy. Is there some python example how to do this with binance convert API ?
Regards !

Hi, you want to create a simple bot that can convert between predefined cryptocurrencies using the Binance Convert API, rather than trading pairs directly available on the market?

First:

pip install requests

Then, here is a basic script to perform the conversion:

import requests
import json
import time
import hmac
import hashlib

# Your Binance API credentials
API_KEY = 'YOUR_API_KEY'
SECRET_KEY = 'YOUR_SECRET_KEY'

# Binance API endpoint for converting between cryptocurrencies
CONVERT_ENDPOINT = 'https://api.binance.com/sapi/v1/asset/convert'

# Function to create a signature
def create_signature(params, secret_key):
    query_string = '&'.join([f"{key}={params[key]}" for key in params])
    return hmac.new(secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

# Function to perform the conversion
def convert(from_asset, to_asset, amount):
    timestamp = int(time.time() * 1000)
    
    params = {
        'fromAsset': from_asset,
        'toAsset': to_asset,
        'amount': amount,
        'timestamp': timestamp
    }
    
    signature = create_signature(params, SECRET_KEY)
    headers = {
        'X-MBX-APIKEY': API_KEY
    }
    
    params['signature'] = signature
    
    response = requests.post(CONVERT_ENDPOINT, headers=headers, params=params)
    
    if response.status_code == 200:
        return response.json()
    else:
        return response.text

# Example usage
if __name__ == "__main__":
    from_asset = 'SOL'
    to_asset = 'TRX'
    amount = 1  # Amount of SOL to convert
    
    result = convert(from_asset, to_asset, amount)
    print(json.dumps(result, indent=4))

This script should help you perform conversions between predefined cryptocurrencies using the Binance Convert API.

Thank you for your reply. Yes, that’s exactly what i want to do. I filled the questionnaire and I got access to convert api but when I run it I get error:
Error getting quote: {‘code’: -1002, ‘msg’: ‘You are not authorized to execute this request.’}

According to your reply, it looks am using wrong approach. I will try your code and let you know in a day or two.

Best regards !

1 Like

Hi, I’m hitting a wall with the endpoint here. Tried ‘https://api.binance.com/sapi/v1/asset/convert’ but it keeps bouncing me out. Any alternatives?

Go to API Management and ensure that “Enable Spot & Margin Trading” is checked for the API key being used.
Additionally, make sure that IP restrictions (if set) are not blocking the requests. If the IP is restricted, they need to add their server IP to the list of allowed IPs.

Lets try with endpointPOST /sapi/v1/convert/getQuote. The /getQuote endpoint is used to get a quote for converting between two assets, and after getting the quote, they will need to call POST /sapi/v1/convert/acceptQuote to accept the conversion.

Try with this code:

import requests
import json
import time
import hmac
import hashlib

# Your Binance API credentials
API_KEY = 'YOUR_API_KEY'
SECRET_KEY = 'YOUR_SECRET_KEY'

# Binance API endpoints for conversion
QUOTE_ENDPOINT = 'https://api.binance.com/sapi/v1/convert/getQuote'
ACCEPT_ENDPOINT = 'https://api.binance.com/sapi/v1/convert/acceptQuote'

# Function to create a signature
def create_signature(params, secret_key):
   query_string = '&'.join([f"{key}={params[key]}" for key in params])
   return hmac.new(secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

# Function to get a conversion quote
def get_quote(from_asset, to_asset, amount):
   timestamp = int(time.time() * 1000)
   
   params = {
       'fromAsset': from_asset,
       'toAsset': to_asset,
       'amount': amount,
       'timestamp': timestamp
   }
   
   signature = create_signature(params, SECRET_KEY)
   headers = {
       'X-MBX-APIKEY': API_KEY
   }
   
   params['signature'] = signature
   
   response = requests.post(QUOTE_ENDPOINT, headers=headers, params=params)
   
   if response.status_code == 200:
       return response.json()
   else:
       return response.text

# Function to accept the quote and perform the conversion
def accept_quote(quote_id):
   timestamp = int(time.time() * 1000)
   
   params = {
       'quoteId': quote_id,
       'timestamp': timestamp
   }
   
   signature = create_signature(params, SECRET_KEY)
   headers = {
       'X-MBX-APIKEY': API_KEY
   }
   
   params['signature'] = signature
   
   response = requests.post(ACCEPT_ENDPOINT, headers=headers, params=params)
   
   if response.status_code == 200:
       return response.json()
   else:
       return response.text

# Example usage
if __name__ == "__main__":
   from_asset = 'SOL'
   to_asset = 'TRX'
   amount = 1  # Amount of SOL to convert
   
   # Step 1: Get a quote
   quote_result = get_quote(from_asset, to_asset, amount)
   print("Quote Result:", json.dumps(quote_result, indent=4))
   
   # Step 2: Accept the quote if successful
   if 'quoteId' in quote_result:
       quote_id = quote_result['quoteId']
       conversion_result = accept_quote(quote_id)
       print("Conversion Result:", json.dumps(conversion_result, indent=4))
   else:
       print("Failed to get quote:", quote_result)