NAV
python java

Change Log

9th February 2024

16th January 2024

26th December 2023

26th December 2023

10th November 2023

6th November 2023

In Portfolio API, we have removed blocked_balance_deposit, blocked_balance_withdraw, blocked_balance_stake, blocked_balance_vault response fields.

25th September 2023

We have introduced two new status "CANCELLATION_RAISED" and "EXPIRATION_RAISED". It is an intermediate state.

CANCELLATION_RAISED means that we have asked the exchange to cancel the order but it is not cancelled on the exchange yet.

EXPIRATION_RAISED means that the order is getting expired from the broker end. During this period order cancellation is not allowed.

New Endpoints:



4th August 2023

We have improved our V1 APIs:

New Endpoints:

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.

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

How to Setup

Begin API Trading on CoinSwitch PRO by following the mentioned set-up steps based on your preferred client language.

Python client

Setup With PyCharm

To set up a Python file in PyCharm, follow these step-by-step instructions:

Install PyCharm

Download and install the PyCharm community version IDE from the JetBrains website https://www.jetbrains.com/edu-products/download/other-PCE.html). Choose the appropriate version for your operating system and install Python 3 as well.

Create a new project

Launch PyCharm and click on Create New Project on the welcome screen.
If you already have a project open, you can also go to File -> New Project to create a new one.

Configure project settings

In the New Project dialog, choose the location where you want to store your project files and give your project a name.
You can also specify the Python interpreter you want to use for this project.
If you have a specific interpreter installed, select it; otherwise, you can choose the default option.

Create a new Python file

Once the project is created, you'll see the project structure on the left-hand side of the PyCharm window.
Right-click on the directory where you want to create your Python file (e.g., the project root directory) and select New -> Python File.
Give the file a meaningful name and press Enter

Write your Python code or paste api trading python file

The newly created Python file will open in the editor window. You can start writing your Python code here or paste the API trading python file that is shared with you over the email. PyCharm provides features like syntax highlighting, code completion, and debugging assistance to help you during development.

Install dependency

Open PyCharm Terminal and run below command

pip install cryptography==40.0.2
pip install requests==2.27.1
pip install python-socketio==5.5.1
pip install websocket-client==1.2.3

Run the Python file

To run your Python file, you can right-click anywhere in the editor window and select Run from the context menu.
Alternatively, you can use the keyboard shortcut (Ctrl+Shift+F10 on Windows/Linux or Shift+Control+R on macOS) to run the current Python file.

View the output

After running the Python file, you'll see the output in the Run tool window at the bottom of the PyCharm interface. If your program generates any output, it will be displayed here.

That's it! You have successfully set up the environment for API Trading .

Note: Please ensure you install Python 3.9 and the following libraries to their latest versions -cryptography, requests via your terminal in order to successfully run your scripts in your local machine without any virtual environment.

Java Client

Here's a guide to help you get started with setting up a Java project with IntelliJ and Gradle:

Install IntelliJ IDEA

Download and install the latest version of IntelliJ IDEA from the official JetBrains website https://www.jetbrains.com/idea/.

Install Gradle

Download and install Gradle by following the instructions on the official Gradle website https://gradle.org/install/.

Open Shared API Trading Gradle project in IntelliJ

Launch IntelliJ IDEA and select Open Project on the welcome screen.
Choose Gradle on the left panel and click Next
Select Java as the project type and click Next
Specify the project name and location, then click Finish

Configure Gradle in IntelliJ

After creating the project, IntelliJ will prompt you to configure Gradle.
Choose Use auto-import to automatically synchronize Gradle changes.
Select the Gradle JVM (Java Virtual Machine) you want to use for your project.

Configure project structure

In the Project view on the left side of IntelliJ, navigate to the project folder.
Right-click on the src folder and you will see two files: the first one is the main java file and second one is the config file
Specify the class name and click OK

Configure dependencies with Gradle

Open the build.gradle file in the project root directory. Inside the dependencies block, specify the libraries and dependencies you want to include in your project. For example, to include the Apache Commons Lang library, you can add the following line:

dependencies { implementation 'org.apache.commons:commons-lang3:3.12.0'}

Build and run the project

