Step by Step Guide on How to Integrate ChangeNOW API

Written by edwardmoon | Published 2024/03/18
Tech Story Tags: changenow-api | how-to-integrate-api | instant-crypto-exchange-api | api-integration | cryptocurrency | changenow-api-key | how-to-integrate-changenow-api | cryptoexchange

TLDRThis guide walks you through integrating the ChangeNOW cryptocurrency exchange API into your application using Python. It covers signing up for an API key, setting up your environment, authenticating requests, retrieving available currency pairs, checking exchange amounts, estimating rates, creating transactions, and monitoring their status. Code examples are provided for each step.via the TL;DR App

Unlike traditional centralized exchanges, instant crypto exchanges allow users to trade cryptocurrencies directly from their wallets, without the need to deposit funds into an exchange account. Also, many of them help to exchange crypto between different blockchains.

Integrating instant crypto exchange functionality into applications through APIs opens up new possibilities for developers. By using these APIs, developers can offer their users the ability to seamlessly swap between cryptocurrencies without leaving the application. This eliminates the need for users to navigate multiple platforms and chains providing access to a wide range of trading pairs. And of course APIs allow developers to benefit from exchange fees, creating a new revenue stream for their applications.

In this article, I will explore the process of integrating a ChangeNow API into an application. I will cover the essential steps, including obtaining an API key, authenticating requests, retrieving available trading pairs, executing trades, and monitoring transaction status.

By the end of this guide, you'll have a clear understanding of how to leverage such APIs to add powerful trading capabilities to your application.

So, let's dive in?

Step 1: Sign Up for a ChangeNOW API Key

To get started with the ChangeNOW API, you first need to sign up for an API key. This key will be used to authenticate your API requests and ensure secure access to the ChangeNOW exchange services.

  • Navigate to the ChangeNOW crypto exchange API page and click on the "Start your integration" button.
  • Fill in the required information, such as your email address and password, to create a new account.
  • Once you have successfully created an account, log in to your ChangeNOW account dashboard.
  • In the account dashboard, locate the "API" section. This is where you can manage your API keys and access the necessary information for integrating the ChangeNOW API into your application.
  • Click on the "Generate New API Key" button to create a new API key. You may be prompted to provide additional information or verify your account before proceeding.

After successfully generating a new API key, you will see it displayed in the API section of your account dashboard. Make sure to copy and store this API key securely, as you will need it for authenticating your API requests.

With your ChangeNOW API key generated, you are now ready to proceed to the next step of setting up your development environment and starting to integrate the ChangeNOW API into your application.

Remember to keep your API key confidential and avoid sharing it with others. If you suspect that your API key has been compromised, you can always generate a new one from your account dashboard and update your application accordingly.

Step 2: Set Up Your Development Environment

Before you start integrating the ChangeNOW API into your application, you need to set up your development environment. This involves choosing a programming language and an Integrated Development Environment (IDE) that you are comfortable with, and installing the necessary libraries for making HTTP requests.

For this guide, I will provide examples in Python.

  • Install Python on your machine if you haven't already. You can download the latest version of Python from the official website and follow the installation instructions for your operating system.

  • Choose an IDE for Python development. Some popular options include PyCharm, Visual Studio Code, and Sublime Text.

  • Install the requests library, which is a popular library for making HTTP requests in Python. You can install it using pip, the package installer for Python, by running the following command in your terminal or command prompt:

pip install requests

  • Create a new Python file in your IDE and import the requests library at the top of your file:

import requests

With your development environment set up and the necessary libraries installed, you are now ready to start making API requests to the ChangeNOW API.

Step 3: Authenticate Your API Requests

To authenticate your API requests and ensure secure communication with the ChangeNOW API, you need to include your API key in the x-changenow-api-key header of each request. This header tells the ChangeNOW API that you are an authorized user and grants you access to the API endpoints.

Here's how you can set the API key header in Python:

import requests

api_key = 'YOUR_API_KEY'  # Replace with your actual API key

headers = { 'x-changenow-api-key': api_key }

response = requests.get('https://api.changenow.io/v1/endpoint', headers=headers)

Replace 'YOUR_API_KEY' with the actual API key you obtained in Step 1.

The headers object is created with the x-changenow-api-key header set to your API key. This header is then included in the API request using the headers parameter of the requests.get() method.

By including the API key header in each request, you authenticate yourself as an authorized user of the ChangeNOW API. The API server will validate your API key and grant access to the requested endpoints if the key is valid.

Step 4: Retrieve Available Currency Pairs

To start using the ChangeNOW API, you need to know which currency pairs are available for exchange. The ChangeNOW API provides an endpoint to retrieve the list of available currency pairs.

