Streamline Your Trading Experience
Discover the power of CoinSwitch PRO API trading for spot exchanges! This comprehensive guide will help you leverage our API to automate your trades, access real-time crypto rates, and create seamless integrations for your trading experience.
Our REST API is structured with user-friendly endpoints, giving you easy access to essential market data and exchange status information. We also provide private authenticated endpoints for advanced features such as trading and user-specific data. These endpoint requests need to be signed, for enhanced security and protection for your transactions.
Setting up an API Key
To fully utilize certain endpoints, you'll need an API key and a secret Key. You can generate this key pair on your CoinSwitch PRO Profile
In case you face any issues, please email your API key generation request to us at api@coinswitch.co. This step ensures an added layer of protection for your account and data.
Remember: Never share your API key or secret key with anyone. If your API keys have been unintentionally shared, we urge you to promptly delete them and generate a fresh key to maintain the highest level of security.
You can only have one API and one secret key active at a time.
Contact us
You can reach out to us at api@coinswitch.co in case of any queries/suggestions
Information about our APIs
At CoinSwitch PRO, our base endpoint for API calls is https://coinswitch.co. All our endpoints provide responses in the form of JSON objects or arrays, ensuring easy integration with your applications.
To maintain consistency, all time and timestamp related fields within our API follow a standardized format of milliseconds. This precision allows for accurate calculations and seamless data synchronization.
In each of the APIs we need the following headers :
Header | Value |
---|---|
Content-Type | application/json |
X-AUTH-SIGNATURE | Singature that you need to generate at your end |
X-AUTH-APIKEY | API key provided by Coinswitch |
Signature Generation
To access CoinSwitch APIs you need to generate signature and pass it as header in each and every API call.
from cryptography.hazmat.primitives.asymmetric import ed25519
from urllib.parse import urlparse, urlencode
import urllib
import json
# example method ['GET', 'POST', 'DELETE']
# params represent the query params we need to pass during GET call
def get_signature(method, endpoint, payload, params):
unquote_endpoint = endpoint
if method == "GET" and len(params) != 0:
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
unquote_endpoint = urllib.parse.unquote_plus(endpoint)
signature_msg = method + unquote_endpoint + json.dumps(payload, separators=(',', ':'), sort_keys=True)
request_string = bytes(signature_msg, 'utf-8')
secret_key_bytes = bytes.fromhex(secret_key)
secret_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret_key_bytes)
signature_bytes = secret_key.sign(request_string)
signature = signature_bytes.hex()
return signature
public class Main {
public static void main(String[] args) throws Exception {
Main main = new Main();
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String Response = main.generateSignature("GET", "/trade/api/v2/orders", payload, parameters);
System.out.println(Response);
}
private String paramsToString(Map<String, String> params) throws Exception {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return sb.toString();
}
private String signatureMessage(String method, String endpoint, HashMap<String, Object> payload) throws Exception {
TreeMap<String, Object> treeMap = new TreeMap<>(payload);
String sortedPayloadJson = new ObjectMapper().writeValueAsString(treeMap);
return method + endpoint + sortedPayloadJson;
}
public String getSignatureOfRequest(String secretKey, String requestString) {
byte[] requestBytes = requestString.getBytes(StandardCharsets.UTF_8);
byte[] secretKeyBytes = Hex.decode(secretKey);
// Generate private key
Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(secretKeyBytes, 0);
// Sign the request
Ed25519Signer signer = new Ed25519Signer();
signer.init(true, privateKey);
signer.update(requestBytes, 0, requestBytes.length);
byte[] signatureBytes = signer.generateSignature();
String signatureHex = Hex.toHexString(signatureBytes);
return signatureHex;
}
public String generateSignature(String method, String endpoint, HashMap<String, Object> payload, HashMap<String, String> params) throws Exception{
String decodedEndpoint = endpoint;
String secretKey = ""; // provided by coinswitch
if (method.equals("GET") && !params.isEmpty()) {
String query = new URI(endpoint).getQuery();
endpoint += (query == null || query.isEmpty()) ? "?" : "&";
endpoint += URLEncoder.encode(paramsToString(params), "UTF-8");
decodedEndpoint = URLDecoder.decode(endpoint, "UTF-8");
}
String signatureMsg = signatureMessage(method, decodedEndpoint, payload);
String signature = getSignatureOfRequest(secretKey, signatureMsg);
return signature;
}
}
Lets take an example of a Get API:
from cryptography.hazmat.primitives.asymmetric import ed25519
from urllib.parse import urlparse, urlencode
import urllib
import json
import requests
params = {
"count": 20,
"from_time": 1600261657954,
"to_time": 1687261657954,
"side": "sell",
"symbols": "btc/inr,eth/inr",
"exchanges": "coinswitchx,wazirx",
"type": "limit",
"open": True
}
endpoint = "/trade/api/v2/orders"
method = "GET"
payload = {}
secret_key = < secret_key > # provided by coinswitch
api_key = < api_key> # provided by coinswitch
unquote_endpoint = endpoint
if method == "GET" and len(params) != 0:
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
unquote_endpoint = urllib.parse.unquote_plus(endpoint)
signature_msg = method + unquote_endpoint + json.dumps(payload, separators=(',', ':'), sort_keys=True)
request_string = bytes(signature_msg, 'utf-8')
secret_key_bytes = bytes.fromhex(secret_key)
secret_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret_key_bytes)
signature_bytes = secret_key.sign(request_string)
signature = signature_bytes.hex()
url = "https://coinswitch.co" + endpoint
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': signature,
'X-AUTH-APIKEY': api_key
}
response = requests.request("GET", url, headers=headers, json=payload)
package com.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.bouncycastle.util.encoders.Hex;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws Exception {
Main main = new Main();
String Response = main.getOpenOrders();
System.out.println(Response);
}
public String getOpenOrders() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?&count=" + URLEncoder.encode("20", "UTF-8")
+ "&from_time=" + URLEncoder.encode("1600261657954", "UTF-8")+
"&to_time=" + URLEncoder.encode("1687261657954", "UTF-8")+
"&side=" + URLEncoder.encode("sell", "UTF-8")+
"&type=" + URLEncoder.encode("limit", "UTF-8")+
"&exchanges=" + URLEncoder.encode("coinswitchx,wazirx", "UTF-8")+
"&symbols=" + URLEncoder.encode("btc/inr,eth/inr", "UTF-8")
;
path = path.replaceAll("%2C", ",");
path = path.replaceAll("%2F", "/");
return this.makeRequest("GET","/trade/api/v2/orders" + path, payload, parameters);
}
public String makeRequest(String method, String endpoint, HashMap<String, Object> payload, HashMap<String, String> params) throws Exception {
String secretKey = "" ; // provided by coinswitch
String apiKey = ""; // provided by coinswitch
String decodedEndpoint = endpoint;
if (method.equals("GET") && !params.isEmpty()) {
String query = new URI(endpoint).getQuery();
endpoint += (query == null || query.isEmpty()) ? "?" : "&";
endpoint += URLEncoder.encode(paramsToString(params), "UTF-8");
decodedEndpoint = URLDecoder.decode(endpoint, "UTF-8");
}
String signatureMsg = signatureMessage(method, decodedEndpoint, payload);
String signature = getSignatureOfRequest(secretKey, signatureMsg);
Map<String, String> headers = new HashMap<>();
String url = "https://coinswitch.co" + endpoint;
headers.put("X-AUTH-SIGNATURE", signature);
headers.put("X-AUTH-APIKEY", apiKey);
if (method.equals("GET")){
HttpResponse<String> response = callGetApi(url, headers, payload);
return response.body().toString();
}
if (method.equals("POST") || method.equals("PUT") || method.equals("DELETE")){
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(payload);
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// Set the request method to POST
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-AUTH-SIGNATURE", signature);
connection.setRequestProperty("X-AUTH-APIKEY", apiKey);
// Enable output and set the request body
connection.setDoOutput(true);
connection.getOutputStream().write(json.getBytes());
// Get the response code
int responseCode = connection.getResponseCode();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Close the connection
connection.disconnect();
return response.toString();
};
return "SUCCESS";
}
private String paramsToString(Map<String, String> params) throws Exception {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return sb.toString();
}
private String signatureMessage(String method, String endpoint, HashMap<String, Object> payload) throws Exception {
TreeMap<String, Object> treeMap = new TreeMap<>(payload);
String sortedPayloadJson = new ObjectMapper().writeValueAsString(treeMap);
return method + endpoint + sortedPayloadJson;
}
public String getSignatureOfRequest(String secretKey, String requestString) {
byte[] requestBytes = requestString.getBytes(StandardCharsets.UTF_8);
byte[] secretKeyBytes = Hex.decode(secretKey);
// Generate private key
Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(secretKeyBytes, 0);
// Sign the request
Ed25519Signer signer = new Ed25519Signer();
signer.init(true, privateKey);
signer.update(requestBytes, 0, requestBytes.length);
byte[] signatureBytes = signer.generateSignature();
String signatureHex = Hex.toHexString(signatureBytes);
return signatureHex;
}
private HttpResponse<String> callGetApi(String url, Map<String, String> headers, HashMap<String, Object> payload) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest.Builder requestBuilder;
requestBuilder = HttpRequest.newBuilder()
.GET()
.uri(new URI(url));
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.header(entry.getKey(), entry.getValue());
}
HttpRequest request = requestBuilder.build();
return client.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Lets take an example of a DELETE API:
from cryptography.hazmat.primitives.asymmetric import ed25519
from urllib.parse import urlparse, urlencode
import urllib
import json
import requests
payload = {
"order_id": "698ed406-8ef5-4664-9779-f7978702a447"
}
endpoint = "/trade/api/v2/order"
method = "DELETE"
params = {}
secret_key = < secret_key > # provided by coinswitch
api_key = < api_key> # provided by coinswitch
signature_msg = method + endpoint + json.dumps(payload, separators=(',', ':'), sort_keys=True)
request_string = bytes(signature_msg, 'utf-8')
secret_key_bytes = bytes.fromhex(secret_key)
secret_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret_key_bytes)
signature_bytes = secret_key.sign(request_string)
signature = signature_bytes.hex()
url = "https://coinswitch.co" + endpoint
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': signature,
'X-AUTH-APIKEY': api_key
}
response = requests.request("DELETE", url, headers=headers, json=payload)
package com.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.bouncycastle.util.encoders.Hex;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws Exception {
Main main = new Main();
String Response = main.cancelOrder();
System.out.println(Response);
}
public String cancelOrder() throws Exception{
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
payload.put("order_id", "698ed406-8ef5-4664-9779-f7978702a447");
return this.makeRequest("DELETE", "/trade/api/v2/order", payload, parameters);
}
public String makeRequest(String method, String endpoint, HashMap<String, Object> payload, HashMap<String, String> params) throws Exception {
String secretKey = "" ; // provided by coinswitch
String apiKey = ""; // provided by coinswitch
String decodedEndpoint = endpoint;
if (method.equals("GET") && !params.isEmpty()) {
String query = new URI(endpoint).getQuery();
endpoint += (query == null || query.isEmpty()) ? "?" : "&";
endpoint += URLEncoder.encode(paramsToString(params), "UTF-8");
decodedEndpoint = URLDecoder.decode(endpoint, "UTF-8");
}
String signatureMsg = signatureMessage(method, decodedEndpoint, payload);
String signature = getSignatureOfRequest(secretKey, signatureMsg);
Map<String, String> headers = new HashMap<>();
String url = "https://coinswitch.co" + endpoint;
headers.put("X-AUTH-SIGNATURE", signature);
headers.put("X-AUTH-APIKEY", apiKey);
if (method.equals("GET")){
HttpResponse<String> response = callGetApi(url, headers, payload);
return response.body().toString();
}
if (method.equals("POST") || method.equals("PUT") || method.equals("DELETE")){
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(payload);
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// Set the request method to POST
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-AUTH-SIGNATURE", signature);
connection.setRequestProperty("X-AUTH-APIKEY", apiKey);
// Enable output and set the request body
connection.setDoOutput(true);
connection.getOutputStream().write(json.getBytes());
// Get the response code
int responseCode = connection.getResponseCode();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Close the connection
connection.disconnect();
return response.toString();
};
return "SUCCESS";
}
private String paramsToString(Map<String, String> params) throws Exception {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return sb.toString();
}
private String signatureMessage(String method, String endpoint, HashMap<String, Object> payload) throws Exception {
TreeMap<String, Object> treeMap = new TreeMap<>(payload);
String sortedPayloadJson = new ObjectMapper().writeValueAsString(treeMap);
return method + endpoint + sortedPayloadJson;
}
public String getSignatureOfRequest(String secretKey, String requestString) {
byte[] requestBytes = requestString.getBytes(StandardCharsets.UTF_8);
byte[] secretKeyBytes = Hex.decode(secretKey);
// Generate private key
Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(secretKeyBytes, 0);
// Sign the request
Ed25519Signer signer = new Ed25519Signer();
signer.init(true, privateKey);
signer.update(requestBytes, 0, requestBytes.length);
byte[] signatureBytes = signer.generateSignature();
String signatureHex = Hex.toHexString(signatureBytes);
return signatureHex;
}
private HttpResponse<String> callGetApi(String url, Map<String, String> headers, HashMap<String, Object> payload) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest.Builder requestBuilder;
requestBuilder = HttpRequest.newBuilder()
.GET()
.uri(new URI(url));
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.header(entry.getKey(), entry.getValue());
}
HttpRequest request = requestBuilder.build();
return client.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Keys Validation
from cryptography.hazmat.primitives.asymmetric import ed25519
from urllib.parse import urlparse, urlencode
import urllib
import json
import requests
params = {}
endpoint = "/trade/api/v2/validate/keys"
method = "GET"
payload = {}
secret_key = < secret_key > # provided by coinswitch
api_key = < api_key> # provided by coinswitch
unquote_endpoint = endpoint
if method == "GET" and len(params) != 0:
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
unquote_endpoint = urllib.parse.unquote_plus(endpoint)
signature_msg = method + unquote_endpoint + json.dumps(payload, separators=(',', ':'), sort_keys=True)
request_string = bytes(signature_msg, 'utf-8')
secret_key_bytes = bytes.fromhex(secret_key)
secret_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret_key_bytes)
signature_bytes = secret_key.sign(request_string)
signature = signature_bytes.hex()
url = "https://coinswitch.co" + endpoint
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': signature,
'X-AUTH-APIKEY': api_key
}
response = requests.request("GET", url, headers=headers, json=payload)
package com.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.bouncycastle.util.encoders.Hex;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws Exception {
Main main = new Main();
String Response = main.ValidateKeys();
System.out.println(Response);
}
public String ValidateKeys() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
return this.makeRequest("GET", "/trade/api/v2/validate/keys", payload, parameters);
}
public String makeRequest(String method, String endpoint, HashMap<String, Object> payload, HashMap<String, String> params) throws Exception {
String secretKey = "" ; // provided by coinswitch
String apiKey = ""; // provided by coinswitch
String decodedEndpoint = endpoint;
if (method.equals("GET") && !params.isEmpty()) {
String query = new URI(endpoint).getQuery();
endpoint += (query == null || query.isEmpty()) ? "?" : "&";
endpoint += URLEncoder.encode(paramsToString(params), "UTF-8");
decodedEndpoint = URLDecoder.decode(endpoint, "UTF-8");
}
String signatureMsg = signatureMessage(method, decodedEndpoint, payload);
String signature = getSignatureOfRequest(secretKey, signatureMsg);
Map<String, String> headers = new HashMap<>();
String url = "https://coinswitch.co" + endpoint;
headers.put("X-AUTH-SIGNATURE", signature);
headers.put("X-AUTH-APIKEY", apiKey);
if (method.equals("GET")){
HttpResponse<String> response = callGetApi(url, headers, payload);
return response.body().toString();
}
if (method.equals("POST") || method.equals("PUT") || method.equals("DELETE")){
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(payload);
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// Set the request method to POST
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-AUTH-SIGNATURE", signature);
connection.setRequestProperty("X-AUTH-APIKEY", apiKey);
// Enable output and set the request body
connection.setDoOutput(true);
connection.getOutputStream().write(json.getBytes());
// Get the response code
int responseCode = connection.getResponseCode();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Close the connection
connection.disconnect();
return response.toString();
};
return "SUCCESS";
}
private String paramsToString(Map<String, String> params) throws Exception {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return sb.toString();
}
private String signatureMessage(String method, String endpoint, HashMap<String, Object> payload) throws Exception {
TreeMap<String, Object> treeMap = new TreeMap<>(payload);
String sortedPayloadJson = new ObjectMapper().writeValueAsString(treeMap);
return method + endpoint + sortedPayloadJson;
}
public String getSignatureOfRequest(String secretKey, String requestString) {
byte[] requestBytes = requestString.getBytes(StandardCharsets.UTF_8);
byte[] secretKeyBytes = Hex.decode(secretKey);
// Generate private key
Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(secretKeyBytes, 0);
// Sign the request
Ed25519Signer signer = new Ed25519Signer();
signer.init(true, privateKey);
signer.update(requestBytes, 0, requestBytes.length);
byte[] signatureBytes = signer.generateSignature();
String signatureHex = Hex.toHexString(signatureBytes);
return signatureHex;
}
private HttpResponse<String> callGetApi(String url, Map<String, String> headers, HashMap<String, Object> payload) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest.Builder requestBuilder;
requestBuilder = HttpRequest.newBuilder()
.GET()
.uri(new URI(url));
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.header(entry.getKey(), entry.getValue());
}
HttpRequest request = requestBuilder.build();
return client.send(request, HttpResponse.BodyHandlers.ofString());
}
}
You can validate the keys provided by Coinswitch using the URL given below:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/validate/keys
RESPONSE 200
{
"message":"Valid Access"
}
RESPONSE 401
{
"message":"Invalid Access"
}
Ping Testing
Use the code below to check if your ecosystem has been successfully connected to the CoinSwitch ecosystem. In case of any error in connection write to us at api@coinswitch.co.
import requests
import json
url = "https://coinswitch.co/trade/api/v2/ping"
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String ping() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
return this.makeRequest("GET", "/trade/api/v2/ping", payload, parameters);
}
Response
{
"message":"OK"
}
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/ping
Trading
Order Status Description
Status | Description |
---|---|
OPEN | Order has not been executed at all |
PARTIALLY_EXECUTED | Order has been partially executed |
CANCELED | User has canceled the order |
EXECUTED | Order has been executed |
EXPIRED | Order has expired |
DISCARDED | Order has not been processed (It has not been placed on the exchange) |
Create Order
import requests
import json
url = "https://coinswitch.co/trade/api/v2/order"
payload = {
"side":"sell",
"symbol":"BTC/INR",
"type":"limit",
"price":2300000,
"quantity":0.00005,
"exchange":"coinswitchx"
}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("POST", url, headers=headers, json=payload)
public String createOrder() throws Exception{
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
payload.put("side", "sell");
payload.put("symbol", "BTC/INR");
payload.put("type", "limit");
payload.put("quantity", 0.00005);
payload.put("price", 2300000);
payload.put("exchange", "coinswitchx");
DecimalFormat decimalFormat = new DecimalFormat("#.################");
String formattedQuantity = decimalFormat.format(payload.get("quantity"));
String formattedPrice = decimalFormat.format(payload.get("price"));
BigDecimal price = new BigDecimal(formattedPrice);
BigDecimal quantity = new BigDecimal(formattedQuantity);
payload.put("quantity", quantity);
payload.put("price", price);
return this.makeRequest("POST", "/trade/api/v2/order", payload, parameters);
}
The above command returns JSON structured like this:
RESPONSE 200
{
"data":{
"order_id":"927db2d9-643c-47a3-9c0f-78741ac95cf5",
"symbol":"BTC/INR",
"price":2300000, # price at which Order was placed by the user
"average_price":0, # price at which the order got executed
"orig_qty":5e-05, # quantity at which order was placed
"executed_qty":0, # quantity that got executed
"status":"OPEN",
"side":"SELL",
"exchange":"coinswitchx",
"order_source":"API_TRADING",
"created_time":1689661638000, # time stamp in milli seconds
"updated_time":1689661639000 # time stamp in milli seconds
}
}
RESPONSE: 422
{
"message": "Input price must be of type number"
}
RESPONSE: 400
{
"message": "Amount is more than available balance"
}
RESPONSE: 401
{
"message": "Invalid access"
}
Use the following endpoint to place a new order on the exchange:
HTTP Request
METHOD POST
ENDPOINT https://coinswitch.co/trade/api/v2/order
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
side | string | Yes | Allowed values: “buy”/“sell" (case insensitive) |
symbol | string | Yes | Should be in the format base_currency/quote_currency (case insensitive) |
type | string | Yes | Order type , currently we support only only LIMIT order type |
price | float | Yes | Price at which you want to place the order |
quantity | float | Yes | Base quantity that you want to buy or sell |
exchange | string | Yes | Allowed values: “coinswitchx”/“wazirx” (case insensitive) |
Cancel Order
Use the following endpoint to cancel an order on the exchange:
HTTP Request
METHOD DELETE
ENDPOINT https://coinswitch.co/trade/api/v2/order
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
order_id | string | Yes | order_id that needs to be canceled |
import requests
import json
url = "https://coinswitch.co/trade/api/v2/order"
payload = {
"order_id": "698ed406-8ef5-4664-9779-f7978702a447"
}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("DELETE", url, headers=headers, json=payload)
public String cancelOrder() throws Exception{
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
payload.put("order_id", "698ed406-8ef5-4664-9779-f7978702a447");
return this.makeRequest("DELETE", "/trade/api/v2/order", payload, parameters);
}
The above command returns JSON structured like this:
RESPONSE 200
{
"data":{
"order_id":"698ed406-8ef5-4664-9779-f7978702a447",
"symbol":"BTC/INR",
"price":2300000, # price at which Order was placed by the user
"average_price":0, # price at which the order got executed
"orig_qty":5e-05, # quantity at which order was placed
"executed_qty":0, # quantity that got executed
"status":"CANCELLED",
"side":"SELL",
"exchange":"coinswitchx",
"order_source":"API_TRADING",
"created_time":1689661638000, # time stamp in milli seconds
"updated_time":1689661639000 # time stamp in milli seconds
}
}
Open Orders
import requests
import json
from urllib.parse import urlparse, urlencode
params = {
"count": 2,
"from_time": 1600261657954,
"to_time": 1687261657954,
"side": "sell",
"symbols": "btc/inr,eth/inr",
"exchanges": "coinswitchx,wazirx",
"type": "limit",
"open": True
}
payload = {}
endpoint = "/trade/api/v2/orders"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String getOpenOrders() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?&count=" + URLEncoder.encode("2", "UTF-8")
+ "&from_time=" + URLEncoder.encode("1600261657954", "UTF-8")+
"&to_time=" + URLEncoder.encode("1687261657954", "UTF-8")+
"&side=" + URLEncoder.encode("sell", "UTF-8")+
"&type=" + URLEncoder.encode("limit", "UTF-8")+
"&exchanges=" + URLEncoder.encode("coinswitchx,wazirx", "UTF-8")+
"&symbols=" + URLEncoder.encode("btc/inr,eth/inr", "UTF-8")+
"&open=" + URLEncoder.encode(True, "UTF-8")
;
path = path.replaceAll("%2C", ",");
path = path.replaceAll("%2F", "/");
return this.makeRequest("GET","/trade/api/v2/orders" + path, payload, parameters);
}
The above command returns JSON structured like this:
Response 200
{
"data": {
"orders": [
{
"order_id": "56013d06-7fe6-416f-9086-86902577ba99",
"symbol": "SHIB/INR",
"price": 0.000638,
"average_price": 0.000957,
"orig_qty": 187400,
"executed_qty": 0,
"status": "OPEN",
"side": "SELL",
"exchange": "coinswitchx",
"order_source": "API_TRADING",
"created_time": 1687173658000,
"updated_time": 1687173705000
},
{
"order_id": "87a1b145-84f4-4e8b-8199-0dd0fab2a5ec",
"symbol": "SHIB/INR",
"price": 0.000247,
"average_price": 0,
"orig_qty": 177400,
"executed_qty": 167400,
"status": "PARTIALLY_EXECUTED",
"side": "SELL",
"exchange": "coinswitchx",
"order_source": "API_TRADING",
"created_time": 1687171873000,
"updated_time": 1687173633000
}
],
"total_orders_count": 4 # represent total open orders present
}
}
# If no orders are present
Response 200
{
"data": {
"orders": [],
"total_orders_count": 0
}
}
Use the following endpoint to check closed orders:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/orders
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
count | string | No | Default value 25 |
from_time | string | No | Timestamp in miliseconds |
to_time | string | No | Timestamp in miliseconds |
side | string | No | Allowed values: (case insensitive) “buy" or “sell” |
symbols | string | No | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR", multiple pairs are also allowed like "btc/inr,shib/inr" |
exchanges | string | No | Allowed values: (case insensitive) "coinswitchx,wazirx" "coinswitchx" “wazirx" |
type | string | No | By default it will take Limit |
open | bool | Yes | It should be true to get open orders |
Closed Orders
import requests
import json
from urllib.parse import urlparse, urlencode
params = {
"count": 3,
"from_time": 1600261657954,
"to_time": 1687261657954,
"side": "sell",
"symbols": "btc/inr,eth/inr",
"exchanges": "coinswitchx,wazirx",
"type": "limit",
"status": "EXECUTED",
"open": False
}
payload = {}
endpoint = "/trade/api/v2/orders"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String getClosedOrders() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?&count=" + URLEncoder.encode("3", "UTF-8")+
"&from_time=" + URLEncoder.encode("1600261657954", "UTF-8")+
"&to_time=" + URLEncoder.encode("1687261657954", "UTF-8")+
"&side=" + URLEncoder.encode("sell", "UTF-8")+
"&type=" + URLEncoder.encode("limit", "UTF-8")+
"&exchanges=" + URLEncoder.encode("coinswitchx,wazirx", "UTF-8")+
"&symbols=" + URLEncoder.encode("btc/inr,eth/inr", "UTF-8")+
"&status=" + URLEncoder.encode("EXECUTED", "UTF-8")+
"&open=" + URLEncoder.encode(False, "UTF-8")
;
path = path.replaceAll("%2C", ",");
path = path.replaceAll("%2F", "/");
return this.makeRequest("GET","/trade/api/v2/orders" + path, payload, parameters);
}
The above command returns JSON structured like this:
Response 200
{
"data": {
"orders": [
{
"order_id": "56013d06-7fe6-416f-9086-86902577ba99",
"symbol": "SHIB/INR",
"price": 0.000638,
"average_price": 0.000957,
"orig_qty": 187400,
"executed_qty": 0,
"status": "CANCELLED",
"side": "SELL",
"exchange": "coinswitchx",
"order_source": "API_TRADING",
"created_time": 1687173658000,
"updated_time": 1687173705000
},
{
"order_id": "87a1b145-84f4-4e8b-8199-0dd0fab2a5ec",
"symbol": "SHIB/INR",
"price": 0.000247,
"average_price": 0,
"orig_qty": 177400,
"executed_qty": 167400,
"status": "CANCELLED",
"side": "SELL",
"exchange": "coinswitchx",
"order_source": "API_TRADING",
"created_time": 1687171873000,
"updated_time": 1687173633000
},
{
"order_id": "47a1b145-84f4-4e8b-8199-0dd0fab2a5ec",
"symbol": "SHIB/INR",
"price": 0.000247,
"average_price": 0,
"orig_qty": 177400,
"executed_qty": 177400,
"status": "EXECUTED",
"side": "BUY",
"exchange": "coinswitchx",
"order_source": "API_TRADING",
"created_time": 1687171873000,
"updated_time": 1687173633000
}
],
"total_orders_count": 4 # represent total closed orders present
}
}
# If no orders are present
Response 200
{
"data": {
"orders": [],
"total_orders_count": 0
}
}
Use the following endpoint to check closed orders:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/orders
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
count | string | No | Default value 25 |
from_time | string | No | Timestamp in miliseconds |
to_time | string | No | Timestamp in miliseconds |
side | string | No | Allowed values: (case insensitive) “buy" or “sell” |
symbols | string | No | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr" |
exchanges | string | No | Allowed values: (case insensitive) "coinswitchx,wazirx" "coinswitchx" “wazirx" |
type | string | No | Default value Limit |
status | string | No | Order status |
open | bool | No | Default value is False |
Portfolio
import requests
import json
url = "https://coinswitch.co/trade/api/v2/user/portfolio"
payload={}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String portfolio() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
return this.makeRequest("GET", "/trade/api/v2/user/portfolio", payload, parameters);
}
The above command returns JSON structured like this:
Status Code 200
{
"data":[
{
"currency":"ETH",
"blocked_balance_deposit":"0",
"blocked_balance_withdraw":"0",
"blocked_balance_order":"0.0019",
"main_balance":"0.00008393",
"blocked_balance_stake":"0",
"blocked_balance_vault":"0",
"buy_average_price":110882.72063601,
"invested_value":220.40483679829757,
"invested_value_excluding_fee":219.98355595139932,
"current_value":324.10075659,
"sell_rate":163363,
"buy_rate":164531,
"is_average_price_available":true,
"name":"Ethereum",
"is_delisted_coin":false
},
{
"currency":"SHIB",
"blocked_balance_deposit":"0",
"blocked_balance_withdraw":"0",
"blocked_balance_order":"0",
"main_balance":"99983.2566",
"blocked_balance_stake":"0",
"blocked_balance_vault":"0",
"buy_average_price":0.00088449,
"invested_value":88.498179914358,
"invested_value_excluding_fee":88.434190630134,
"current_value":67.38871494840001,
"sell_rate":0.000674,
"buy_rate":0.000674,
"is_average_price_available":true,
"name":"Shiba Inu",
"is_delisted_coin":false
},
{
"name":"Indian Rupee",
"currency":"INR",
"main_balance":802.33,
"blocked_balance_order":0,
"invested_value":308.9,
"current_value":654.95
}
]
}
Use the following endpoint to check your portfolio:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/user/portfolio
Exchange Precision
import requests
import json
from urllib.parse import urlparse, urlencode
url = "https://coinswitch.co/trade/api/v2/exchangePrecision"
payload = {
"exchange": "coinswitchx",
"symbol": "BTC/INR"
}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("POST", url, headers=headers, json=payload)
public String getExchangePrecision() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
payload.put("exchange","coinswitchx");
payload.put("symbol","BTC/INR");
String response = this.makeRequest("POST","/trade/api/v2/exchangePrecision", payload, parameters);
return response;
}
The above command returns JSON structured like this:
{
"data":{
"coinswitchx":{
"BTC/INR":{
"base":5,
"quote":2,
"limit":0
}
}
}
}
Use the following endpoint to check precision coin and exchange wise:
HTTP Request
METHOD POST
ENDPOINT https://coinswitch.co/trade/api/v2/exchangePrecision
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | "coinswitchx" or "wazirx" |
symbol | string | No | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr" |
Trades
import requests
import json
params = {
"exchange": "wazirx",
"symbol": "btc/inr"
}
endpoint = "/trade/api/v2/trades"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String getTrades() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?exchange=" + URLEncoder.encode("wazirx", "UTF-8")
+ "&symbol=" + URLEncoder.encode("btc/inr", "UTF-8");
path = path.replaceAll("%2F", "/");
String response = this.makeRequest("GET","/trade/api/v2/trades" +path, payload, parameters);
return response;
}
The above command returns JSON structured like this:
{
"data": [
{
"E": 1686512630072, # Event time
"S": "buy", # Side
"a": "ecd673ae-30cf-40e8-9f2e-9c80b9e2962e", # Buyer order ID
"b": "73c4f35e-8e43-4f99-912b-93bd1ec6e2a6", # Seller order ID
"m": false, # Is Buyer Maker
"p": "5.8599", # Price
"q": "42", # Quantity
"s": "DOGE/INR", # Symbol
"t": "f60742d8-2494-4d87-96e5-310ded278c15", # Trade ID
"e": "coinswitchx" # Exchange
}
]
}
Use the following endpoint to get all trades history:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/trades
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | Allowed values: “coinswitchx”/ “wazirx” |
symbol | string | Yes | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr |
Depth
import requests
import json
from urllib.parse import urlparse, urlencode
params = {
"exchange": "wazirx",
"symbol": "btc/inr"
}
endpoint = "/trade/api/v2/depth"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String getDepthOfCoin() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?exchange=" + URLEncoder.encode("wazirx", "UTF-8")
+ "&symbol=" + URLEncoder.encode("btc/inr", "UTF-8");
path = path.replaceAll("%2F", "/");
String response = this.makeRequest("GET","/trade/api/v2/depth" +path, payload, parameters);
return response;
}
The above command returns JSON structured like this:
{
"data": {
"symbol": "DOGE/INR",
"timestamp": 1686514361972,
"bids": [
[
"5.82", //Price
"4350" //Quantity
]
],
"asks": [
[
"5.8664", //Price
"1238" //Quantity
]
]
}
}
Use the following endpoint to check orderbook:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/depth
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | Allowed values: “coinswitchx” “wazirx” |
symbol | string | Yes | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr |
Candles
import requests
from urllib.parse import urlparse, urlencode
params = {
"end_time": "1662681600000",
"start_time": "1647388800000",
"symbol": "BTC/INR",
"interval": "60",
"exchange": "wazirx"
}
endpoint = "/trade/api/v2/candles"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String getCandleStickData() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?end_time=" + URLEncoder.encode("1662681600000", "UTF-8")
+ "&start_time=" + URLEncoder.encode("1647388800000", "UTF-8")
+ "&symbol=" + URLEncoder.encode("BTC/INR", "UTF-8")+
"&interval=" + URLEncoder.encode("60", "UTF-8")+
"&exchange=" + URLEncoder.encode("wazirx", "UTF-8")
;
path = path.replaceAll("%2F", "/");
String response = this.makeRequest("GET","/trade/api/v2/candles"+path, payload, parameters);
return response;
}
The above command returns JSON structured like this:
{
"result": [
{
"o": "1591001.000000000000", # Open
"h": "1610988.000000000000", # High
"l": "1588000.000000000000", # Low
"c": "1591000.000000000000", # Close
"interval": "60", # Candlestick duration
"symbol": "BTC/INR", # case insensitive
"close_time": "1662681600000", # Timestamp in milliseconds
"volume": "0.304680000000", # trade volume
"start_time": "1662678000000" # Timestamp in milliseconds
}
],
}
Use the following endpoint to get candles data:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/candles
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | Allowed values: “coinswitchx” “wazirx” |
symbol | string | Yes | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr |
interval | int | Yes | Duration of candlestick in minutes |
start_time | long | Yes | Timestamp in milliseconds (Epoch format) |
end_time | long | Yes | Timestamp in milliseconds (Epoch format) |
Ticker 24hr All Pairs
import requests
from urllib.parse import urlparse, urlencode
params = {
"exchange": "coinswitchx"
}
endpoint = "/trade/api/v2/24hr/all-pairs/ticker"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String get24hrAllPairData() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?exchange=" + URLEncoder.encode("coinswitchx", "UTF-8");
return this.makeRequest("GET","/trade/api/v2/24hr/all-pairs/ticker"+path, payload, parameters);
}
The above command returns JSON structured like this:
{
"data": {
"WAVES/INR": {
"symbol": "WAVES/INR",
"baseAsset": "WAVES",
"quoteAsset": "INR",
"openPrice": "127.65",
"lowPrice": "125.53",
"highPrice": "129.88",
"lastPrice": "125.56",
"baseVolume": "1910.65",
"quoteVolume": "240593.58",
"percentageChange": "-1.63728946337642",
"bidPrice": "125.56",
"askPrice": "127.29",
"at": 1687267004787
},
"DNT/INR": {
"symbol": "DNT/INR",
"baseAsset": "DNT",
"quoteAsset": "INR",
"openPrice": "0",
"lowPrice": "0",
"highPrice": "0",
"lastPrice": "0",
"baseVolume": "0",
"quoteVolume": "0",
"percentageChange": "0",
"bidPrice": "154",
"askPrice": "156",
"at": 1687267004494
}
}
}
Use the following endpoint to get 24hr ticker for all coins:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/24hr/all-pairs/ticker
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | Allowed values “coinswitchx” “wazirx” |
Ticker 24hr For Specific Coin
import requests
from urllib.parse import urlparse, urlencode
params = {
"symbol": "BTC/INR",
"exchange": "coinswitchx,wazirx"
}
endpoint = "/trade/api/v2/24hr/ticker"
endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params)
url = "https://coinswitch.co" + endpoint
payload = {}
headers = {
'Content-Type': 'application/json',
'X-AUTH-SIGNATURE': <api-signature>,
'X-AUTH-APIKEY': <api-key>
}
response = requests.request("GET", url, headers=headers, json=payload)
public String get24hrSinglePairData() throws Exception {
HashMap<String, String> parameters = new HashMap<>();
HashMap<String, Object> payload = new HashMap<>();
String path = "?exchange=" + URLEncoder.encode("coinswitchx,wazirx", "UTF-8")
+ "&symbol=" + URLEncoder.encode("BTC/INR", "UTF-8");
path = path.replaceAll("%2F", "/");
path = path.replaceAll("%2C", ",");
return this.makeRequest("GET","/trade/api/v2/24hr/ticker"+path, payload, parameters);
}
The above command returns JSON structured like this:
{
"data": {
"WAVES/INR": {
"symbol": "WAVES/INR",
"baseAsset": "WAVES",
"quoteAsset": "INR",
"openPrice": "127.65",
"lowPrice": "125.53",
"highPrice": "129.88",
"lastPrice": "125.56",
"baseVolume": "1910.65",
"quoteVolume": "240593.58",
"percentageChange": "-1.63728946337642",
"bidPrice": "125.56",
"askPrice": "127.29",
"at": 1687267004787
},
"DNT/INR": {
"symbol": "DNT/INR",
"baseAsset": "DNT",
"quoteAsset": "INR",
"openPrice": "0",
"lowPrice": "0",
"highPrice": "0",
"lastPrice": "0",
"baseVolume": "0",
"quoteVolume": "0",
"percentageChange": "0",
"bidPrice": "154",
"askPrice": "156",
"at": 1687267004494
}
}
}
Use the following endpoint to get the 24hr ticker for specific coin:
HTTP Request
METHOD GET
ENDPOINT https://coinswitch.co/trade/api/v2/24hr/ticker
Request Parameters
Parameter | Type | Mandatory | Description |
---|---|---|---|
exchange | string | Yes | Allowed values “coinswitchx” “wazirx” |
symbol | string | Yes | Allowed values: (case insensitive) “BTC/INR" "SHIB/INR" "btc/inr,eth/inr |
Error Scenarios
HTTP Error Codes
HTTP 4XX: Malformed request; the issue is on the sender's end.
HTTP 429: Your request rate limit has been exceeded.
HTTP 5XX: Internal error; issue on CoinSwitch end. It is important to NOT treat this as a failure operation; the execution status is UNKNOWN and could have been a success.
Custom Error Messages
Status Code 422
{ "message":"Input <field name> is missing" }
Status Code 422
{ "message":"The value you provided for the field is not valid. Please check the documentation for valid values and try again." }
Status Code 400
{ "message":"Amount is more than available balance" }
Status Code 401
{ "message":"Invalid Access" }
WebSockets
How to connect ?
Socket Config | Value |
---|---|
Type | Socket.IO |
Version | v4 |
Handshake Path | /pro/realtime-rates-socket/ |
Base URL | wss://ws.coinswitch.co/ |
PRO Tip: To connect with a particular exchange, we have to provide namespace as we use multiplexing.
Namespace
Exchange | Namespace |
---|---|
Wazirx | baseurl + /wazirx |
CoinswitchX | baseurl + /coinswitchx |
Order Book
Event Name = "FETCH_ORDER_BOOK_CS_PRO"
import socketio
sio = socketio.Client()
pair = "BTC,INR"
sio.connect(url=base_url, namespaces=[namespace], transports='websocket',
socketio_path='/pro/realtime-rates-socket', wait=True, wait_timeout=3600)
subscribe_data = {
'event': 'subscribe',
'pair': pair
}
sio.emit(FETCH_ORDER_BOOK_CS_PRO, subscribe_data, namespace=namespace)
package com.coinswitch.socket.client.service;
import java.io.Closeable;
import com.coinswitch.socket.client.data.Constant;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.coinswitch.socket.client.data.Constant.*;
public Closeable onOrderBookEvent() {
String exchange = "wazirx"
String coinPair = "BTC,INR"
String nameSpaceMessage = "42/" + exchange + ",";
JSONObject subscribeData = new JSONObject();
subscribeData.put("event", "subscribe");
subscribeData.put("pair", coinPair);
String subscriptionEventMessage = nameSpaceMessage + "["+ "\"FETCH_ORDER_BOOK_CS_PRO\"" +","+subscribeData+"]";
System.out.println(subscriptionEventMessage);
return createNewWebSocket(exchange, subscriptionEventMessage, new CoinSwitchApiWebSocketListener<>(Class.class));
}
private Closeable createNewWebSocket(String exchange, String subscriptionEventMessage, CoinSwitchApiWebSocketListener<?> listener) {
Request request = new Request.Builder().url("wss://ws.coinswitch.co/pro/realtime-rates-socket/?EIO=4&transport=websocket").build();
final WebSocket webSocket = client.newWebSocket(request, listener);
String nameSpace = "40/" + exchange + ",";
webSocket.send(nameSpace);
webSocket.send(subscriptionEventMessage);
return () -> {
final int code = 1000;
listener.onClosing(webSocket, code, null);
webSocket.close(code, null);
listener.onClosed(webSocket, code, null);
};
}
RESPONSE
{
"s": "BTC,INR",
"timestamp": 1673255767122,
"bids": [
[
"1471201.000000000000", //Price
"0.005870" //Quantity
],
[
"1470201.000000000000", //Price
"0.046770" //Quantity
]
],
"asks": [
[
"1484400.000000000000",
"0.022109"
],
[
"1484500.000000000000",
"0.000390"
]
]
}
Trades
Event Name = "FETCH_TRADES_CS_PRO"
import socketio
sio = socketio.Client()
pair = "BTC,INR"
sio.connect(url=base_url, namespaces=[namespace], transports='websocket',
socketio_path='/pro/realtime-rates-socket', wait=True, wait_timeout=3600)
subscribe_data = {
'event': 'subscribe',
'pair': pair
}
sio.emit(FETCH_TRADES_CS_PRO, subscribe_data, namespace=namespace)
package com.coinswitch.socket.client.service;
import java.io.Closeable;
import com.coinswitch.socket.client.data.Constant;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.coinswitch.socket.client.data.Constant.*;
public Closeable onTradeHistoryEvent() {
String exchange = "wazirx"
String coinPair = "BTC,INR"
String nameSpaceMessage = "42/" + exchange + ",";
JSONObject subscribeData = new JSONObject();
subscribeData.put("event", "subscribe");
subscribeData.put("pair", coinPair);
String subscriptionEventMessage = nameSpaceMessage + "["+ "\"FETCH_TRADES_CS_PRO\"" +","+subscribeData+"]";
System.out.println(subscriptionEventMessage);
return createNewWebSocket(exchange, subscriptionEventMessage, new CoinSwitchApiWebSocketListener<>(Class.class));
}
private Closeable createNewWebSocket(String exchange, String subscriptionEventMessage, CoinSwitchApiWebSocketListener<?> listener) {
Request request = new Request.Builder().url("wss://ws.coinswitch.co/pro/realtime-rates-socket/?EIO=4&transport=websocket").build();
final WebSocket webSocket = client.newWebSocket(request, listener);
String nameSpace = "40/" + exchange + ",";
webSocket.send(nameSpace);
webSocket.send(subscriptionEventMessage);
return () -> {
final int code = 1000;
listener.onClosing(webSocket, code, null);
webSocket.close(code, null);
listener.onClosed(webSocket, code, null);
};
}
RESPONSE
{
"E": 1673257880000, // Event time
"S": "buy", // Side
"a": 3528009247, // Buyer order ID
"b": 3528008972, // Seller order ID
"p": "1472499.0", // Price
"q": "0.0004", // Quantity
"s": "BTC,INR", // Symbol
"t": 395531528, // Trade ID
"e": "wazirx" // Exchange
}
Change Log
4th August 2023
We have improved our V1 APIs:
- Improved security in V2 APIs.
- API responses have become consistent.
New Endpoints:
Validate Keys
GET /trade/api/v2/validate/keys
Ping
GET /trade/api/v2/ping
Create Order
POST /trade/api/v2/order
Cancel Order
DELETE /trade/api/v2/order
Open Order
GET /trade/api/v2/orders
Close Order
GET /trade/api/v2/orders
Portfolio
GET /trade/api/v2/user/portfolio
Exchange Precision
POST /trade/api/v2/exchangePrecision
24hr all pairs
GET /trade/api/v2/24hr/all-pairs/ticker
24hr specific pair
GET /trade/api/v2/24hr/ticker
Depth
GET /trade/api/v2/depth
Trade
GET /trade/api/v2/trades