Click on the Gradle tab on the right side of the IntelliJ window.
Expand the project tree and navigate to the Tasks section.
Double-click on build to build the project.
Once the build is successful, you can run the project by right-clicking on the Java class file and selecting Run.

Congratulations! You have set up the API Trading Java project with IntelliJ using Gradle as the build tool.

Get Set Go

Add the received secret_key and api_key (keys shared over email or have been generated from Coinswitch Pro UI) in your script and start using API trading.

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, new HashMap<>());
    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.

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

Introduction to C2C Trading

CoinSwitch PRO brings you the opportunity to trade your favorite cryptocurrencies using other cryptocurrencies. We have currently launched USDT Pairs for our traders to trade in. An active API trader would be able to place and successfully execute a crypto-to-crypto order on CoinSwitch PRO on these pairs. You can refer to the below illustration for better understanding.

Here is an example of a BUY/SELL C2C USDT Pair trade respectively for better trader understanding –

[USDT - BTC] — C2C Trade BUY
User can now use his/her available USDT from their balances and trade and acquire BTC on CoinSwitch PRO

[BTC - USDT] — C2C Trade SELL
User can sell away his/her existing cryptocurrency to obtain corresponding amount of USDT on CoinSwitch PRO

Trading APIs

Order Status Description

Status Description
OPEN Order has not been executed at all
PARTIALLY_EXECUTED Order has been partially executed
CANCELLED User has cancelled 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)
CANCELLATION_RAISED This is an intermeditiate state. We have requested the exchange to cancel the order. This status will come only when the order is cancelled on the exchange.
EXPIRATION_RAISED This is an intermeditiate state. We have requested the exchange to expire the order.

Active Coins

import requests
import json
from urllib.parse import urlparse, urlencode

params = {
    "exchange": "wazirx",
}
payload = {}

endpoint = "/trade/api/v2/coins"

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 getCoins() throws Exception {
    HashMap<String, String> parameters = new HashMap<>();
    HashMap<String, Object> payload = new HashMap<>();

    String path = "?&exchange=" + URLEncoder.encode("wazirx", "UTF-8");
    path = path.replaceAll("%2C", ",");
    path = path.replaceAll("%2F", "/");

    return this.makeRequest("GET","/trade/api/v2/coins" + path, payload, parameters);
    }

The above command returns JSON structured like this:


Response: 200
{
    "data": {
        "wazirx": [
            "BAT/INR",
            "BNB/INR",
            "CHR/INR",
            "CRV/INR",
            "ETH/INR",
            "FTM/INR",
            "LRC/INR",
            "LTC/INR",
            "MKR/INR",
            "OGN/INR",
            "OMG/INR",
            "REQ/INR",
            "SXP/INR",
            "TRX/INR",
            "UMA/INR",
            "UNI/INR",
            "XLM/INR",
            "XRP/INR",
            "YFI/INR",
            "ZRX/INR",
            "BICO/INR",
            "COMP/INR",
            "COTI/INR",
            "DOGE/INR",
            "GALA/INR",
            "IOST/INR",
            "PEPE/INR",
            "SAND/INR",
            "USDT/INR",
            "YFII/INR",
            "1INCH/INR",
            "ALICE/INR",
            "JASMY/INR",
            "MATIC/INR"
        ]
    }
}

Use the following endpoint to check all the active coins for an exchange:

HTTP Request

METHOD GET

ENDPOINT https://coinswitch.co/trade/api/v2/coins

Request Parameters

Parameter Type Mandatory Description
exchange string YES Allowed values: “coinswitchx”/“wazirx”/"c2c1"/ "c2c2" (case insensitive)

Create Order

import requests
import json

url = "https://coinswitch.co/trade/api/v2/order"

payload = {
   "side":"sell",
   "symbol":"BTC/USDT",
   "type":"limit",
   "price":26000,
   "quantity":0.0009,
   "exchange":"c2c1"
}

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/USDT");
        payload.put("type", "limit");
        payload.put("quantity", 0.0009);
        payload.put("price", 26000);
        payload.put("exchange", "c2c1");
        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/USDT",
      "price":26000, # price at which Order was placed by the user
      "average_price":0, # price at which the order got executed
      "orig_qty":0.0009, # quantity at which order was placed
      "executed_qty":0, # quantity that got executed
      "status":"OPEN",
      "side":"SELL",
      "exchange":"c2c1",
      "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 LIMIT: 100 requests per 10 second

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). The quote currency can be USDT/BTC/INR.
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”/"c2c1"/"c2c2" (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 cancelled
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
   }
}