To retrieve the available currency pairs, you need to make a GET request to the /v1/market-info/available-pairs/ endpoint. Here's how you can send the request and parse the response:

import requests

api_key = 'YOUR_API_KEY'

headers = {

'x-changenow-api-key': api_key }

response = requests.get('https://api.changenow.io/v1/market-info/available-pairs/', headers=headers)

if response.status_code == 200:

available_pairs = response.json()

print("Available currency pairs:")

for pair in available_pairs: print(pair) 

else: print(f"Error: {response.status_code}")

The code sends a GET request to the /v1/market-info/available-pairs/ endpoint, including the API key in the x-changenow-api-key header for authentication.

If the request is successful (status code 200), the response will contain a JSON array of available currency pairs. The code then parses the response and extracts the list of currency pairs.

The response.json() method is used to parse the JSON response into a Python list. The code then iterates over the list and prints each currency pair.

If the request fails, the code prints an error message along with the status code.

By retrieving the available currency pairs, you can provide your users with the options to choose from when performing an exchange.

Step 5: Check Minimum and Maximum Exchange Amounts

Before performing an exchange, it's important to know the minimum and maximum amounts allowed for a specific currency pair. The ChangeNOW API provides an endpoint to retrieve this information.

To check the minimum and maximum exchange amounts, you need to make a GET request to the /v2/exchange/range endpoint, providing the required parameters: fromCurrency and toCurrency.

Here's how you can construct the request URL with query parameters and parse the response:

import requests

api_key = 'YOUR_API_KEY'

headers = { 'x-changenow-api-key': api_key }

from_currency = 'btc'  # Replace with the source currency

to_currency = 'eth'    # Replace with the target currency

url = f'https://api.changenow.io/v2/exchange/range?fromCurrency={from_currency}&toCurrency={to_currency}'

response = requests.get(url, headers=headers)

if response.status_code == 200:

data = response.json() 

min_amount = data['minAmount'] 

max_amount = data['maxAmount'] 

print(f"Minimum exchange amount: {min_amount}") 

print(f"Maximum exchange amount: {max_amount}") 

else: print(f"Error: {response.status_code}")

Set the fromCurrency and toCurrency variables to the desired source and target currencies, respectively.

The code constructs the request URL by appending the fromCurrency and toCurrency parameters as query parameters to the /v2/exchange/range endpoint URL.

It then sends a GET request to the constructed URL, including the API key in the x-changenow-api-key header for authentication.

If the request is successful (status code 200), the response will contain a JSON object with the minAmount and maxAmount fields. The code parses the response and extracts these values.

Tthe response.json() method is used to parse the JSON response into a Python dictionary. The minAmount and maxAmount values are then accessed and printed.

By checking the minimum and maximum exchange amounts, you can ensure that the user's requested exchange amount falls within the allowed range for the selected currency pair.

Step 6: Estimate Exchange Amounts

Before proceeding with an exchange, you may want to provide an estimate of the exchange amount to the user based on their input. The ChangeNOW API offers an endpoint to estimate the exchange amount for a given currency pair and amount.

To estimate the exchange amount, you need to make a GET request to the /v2/markets/estimate endpoint, providing the required parameters: fromCurrency, toCurrency, fromAmount or toAmount, and type.

Here's how you can build the request URL, send the request, and handle the response:

import requests

api_key = 'YOUR_API_KEY'

headers = { 'x-changenow-api-key': api_key }

from_currency = 'btc'   # Replace with the source currency

to_currency = 'eth'     # Replace with the target currency 

from_amount = 1.5       # Replace with the source amount

url = f'https://api.changenow.io/v2/markets/estimate?fromCurrency={from_currency}&toCurrency={to_currency}&fromAmount={from_amount}&type=direct'

response = requests.get(url, headers=headers)

if response.status_code == 200:

data = response.json() 

estimated_amount = data['toAmount'] 

print(f"Estimated exchange amount: {estimated_amount} {to_currency}") 

else: print(f"Error: {response.status_code}")

Set the fromCurrency, toCurrency, and fromAmount variables to the desired source currency, target currency, and source amount.

The code builds the request URL by appending the fromCurrency, toCurrency, fromAmount, and type parameters as query parameters to the /v2/markets/estimate endpoint URL.

It then sends a GET request to the constructed URL, including the API key in the x-changenow-api-key header for authentication.

If the request is successful (status code 200), the response will contain a JSON object with the estimated exchange amount in the toAmount field. The code parses the response and extracts the estimated amount.