Get Order

import requests
import json
from urllib.parse import urlparse, urlencode

params = {
    "order_id": "698ed406-8ef5-4664-9779-f7978702a447",
}
payload = {}

endpoint = "/trade/api/v2/order"

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 getOrder() throws Exception {
    HashMap<String, String> parameters = new HashMap<>();
    HashMap<String, Object> payload = new HashMap<>();

    String path = "?&order_id=" + URLEncoder.encode("698ed406-8ef5-4664-9779-f7978702a447", "UTF-8");
    path = path.replaceAll("%2C", ",");
    path = path.replaceAll("%2F", "/");

    return this.makeRequest("GET","/trade/api/v2/order" + path, payload, parameters);
    }

The above command returns JSON structured like this:


Response 200
{
   "data":{
      "order_id":"698ed406-8ef5-4664-9779-f7978702a447",
      "symbol":"BTC/USDT",
      "price":27000,
      "average_price":"0",
      "orig_qty":37.79055,
      "executed_qty":0,
      "status":"OPEN",
      "side":"SELL",
      "exchange":"c2c1",
      "order_source":"API_TRADING",
      "created_time":1695365983000,
      "updated_time":1695365983000
   }
}

Use the following endpoint to check order details for a particular order:

HTTP Request

METHOD GET

ENDPOINT https://coinswitch.co/trade/api/v2/order

Request Parameters

Parameter Type Mandatory Description
order_id string YES order_id of the order that you want to fetch

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
      }
    ]
  }
}

# If no orders are present 

Response 200
{
  "data": {
    "orders": []
  }
}

Use the following endpoint to check open orders:

HTTP Request

METHOD GET

ENDPOINT https://coinswitch.co/trade/api/v2/orders

REQUEST LIMIT: 10000 requests per 10 second

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 (case insensitive) Example: "BTC/INR" "SHIB/INR" "BTC/USDT" "btc/inr,eth/inr"
exchanges string No Allowed values: (case insensitive) "coinswitchx,wazirx,c2c1, c2c2" / "coinswitchx" / "wazirx"/ "c2c1"/ "c2c2"
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
      }
    ]
  }
}

# If no orders are present 

Response 200
{
  "data": {
    "orders": []
  }
}

Use the following endpoint to check closed orders:

HTTP Request

METHOD GET

ENDPOINT https://coinswitch.co/trade/api/v2/orders

REQUEST LIMIT: 10000 requests per 10 second

Request Parameters

Parameter Type Mandatory Description
count string No Default value 500
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 (case insensitive) Example: "BTC/INR" "SHIB/INR" "BTC/USDT" "btc/inr,eth/inr"
exchanges string No Allowed values: (case insensitive) "coinswitchx,wazirx,c2c1, c2c2" / "coinswitchx" / “wazirx" / "c2c1"/"c2c2"
type string No Default value Limit
status string No Order status
open bool No Default value is False

Note : This API response would contain the latest 500 row data entries, for older records please reach out to us at api@coinswitch.co for support

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_order":"0.0019",
         "main_balance":"0.00008393",
         "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_order":"0",
         "main_balance":"99983.2566",
         "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

REQUEST LIMIT: 5000 requests per 10 second

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 (case insensitive) Allowed values: "coinswitchx"/ "wazirx" / "c2c1"/ "c2c2"
symbol string No (case insensitive) Example: "BTC/INR" "SHIB/INR" "BTC/USDT"

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
            "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 (case insensitive) Allowed values: "coinswitchx"/ "wazirx" / "c2c1"/ "c2c2"