The response.json() method is used to parse the JSON response into a Python dictionary. The toAmount value is then accessed and printed along with the target currency.

If the request fails, the code prints an error message along with the status code.

By estimating the exchange amount, you can provide the user with an idea of how much they will receive in the target currency based on their input amount in the source currency.

Step 7: Create an Exchange Transaction

Once the user has provided the necessary information, such as the source and target currencies, the amount to exchange, and the destination address, you can create an exchange transaction using the ChangeNOW API.

To create an exchange transaction, you need to make a POST request to the /v2/exchange/refund endpoint, including the required parameters in the request body: id, address, and extraId (if applicable).

Here's how you can construct the request payload, send the POST request, and handle the API response:

import requests

api_key = 'YOUR_API_KEY'

headers = { 'x-changenow-api-key': api_key, 'Content-Type': 'application/json' }

transaction_id = 'YOUR_TRANSACTION_ID'  # Replace with the actual transaction ID

refund_address = 'YOUR_REFUND_ADDRESS'  # Replace with the actual refund address 

extra_id = 'YOUR_EXTRA_ID'  # Replace with the actual extra ID (if applicable)

payload = {

'id': transaction_id, 

'address': refund_address, 

'extraId': extra_id 

}

response = requests.post('https://api.changenow.io/v2/exchange/refund', headers=headers, json=payload)

if response.status_code == 200:

data = response.json() 

refund_status = data['result'] 

print(f"Refund status: {refund_status}") 

else: print(f"Error: {response.status_code}")

Set the transactionId, refundAddress, and extraId variables to the appropriate values for the exchange transaction.

The code constructs the request payload as a JSON object containing the id, address, and extraId fields.

It then sends a POST request to the /v2/exchange/refund endpoint, including the API key in the x-changenow-api-key header and the payload in the request body.

If the request is successful (status code 200), the response will contain a JSON object indicating the refund status in the result field. The code parses the response and extracts the refund status.

The response.json() method is used to parse the JSON response into a Python dictionary. The result value is then accessed and printed.

By creating an exchange transaction, you initiate the process of exchanging the user's funds from the source currency to the target currency. The API will handle the exchange process and send the exchanged funds to the specified destination address.

Step 8: Monitor Transaction Status

After creating an exchange transaction, you can monitor its status to keep track of the progress and provide updates to the user. The ChangeNOW API allows you to retrieve the status and details of transactions using the /v2/exchanges endpoint.

To monitor the status of a transaction, you need to make a GET request to the /v2/exchanges endpoint. You can optionally include query parameters to filter and sort the transactions.

Here's how you can build the request URL with query parameters, send the request, and parse the response to retrieve transaction details and status:

import requests

api_key = 'YOUR_API_KEY'  # Replace with your actual API key

headers = { 'x-changenow-api-key': api_key }

url = 'https://api.changenow.io/v2/exchanges?limit=10&offset=0&sortField=createdAt&sortDirection=DESC'

response = requests.get(url, headers=headers)

if response.status_code == 200:

data = response.json() 

transactions = data['exchanges'] 

for transaction in transactions: 

transaction_id = transaction['requestId'] 

status = transaction['status'] 

print(f"Transaction ID: {transaction_id}, Status: {status}") 

else: print(f"Error: {response.status_code}")

The code builds the request URL with optional query parameters. In this example, the limit parameter is set to 10 to retrieve a maximum of 10 transactions, the offset parameter is set to 0 to start from the beginning, the sortField parameter is set to 'createdAt' to sort the transactions by creation date, and the sortDirection parameter is set to 'DESC' to sort in descending order.

It then sends a GET request to the /v2/exchanges endpoint, including the API key in the x-changenow-api-key header for authentication.

If the request is successful (status code 200), the response will contain a JSON object with an array of transactions in the exchanges field. The code parses the response and iterates over the transactions.

The response.json() method is used to parse the JSON response into a Python dictionary. The code then iterates over the exchanges array and prints the transaction ID and status for each transaction.

By monitoring the transaction status, you can keep track of the progress of the exchange and provide relevant updates to the user. You can periodically poll the API to fetch the latest status of the transaction until it reaches a final state (e.g., "finished" or "failed").

Congratulations!

You have successfully learned how to set up and use the ChangeNOW API to integrate cryptocurrency exchange functionality into your application.

If you have any problems or need further assistance while implementing the ChangeNOW API, please feel free to leave a comment below.

There are many guides on HackerNoon, but you'd like to see a similar step-by-step guide for integrating any other API into your application, let me know in the comments section.

Keep exploring, keep learning, and happy coding!


Written by edwardmoon | Software developer
Published by HackerNoon on 2024/03/18