symbol string Yes (case insensitive) Example: "BTC/INR" "SHIB/INR" "BTC/USDT". The quote currency can be USDT/BTC/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 (case insensitive) Allowed values: "coinswitchx" / "wazirx" / "c2c1"/ "c2c2"
symbol string Yes (case insensitive) Example: "BTC/INR" "SHIB/INR" "BTC/USDT".The quote currency can be USDT/BTC/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 (case insensitive) Allowed values: "coinswitchx" / "wazirx" / "c2c1"/"c2c2*"
symbol string Yes (case insensitive) Example: “BTC/INR" "SHIB/INR" “BTC/USDT". The quote currency can be USDT/BTC/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",
            "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",
            "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 (case insensitive) Allowed values "coinswitchx" / "wazirx" / "c2c1"/"c2c2"

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",
            "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",
            "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 (case insensitive) Allowed values "coinswitchx" / "wazirx" / "c2c1"/"c2c2"
symbol string Yes (case insensitive) Example: “BTC/INR" "SHIB/INR" “BTC/USDT".The quote currency can be USDT/BTC/INR.

Error Scenarios

HTTP Error Codes

Custom Error Messages

WebSockets

How to connect ?

Socket Config Value
Type Socket.IO
Version v4
Handshake Path /pro/realtime-rates-socket/spot/{parameter}
Base URL wss://ws.coinswitch.co/
Parameter Type Mandatory Description
parameter string Yes (case insensitive) Allowed values "coinswitchx" / "wazirx" / "c2c1"/"c2c2"

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
C2C1 baseurl + /c2c1
C2C2 baseurl + /c2c2

Client Set Up for Websockets

Order Book

Whenever a new order is placed or a change happens in order book/market depth, web socket will send an update.

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/spot', 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/spot/?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"
        ]
    ]
  }

Candlestick

The socket will share the candlestick data last 1 min if trades are executed on given pair.

Event Name = "FETCH_CANDLESTICK_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/spot', wait=True, wait_timeout=3600)
subscribe_data = {
    'event': 'subscribe',
    'pair': pair
}
sio.emit(FETCH_CANDLESTICK_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 onCandlestickEvent() {
    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_CANDLESTICK_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/spot/?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
Sample response
{
  "o": "19.000000000000", //open
  "h": "19.000000000000", //high
  "l": "19.000000000000", //low
  "c": "19.000000000000", // close
  "volume": "470.300000000000",
  "end_time": "1699423980000",
  "symbol": "BAT,INR",
  "interval": "1"
}

Trades

Whenever a trade gets executed, the web socket will send an update.

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/spot', 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/spot/?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
    "p": "1472499.0",   // Price
    "q": "0.0004",      // Quantity
    "s": "BTC,INR",     // Symbol
    "t": 395531528,     // Trade ID
    "e": "wazirx"       // Exchange
}

Terms and Conditions (T&Cs)

CoinSwitch Crypto Aggregator Platform
CoinSwitch PRO API Trading - Terms & Conditions
1. These Application Programming Interface (API) License Terms and Conditions (“API Terms”) shall govern the use of the API of CoinSwitch for the users of CoinSwitch PRO to undertake various trades (“Services”) by Users who fulfill the Eligibility Criteria stated in the Terms of Use (the “Terms”) and these API Terms. The User hereby agrees and acknowledges that upon accessing any CoinSwitch PRO API (defined hereinafter), and/or any other information, service, feature governed by terms contained herein, the User shall be bound by the Terms and these API Terms, as updated, modified, and/or replaced from time to time at the sole discretion of CoinSwitch without any prior notice to You. You are advised to review these API Terms for any such amendment, replacement or changes to the terms contained herein and any future use or access to any Services covered herein. These API Terms incorporate by reference and supplements the Terms and the Trading Policy.
Capitalized terms used but not defined herein shall have the meanings given to them in the Terms and/or the Trading Policy. In the event of a conflict between the Terms and these API Terms or the Trading Policy and these API Terms, these API Terms will prevail to the extent of the conflict. 2. AVAILING THE SERVICES BEING OFFERED BY COINSWITCH CONSTITUTES A LEGAL AGREEMENT BETWEEN YOU, AS THE USER OF THE PLATFORM, AND COINSWITCH, AS THE OPERATOR OF THE PLATFORM AND PROVIDER OF SERVICES. BY REGISTERING YOUR USER’S COINSWITCH API ACCOUNT WITH COINSWITCH AND BY AVAILING COINSWITCH’S SERVICES, YOU ARE HEREBY PROVIDING US YOUR EXPRESS CONSENT TO ABIDE WITH THESE API TERMS. IF YOU DO NOT AGREE WITH THESE API TERMS, PLEASE DO NOT PROCEED FURTHER TO USE/ ACCESS THE SERVICES. ALSO, IN THE ABSENCE OF AN ACCEPTANCE OF THE API TERMS BY YOU, WE WILL NOT BE ABLE TO PROVIDE THE SERVICES TO YOU. 3. Definitions 3.1 “API” means certain application program interface / software (in object code form) either owned by or licensed to CoinSwitch which could be integrated with the software or any application or tools of the User (that the User will create using any software that is not provided by CoinSwitch) that will allow Users of CoinSwitch PRO to access all data related to the trading activity on any website, applications or platform provided by CoinSwitch and/ or execute trades and shall include corrections and fixes furnished by or on behalf of CoinSwitch from time to time. The term APIs shall include all the Intellectual Property Rights contained in or in relation thereto. 4. API License:
4.1 Subject to the terms of these API Terms and in accordance with, and subject to, the Terms, as updated from time to time, CoinSwitch shall make available APIs to the User on a limited, personal, non-exclusive, non-transferable and non-sublicensable basis to be installed and used in the territory of India solely for the purpose of entering into trades with other counterparties on third-party Crypto exchanges. The User is responsible for, and must provide and maintain, any interface, system, equipment or service required for receipt of data obtained through the API or for the push of User’s data from the Target System (defined hereinafter) to the API.
4.2 For the purpose of using APIs, CoinSwitch hereby permits the User to use any printed and electronic documentation provided to User in connection with the API (including manuals, specifications, training materials and collateral) (“API Documentation”) for the sole purpose of integrating its systems (the “Target System”) with API in accordance with the API Documentation.
4.3 We will provide to you a software generated alphanumeric key-code that will permit you to use the API (the "Key"). The Key is the property of the Company and may be immediately revoked or terminated by the Company. Unless otherwise permitted under these API Terms, You shall never share or disclose the Key to any other person or party, and Key shall remain the confidential information of the Company.
4.4 The User covenants to (i) not reverse engineer or use other techniques to access logic, internal data structures or internal services utilized by APIs and API Documentation or otherwise translate, reverse-engineer, decompile, decrypt, disassemble, reverse assemble, reproduce, adapt, modify, create any derivative work or copy any source code or underlying ideas or algorithms of the API by any means; (ii) not distribute, disclose, publish, market, sell, provide, rent, lease, license, transfer or grant any rights in the API and API Documentation, in full or in part including no “time sharing”, “interval ownership” or similar regime; (iii) not to infringe any Intellectual Property Rights of CoinSwitch, its licensors or any third party and further shall not remove, alter or obscure any identification, copyright, trademark or other proprietary notices, labels or marks on or in the API and the API Documentation, if any; (iv) not modify, adapt, incorporate into or with other platforms, websites, or create a derivative work of any part of the API or the API Documentation; (v) not develop its application in the class production environment; (iv) take reasonable care to protect the APIs and API Documentation from infringement or damage, and to cease all use of the APIs and API Documentation immediately upon termination of these API Terms and revocation of Your access to the Services; (vii) not to use the API and Services for any illegal, restrictive or prohibitive purposes under applicable laws; and (viii) not commercialize (i.e., sell, rent, or lease), copy, store or cache any content of the API Documentation or any content, data or information created or generated from the use of API, other than for the purposes allowed by these API Terms.
4.5 CoinSwitch and/or its third-party licensor(s) owns and retains all right, title and interest to and in all the Intellectual Property Rights in and in relation to the API and API Documentation and any other software provided to the User under these API Terms. Any feedback or suggestions shared by the User on the features, specifications, technology, working, performance, errors, improvements etc. of the API and API Documentation provided herein shall be solely owned by CoinSwitch and/or its third-party licensors. 5. Trading Arrangement
5.1 You acknowledge and agree that for Crypto to Crypto trades, You have the option to place buy / sell orders using only Limit Orders.
5.2 You acknowledge and agree that in order to utilize the Services, you will be required to use certain third-party tools, External Platforms or resources which may be referred to in the API Documentation or generally required by you to avail the Services. For the avoidance of doubt, it is reiterated that You acknowledge that the Platform/ CoinSwitch is providing any such links or references of External Platforms or resources to You, including APIs to various third party Crypto exchanges, only as a convenience to You and that the Platform/ CoinSwitch makes no representations whatsoever about any External Platforms which You may access through or via the API, including such external platforms being free of such items as viruses, worms, trojan horses, and other items of a destructive nature. CoinSwitch is not responsible for the availability of, and content provided on any External Platforms. You are requested to review the terms of use and policies posted by such External Platforms regarding privacy and other topics before use. The Platform/ CoinSwitch is not responsible for third party content accessible through the Platform and API, including opinions, advice, statements, prices, activities, and advertisements, and You shall bear all risks associated with the use of such content or trading Cryptos on such External Platforms.
5.3 You acknowledge and agree that for the sake of convenience only the value of Your Cryptos purchased through Crypto to Crypto trades will be reflected in Indian Rupees and not in the value of the exchanged Crypto. The approximate Indian Rupee value of such Cryptos will be calculated based on the last traded price of the exchanged Crypto on CoinSwitchX, unless CoinSwitchX is nonoperational due to any reason in which case the last traded price of the exchanged Crypto on WazirX or any other third party exchange will be considered which offers INR trading pairs, at the time of the trade. For the avoidance of doubt, it is clarified that if You purchase 100 MATIC (1 MATIC= 0.5 USDT) using 50 USDT, the value of 100 MATIC will be reflected as the last traded Indian Rupee value of 50 USDT on CoinSwitchX, unless CoinSwitchX is non-operational due to any reason in which case the last traded price of the exchanged Crypto on WazirX or any other third party exchange will be considered which offers INR trading pairs, at the time of purchase. If the value of 1 USDT at the time of purchase is INR 88, the value of the 100 MATIC in Your Account will be reflected as INR 4400.
5.4 Certain third party Crypto exchanges may be global in nature. The User must ensure and hereby represents and warrants to CoinSwitch that the User is complying with all the applicable laws when undertaking any trades (including Crypto to Crypto trades) on all given third party Crypto exchanges using the Services. 6. Algo Trading Program
6.1 User Participation: A. Program Description : We may in our sole discretion allow You to avail the services of third party traders on the CS Pro platform who will deploy an algorithm to execute trades (“Creators”) on the CS Pro platform using Your funds in Your User’s LLP Account for an agreed upon duration (“Duration”) to generate a minimum agreed upon percentage of profit (“Expected Profit”) as agreed between You and Creator in writing (“Creator Terms”) under the Algo Trading Program (“Program”). This Program is made available to You by Us in our capacity as an intermediary between You and the Creators who are offering their services under the Program.
B. Program Description : Such Creator will be selected by You out of the options provided by Us to You based on Your assessment and analysis of their past performance data displayed on the CS Pro platform. You may request additional information about the Creator, via email communication, including the name of their business, whether registered or not, their geographic address, customer care number, if any, to make the selection and We will provide You with such information no later than 2 (Two) business days from such request via email communication. Post the execution of Creator Terms, you may via email communication also request for any other information required to be provided under applicable laws and We will provide You with such information no later than 2 (Two) business days from such request via email communication.
You acknowledge and agree that We may modify the list of available Creators at our sole discretion without any prior notice to You. In case of removal of any Creator (“Removed Creator”) from the Program, CoinSwitch will intimate the date of removal (“Removal Date”) of the Removed Creator from the Program as soon as reasonably practicable. If You are availing the services of such Removed Creator, you will have the option to avail their Services until the Removal Date following which You will be required to delete the Key to revoke access of the Creator to Your User’s LLP Account and generate a new Key. You acknowledge and agree that: I. You shall never share or disclose the new Key to any other person or party except for a Creator under the Program, and Key shall remain the confidential information of the Company. In the event of any unauthorized sharing of the Keys, We may revoke, suspend or terminate Your access to Your User’s LLP Account; and II. We will not be liable for any losses or deficiency in Expected Profit in the event of such removal of Creator, for any reason whatsoever.
C. Participation : In order to participate in the Program, You must opt-in by selecting the Creator of Your choice on the CS Pro platform out of the options provided by Us to You. Upon opting-in, You will be provided the contact details via email communication of the Creator for You to independently negotiate and execute the Creator Terms. By opting-in, You acknowledge and agree that: I. CoinSwitch will execute the trades on behalf of You on the CS Pro platform as per the instructions of the Creator per the algorithm deployed by the Creator for the Duration; II. In order to enable the Creator to provide their services, You will share your Keys with the Creator consequently providing access to Your User’s LLP Account to the Creator; and III. CoinSwitch will not be liable for any abuse of the Key and consequently the funds held in Your User’s LLP Account by the Creator during the Duration. IV. You will delete the Key and generate a new Key after the Duration or whenever You discontinue the services of the Creator.
For the avoidance of doubt, it is clarified that: A. You retain beneficial ownership of the Designated Balance and such Designated Balance shall remain the property of You when being managed by the Creator; B. CoinSwitch does not in anyway endorse the trading algorithm or strategy deployed by the Creator; and C. In no event, will CoinSwitch be liable for providing the Expected Profit to You or to make good on the losses incurred by You while availing the services of the Creator under the Program. D. Termination : Subject to the subsistence of Your agreement with the Creator, Your participation in the Program will continue per these API Terms. In the event, You wish to discontinue Your participation in the Program, You must inform us in writing on api@coinswitch.co providing at least 1 (One) business day notice, after which You may delete Your Key and generate a New Key. You acknowledge and agree that CoinSwitch will not be liable for Your failure to delete Your Key shared with the Creator and any ensuing consequences, including but not limited to unauthorised access by the Creator or any other third parties, for the same. In the event You delete Your Key and generate a new Key without informing Us and the Creator at least 1 (one) business day in advance, We may forthwith restrict / terminate Your access and use of the CS Pro platform.
6.2 Creator Participation : In the event You want to provide Your services to a User as a Creator under the Program, You may inform us in writing on api@coinswitch.co expressing your interest in the same with details including the duration of You trading on the CoinSwitch Pro platform and Your gross returns on CoinSwitch Pro platform. Upon receiving such request or on our own accord, We may, at our sole discretion and subject to Your fulfillment of the eligibility criteria listed below, allow You to offer Your services for a fee (“Profit Share”) as a Creator under the Program for a fee.
6.3 Force Majeure : You acknowledge and agree that in the event of a force majeure event, including but not limited to technical issues, unauthorized access, cyberattacks or hacks, no party will be liable to perform their obligations under these API Terms.
6.4 Disclaimers : You acknowledge and agree that the services under this Program are being by the Creator on an as-is basis. We are merely acting as an intermediary for Users to discover the services of the Creators. We will not be liable for generation of a certain profit or for the efficacy and accuracy of the algorithm and/ or the services of the Creator under the Program. You agree that we are not liable to make good on the Expected Profit or Profit Share in any event whatsoever. 7. Fees And Charges
7.1 The fees for API trades are given in the CoinSwitch PRO account of the User. The fee may be revised (i.e. increased or decreased) from time to time, and the User is required to check User’s CoinSwitch PRO account each time before entering into any API trade. CoinSwitch may, in its sole discretion, also inform you via other electronic communication modes on any such changes. The invoices, contract note, and taxation on the same (TDS and GST) will be as per the Terms.
7.2 The User hereby agrees and acknowledges that presently no fees or charges are levied by CoinSwitch only for the use of the API. However, nothing contained in this section, or these API Terms shall restrict or limit the right of CoinSwitch to charge fees or levy charges for use of the APIs in addition to the charges or fees for API trades.
7.3 Conditions pertaining to star-marked(*) offers on API Trading
8. Termination
8.1 The User acknowledges and agrees that CoinSwitch may at any time in its sole discretion revoke the User’s access to the API or modify these API Terms without any prior notice or liability to the User.

Contact us

You can reach out to us at api@coinswitch.co in case of any queries/suggestions