### Python: Example GET API Call with Signature Source: https://api-trading.coinswitch.co/index This Python example illustrates a complete GET API request to CoinSwitch, including parameter definition, signature generation using the Ed25519 algorithm, and setting the required `X-AUTH-SIGNATURE`, `X-AUTH-APIKEY`, and `X-AUTH-EPOCH` headers for authentication. ```python from cryptography.hazmat.primitives.asymmetric import ed25519 from urllib.parse import urlparse, urlencode import urllib import json import requests import time 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 epoch_time = str(int(time.time() * 1000)) 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 + epoch_time 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, 'X-AUTH-EPOCH': epoch_time } response = requests.request("GET", url, headers=headers, json=payload) ``` -------------------------------- ### API Specification and Response Example for Get Trades Source: https://api-trading.coinswitch.co/index This section details the HTTP request method, endpoint URL, and request limits for the CoinSwitch Get Trades API. It also specifies the mandatory request parameters and provides a structured example of the JSON response returned by the API, including fields like timestamp, price, quantity, exchange, symbol, and market maker status. ```APIDOC HTTP Request: METHOD: GET ENDPOINT: https://coinswitch.co/trade/api/v2/futures/trades REQUEST LIMIT: 100 requests per 60 seconds Request Parameters: - exchange: Type: string Mandatory: Yes Description: Allowed values: "EXCHANGE_2" (case insensitive) - symbol: Type: string Mandatory: Yes Description: Asset symbol whose leverage needs to be updated (BTCUSDT, ETHUSDT etc.) ``` ```JSON { "data": [ { "E": 1732691693128, "p": 0.39391, "q": 133, "e": "EXCHANGE_2", "s": "DOGEUSDT, "m": true }, { "E": 1732691683370, "p": 0.39378, "q": 32, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true }, { "E": 1732691672521, "p": 0.3941, "q": 2286, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true }, { "E": 1732691662133, "p": 0.39401, "q": 1211, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true } ] } ``` -------------------------------- ### Get Futures Transactions API Call Examples Source: https://api-trading.coinswitch.co/index These code examples demonstrate how to programmatically retrieve futures transaction data from the CoinSwitch API. They show how to construct the request, include necessary parameters and authentication headers, and handle the API response. ```Python import requests import json params = { "symbol": "btcusdt", "exchange": "EXCHANGE_2", "type": "commission", "transaction_id" : "c47d28b9-0e68-56e8-892c-5ff1ce5eef3e" } payload = {} endpoint = "/trade/api/v2/futures/transactions" endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params) url = "https://coinswitch.co" + endpoint headers = { 'Content-Type': 'application/json', 'X-AUTH-SIGNATURE': , #https://api-trading.coinswitch.co/#signature-generation 'X-AUTH-APIKEY': } try: response = requests.request("GET", url, headers=headers, json=payload) print("Response JSON:", response.json()) except Exception as e: print(f"An error occurred: {e}") ``` ```Java public String cancelOrder() throws Exception{ HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); String path = "?&symbol=" + URLEncoder.encode("btcusdt", "UTF-8") + "&exchange=" + URLEncoder.encode("EXCHANGE_2", "UTF-8") + "&type=" + URLEncoder.encode("commission", "UTF-8") + "&transaction_id=" + URLEncoder.encode("c47d28b9-0e68-56e8-892c-5ff1ce5eef3e", "UTF-8"); path = path.replaceAll("%2C", ","); path = path.replaceAll("%2F", "/"); return this.makeRequest("GET", "/trade/api/v2/futures/transactions" + path, payload, parameters); } ``` -------------------------------- ### Example Response: Get Open Orders Source: https://api-trading.coinswitch.co/index This snippet illustrates the JSON structure returned by the 'Get Open Orders' API endpoint upon a successful request (HTTP 200). It shows an array of order objects, each containing detailed information, and also demonstrates the response for when no open orders are present. ```JSON { "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": [] } } ``` -------------------------------- ### Ping API Endpoint (Python Example) Source: https://api-trading.coinswitch.co/index This Python code snippet demonstrates how to perform a GET request to the CoinSwitch ping API endpoint. It uses the `requests` library and includes necessary headers like `Content-Type`, `X-AUTH-SIGNATURE`, and `X-AUTH-APIKEY` for authentication. ```python import requests import json url = "https://coinswitch.co/trade/api/v2/ping" payload = {} headers = { 'Content-Type': 'application/json', 'X-AUTH-SIGNATURE': , 'X-AUTH-APIKEY': } response = requests.request("GET", url, headers=headers, json=payload) ``` -------------------------------- ### Ping API Endpoint (Java Example) Source: https://api-trading.coinswitch.co/index This Java method illustrates how to call the CoinSwitch ping API endpoint. It prepares the necessary parameters and payload, then utilizes a `makeRequest` helper method to send a GET request to `/trade/api/v2/ping`. ```java public String ping() throws Exception { HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); return this.makeRequest("GET", "/trade/api/v2/ping", payload, parameters); } ``` -------------------------------- ### Example JSON Response for Trading Fee API Source: https://api-trading.coinswitch.co/index Provides an example of the JSON structure returned by the `/trade/api/v2/tradingFee` endpoint, showing fee details (maker/taker fees, discounts, timestamp) for various cryptocurrencies on the "coinswitchx" exchange. ```json { "data": { "coinswitchx": { "AVAX": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "AXP": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "AXS": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "ETH": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "FIL": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "PENDLE": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "SHIB": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "USDT": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 }, "YFI": { "maker_fee": 0.0009, "taker_fee": 0.0009, "maker_discount_percentage": 100, "taker_discount_percentage": 100, "maker_fee_after_discount": 0, "taker_fee_after_discount": 0, "timestamp": 1721909805 } } } } ``` -------------------------------- ### Java Example: Coinswitch API Key Validation Source: https://api-trading.coinswitch.co/index This Java snippet provides an example for validating API keys with Coinswitch. It includes methods for constructing the signature message, generating the signature using BouncyCastle's Ed25519, and making authenticated HTTP requests (GET, POST, PUT, DELETE) to the Coinswitch API. It demonstrates how to handle parameters and payloads for different request types. ```Java 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 parameters = new HashMap<>(); HashMap payload = new HashMap<>(); return this.makeRequest("GET", "/trade/api/v2/validate/keys", payload, parameters); } public String makeRequest(String method, String endpoint, HashMap payload, HashMap 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 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 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"; } ``` -------------------------------- ### Create Order API Response Examples Source: https://api-trading.coinswitch.co/index Examples of JSON responses from the Create Order API, including a successful 200 OK response with detailed order information (order_id, symbol, price, quantity, status) and common error responses (422, 400, 401) indicating various issues. ```APIDOC RESPONSE 200 { "data":{ "order_id":"927db2d9-643c-47a3-9c0f-78741ac95cf5", "symbol":"BTC/USDT", "price":26000, "average_price":0, "orig_qty":0.0009, "executed_qty":0, "status":"OPEN", "side":"SELL", "exchange":"c2c1", "order_source":"API_TRADING", "created_time":1689661638000, "updated_time":1689661639000 } } ``` ```APIDOC RESPONSE: 422 { "message": "Input price must be of type number" } ``` ```APIDOC RESPONSE: 400 { "message": "Amount is more than available balance" } ``` ```APIDOC RESPONSE: 401 { "message": "Invalid access" } ``` -------------------------------- ### Retrieve Trading Information Source: https://api-trading.coinswitch.co/index This section provides code examples in Python and Java, along with API documentation, for checking trading details such as minimum/maximum quote and precision for a specific cryptocurrency symbol on a given exchange. It outlines the GET request to the `/trade/api/v2/tradeInfo` endpoint, including parameters and the expected JSON response. ```python import requests import json url = "https://coinswitch.co/trade/api/v2/tradeInfo" params = { "exchange": "coinswitchx", "symbol": "BTC/INR" } headers = { 'Content-Type': 'application/json', 'X-AUTH-APIKEY': } response = requests.request("GET", url, headers=headers, params=params) ``` ```java public String getTradeInfo() throws Exception { HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); parameters.put("exchange","coinswitchx"); parameters.put("symbol","BTC/INR"); String response = this.makeRequest("GET","/trade/api/v2/tradeInfo", payload, parameters); return response; } ``` ```APIDOC HTTP Request METHOD `GET` ``` -------------------------------- ### Handle HTTP API Requests (GET, POST, PUT, DELETE) in Java Source: https://api-trading.coinswitch.co/index This core method orchestrates API calls, distinguishing between GET and other methods (POST, PUT, DELETE). It handles request setup, JSON serialization for payloads, setting headers, sending requests, and processing responses. It uses `HttpURLConnection` for non-GET requests and `HttpClient` for GET requests. ```Java HttpResponse 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"; } ``` -------------------------------- ### Python Example: Coinswitch API Key Validation Source: https://api-trading.coinswitch.co/index This Python snippet illustrates how to validate API keys with Coinswitch. It demonstrates the process of constructing the signature message, signing it using Ed25519 with the secret key, and then making an authenticated GET request to the `/trade/api/v2/validate/keys` endpoint. It uses `cryptography.hazmat.primitives.asymmetric.ed25519` for signing and `requests` for HTTP calls. ```Python 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) ``` -------------------------------- ### Install Python Dependencies for CoinSwitch PRO API Source: https://api-trading.coinswitch.co/index Commands to install necessary Python libraries required for running CoinSwitch PRO API trading scripts. These dependencies include cryptography for secure operations, requests for HTTP communication, python-socketio for WebSocket connections, and websocket-client for WebSocket interactions. ```Python 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 ``` -------------------------------- ### Example Response: Get Single Order Source: https://api-trading.coinswitch.co/index This snippet illustrates the JSON structure returned by the 'Get Order' API endpoint upon a successful request (HTTP 200). It shows the various fields related to an order, such as `order_id`, `symbol`, `price`, `status`, and timestamps. ```JSON { "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 } } ``` -------------------------------- ### API Response Example: Futures Ticker Data Source: https://api-trading.coinswitch.co/index Illustrates the JSON structure returned by the GET Ticker endpoint, providing detailed information such as 24-hour price range, last price, timestamp, best bid/ask, volume, and funding rates for a specific asset on an exchange. ```json STATUS CODE 200 { "data": { "EXCHANGE_2": { "low_price_24h": "94707.00", "high_price_24h": "97276.00", "last_price": "95136.60", "symbol": "BTCUSDT", "exchange": "EXCHANGE_2", "timestamp": 1732821806680, "best_ask_price": "95136.70", "best_bid_price": "95136.60", "price_24h_pcnt": "-1.297300", "base_asset_volume_24h": "93707.6800", "quote_asset_volume_24h": "8970676685.2608", "index_price": 95046.53, "mark_price": 95136.7, "open_interest": "67529.878", "open_interest_value": "6424569744.32", "funding_rate": 0.00039681, "next_funding_timestamp": 1732838400000, "best_bid_size": "3.189", "best_ask_size": "3.963" } } } ``` -------------------------------- ### Example JSON Response for Get Futures Transactions Source: https://api-trading.coinswitch.co/index Illustrates the expected JSON structure returned by the CoinSwitch futures transactions API upon a successful GET request. It includes an array of transaction objects, each detailing exchange, transaction ID, symbol, type, quote asset, and amount. ```APIDOC STATUS CODE 200 { "data": [ { "exchange": "EXCHANGE_2", "transaction_id": "678708aa-507b-4881-8b3f-1a50b63dd0c4-0193677c-0544-77d1-b3a6-2130d671e54c", "symbol": "ADAUSDT", "type": "FUNDING_FEE", "quote_asset": "USDT", "amount": "0.00099946" }, { "exchange": "EXCHANGE_2", "transaction_id": "8b81b763-df36-4c93-9bc8-9a93d65b8546-0193677c-0a0d-75ca-9303-cee4ec5eef3e", "symbol": "DOGEUSDT", "type": "FUNDING_FEE", "quote_asset": "USDT", "amount": "-0.002482813801" }, { "exchange": "EXCHANGE_2", "transaction_id": "8b81b763-df36-4c93-9bc8-9a93d65b8546", "symbol": "DOGEUSDT", "type": "ADD_MARGIN", "quote_asset": "USDT", "amount": "16" }, { "exchange": "EXCHANGE_2", "transaction_id": "8b81b763-df36-4c93-9bc8-9a93d65b8546", "symbol": "DOGEUSDT", "type": "ADD_MARGIN", "quote_asset": "USDT", "amount": "16" } ] } ``` -------------------------------- ### Configure Gradle Dependencies for Java Project Source: https://api-trading.coinswitch.co/index Illustrates how to add external libraries to a Java project by modifying the `build.gradle` file. This example adds the Apache Commons Lang library. ```Gradle dependencies { implementation 'org.apache.commons:commons-lang3:3.12.0'} ``` -------------------------------- ### Cancel Order API Response Example Source: https://api-trading.coinswitch.co/index An example of a successful 200 OK JSON response from the Cancel Order API, showing the updated status of the order as 'CANCELLED' along with other relevant order details. ```APIDOC RESPONSE 200 { "data":{ "order_id":"698ed406-8ef5-4664-9779-f7978702a447", "symbol":"BTC/INR", "price":2300000, "average_price":0, "orig_qty":5e-05, "executed_qty":0, "status":"CANCELLED", "side":"SELL", "exchange":" ``` -------------------------------- ### Fetch All-Pairs Ticker Data Source: https://api-trading.coinswitch.co/index This section provides code examples in Python and Java for retrieving real-time ticker information for all trading pairs from the CoinSwitch API's `/trade/api/v2/futures/all-pairs/ticker` endpoint. Both examples demonstrate how to set up the request with necessary parameters and authentication headers. ```Python import requests import json from urllib.parse import urlparse, urlencode params = { "exchange": "EXCHANGE_2" } payload = {} endpoint = "/trade/api/v2/futures/all-pairs/ticker" endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params) url = "https://coinswitch.co" + endpoint headers = { 'Content-Type': 'application/json', 'X-AUTH-SIGNATURE': "", #https://api-trading.coinswitch.co/#signature-generation 'X-AUTH-APIKEY': "" } try: response = requests.request("GET", url, headers=headers, json=params) print("Response JSON:", response.json()) except Exception as e: print(f"An error occurred: {e}") ``` ```Java public String allPairsTicker() throws Exception{ HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); String path = "?&exchange=" + URLEncoder.encode("EXCHANGE_2", "UTF-8"); path = path.replaceAll("%2C", ","); path = path.replaceAll("%2F", "/"); return this.makeRequest("GET", "/trade/api/v2/futures/all-pairs/ticker", payload, parameters); } ``` -------------------------------- ### Get Open Trading Positions Source: https://api-trading.coinswitch.co/index This snippet illustrates how to fetch all open trading positions for a specified exchange and symbol from the CoinSwitch API. It provides code examples in Python and Java, along with the API endpoint and a detailed example of the expected response structure. ```python import requests import json params = { "exchange": "EXCHANGE_2", "symbol": "btcusdt" } payload = {} endpoint = "/trade/api/v2/futures/positions" endpoint += ('&', '?')[urlparse(endpoint).query == ''] + urlencode(params) url = "https://coinswitch.co" + endpoint headers = { 'Content-Type': 'application/json', 'X-AUTH-SIGNATURE': , #https://api-trading.coinswitch.co/#signature-generation 'X-AUTH-APIKEY': } try : response = requests.request("GET", url, headers=headers, json=params) print("Response JSON:", response.json()) except Exception as e: print(f"An error occurred: {e}") ``` ```java public String getPositions() throws Exception{ HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); String path = "?&exchange=" + URLEncoder.encode("EXCHANGE_2", "UTF-8") + "&symbol=" + URLEncoder.encode("btcusdt", "UTF-8"); path = path.replaceAll("%2C", ","); path = path.replaceAll("%2F", "/"); return this.makeRequest("GET", "/trade/api/v2/futures/positions" + path, payload, parameters); } ``` ```APIDOC METHOD: GET ENDPOINT: https://coinswitch.co/trade/api/v2/futures/positions ``` ```json STATUS CODE 200 { "data": [ { "exchange": "EXCHANGE_2", "position_id": "8b81b763-df36-4c93-9bc8-9a93d65b8546", "symbol": "DOGEUSDT", "position_side": "LONG", "leverage": "25", "position_size": "65", // in base_quantity (ex. 65 DOGE) "position_value": "25.09455", // in USDT "position_margin": "34.052117186199", // in USDT "maint_margin": "37.641825", // minimum margin balance after adjusting unrealised pnl required to prevent liquidation "avg_entry_price": "0.38607", "mark_price": "0.38231", "last_price": "0.38135", "unrealised_pnl": "0.3068", "liquidation_price": "0.129122150942", "status": "OPEN", "created_at": 1732617093684, "updated_at": 1732636761825 }, { "exchange": "EXCHANGE_2", "position_id": "678708aa-507b-4881-8b3f-1a50b63dd0c4", "symbol": "ADAUSDT", "position_side": "SHORT", "leverage": "25", "position_size": "11", "position_value": "10.9681", "position_margin": "6.779670888571", "maint_margin": "15.6783", "avg_entry_price": "0.9971", "mark_price": "0.9502", "last_price": "0.9503", "unrealised_pnl": "-0.5148", "liquidation_price": "1.577930285714", "status": "OPEN", "created_at": 1732613252041, "updated_at": 1732636762998 } ] } ``` -------------------------------- ### Python: Get Closed Orders from CoinSwitch API Source: https://api-trading.coinswitch.co/index Demonstrates how to fetch closed orders using the CoinSwitch API with Python's requests library. This example constructs the request URL with parameters, sets necessary headers including API key and signature, and executes a GET request. ```python 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': , 'X-AUTH-APIKEY': } response = requests.request("GET", url, headers=headers, json=payload) ``` -------------------------------- ### Retrieve Active Coins for an Exchange Source: https://api-trading.coinswitch.co/index This section provides code examples in Python and Java, along with API documentation, for fetching a list of active cryptocurrency pairs available on a specified exchange. It details the GET request to the `/trade/api/v2/coins` endpoint, including required parameters and expected JSON response format. ```python 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': , 'X-AUTH-APIKEY': } response = requests.request("GET", url, headers=headers, json=payload) ``` ```java public String getCoins() throws Exception { HashMap parameters = new HashMap<>(); HashMap 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); } ``` ```APIDOC 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) ``` -------------------------------- ### Example Futures Ticker Data JSON Response Source: https://api-trading.coinswitch.co/index This JSON snippet provides an example of the data structure returned by the CoinSwitch Futures API for all trading pairs. It includes various metrics such as 24-hour price changes, volumes, last traded prices, best bid/ask prices, open interest, and funding rates for multiple cryptocurrency pairs. ```JSON { "BTCUSDT": { "quote_asset_volume_24h": "1543061421.3868", "index_price": 0.39839, "mark_price": 0.39871, "open_interest": "2554940115", "open_interest_value": "1018680173.25", "funding_rate": 0.00026608, "next_funding_timestamp": 1732838400000, "best_bid_size": "32177", "best_ask_size": "16740" }, "1000PEPEUSDT": { "low_price_24h": "0.0189620", "high_price_24h": "0.0203749", "last_price": "0.0195068", "symbol": "1000PEPEUSDT", "exchange": "EXCHANGE_2", "timestamp": 1732821805704, "best_ask_price": "0.0195097", "best_bid_price": "0.0195096", "price_24h_pcnt": "-2.137600", "base_asset_volume_24h": "35943473800.0000", "quote_asset_volume_24h": "706593280.9413", "index_price": 0.0194707, "mark_price": 0.0194997, "open_interest": "21465240900", "open_interest_value": "418565757.98", "funding_rate": 0.00084028, "next_funding_timestamp": 1732838400000, "best_bid_size": "41500", "best_ask_size": "300" }, "DASHUSDT": { "low_price_24h": "35.37", "high_price_24h": "38.75", "last_price": "36.65", "symbol": "DASHUSDT", "exchange": "EXCHANGE_2", "timestamp": 1732821806294, "best_ask_price": "36.67", "best_bid_price": "36.66", "price_24h_pcnt": "-2.318700", "base_asset_volume_24h": "109829.6100", "quote_asset_volume_24h": "4036827.9508", "index_price": 36.61, "mark_price": 36.65, "open_interest": "172245.68", "open_interest_value": "6312804.17", "funding_rate": 0.00025568, "next_funding_timestamp": 1732838400000, "best_bid_size": "31.50", "best_ask_size": "15.75" }, "HMSTRUSDT": { "low_price_24h": "0.003727", "high_price_24h": "0.003968", "last_price": "0.003876", "symbol": "HMSTRUSDT", "exchange": "EXCHANGE_2", "timestamp": 1732821804869, "best_ask_price": "0.003876", "best_bid_price": "0.003875", "price_24h_pcnt": "0.025800", "base_asset_volume_24h": "4870172860.0000", "quote_asset_volume_24h": "18715274.1632", "index_price": 0.003871, "mark_price": 0.003875, "open_interest": "3444025580", "open_interest_value": "13345599.12", "funding_rate": 0.00038998, "next_funding_timestamp": 1732838400000, "best_bid_size": "350230", "best_ask_size": "167430" }, "EIGENUSDT": { "low_price_24h": "3.5606", "high_price_24h": "4.1524", "last_price": "3.6003", "symbol": "EIGENUSDT", "exchange": "EXCHANGE_2", "timestamp": 1732821805369, "best_ask_price": "3.6007", "best_bid_price": "3.5999", "price_24h_pcnt": "-6.747300", "base_asset_volume_24h": "17627689.0000", "quote_asset_volume_24h": "67600321.6591", "index_price": 3.5964, "mark_price": 3.5991, "open_interest": "6218291", "open_interest_value": "22380251.14", "funding_rate": 0.0001, "next_funding_timestamp": 1732838400000, "best_bid_size": "217", "best_ask_size": "3" } } ``` -------------------------------- ### API Error Response Example: Invalid Access Source: https://api-trading.coinswitch.co/index This JSON snippet shows an example of an error response, specifically for an 'Invalid access' (HTTP 401) scenario, indicating issues with authentication credentials. ```json RESPONSE: 401 { "message": "Invalid access" } ``` -------------------------------- ### Retrieve User Portfolio Source: https://api-trading.coinswitch.co/index These code snippets demonstrate how to fetch a user's portfolio data from the CoinSwitch API. They make a GET request to the `/trade/api/v2/user/portfolio` endpoint, including necessary authentication headers and parameters. ```Python import requests import json url = "https://coinswitch.co/trade/api/v2/user/portfolio" payload={} headers = { 'Content-Type': 'application/json', 'X-AUTH-SIGNATURE': , 'X-AUTH-APIKEY': } response = requests.request("GET", url, headers=headers, json=payload) ``` ```Java public String portfolio() throws Exception { HashMap parameters = new HashMap<>(); HashMap payload = new HashMap<>(); return this.makeRequest("GET", "/trade/api/v2/user/portfolio", payload, parameters); } ``` -------------------------------- ### Portfolio API Endpoint Details Source: https://api-trading.coinswitch.co/index This section provides the essential HTTP details for accessing the user portfolio. It specifies the GET method, the full endpoint URL, and the request limit for this particular API call. ```APIDOC METHOD `GET` ENDPOINT `https://coinswitch.co/trade/api/v2/user/portfolio` REQUEST LIMIT: `5000 requests per 10 second` ``` -------------------------------- ### Execute HTTP GET API Request in Java Source: https://api-trading.coinswitch.co/index This method specifically handles HTTP GET requests using Java's `HttpClient`. It builds the request with the provided URL and headers, then sends it and returns the `HttpResponse`, allowing for easy retrieval of the response body. ```Java private HttpResponse callGetApi(String url, Map headers, HashMap payload) throws Exception { HttpClient client = HttpClient.newBuilder().build(); HttpRequest.Builder requestBuilder; requestBuilder = HttpRequest.newBuilder() .GET() .uri(new URI(url)); for (Map.Entry entry : headers.entrySet()) { requestBuilder.header(entry.getKey(), entry.getValue()); } HttpRequest request = requestBuilder.build(); return client.send(request, HttpResponse.BodyHandlers.ofString()); } ``` -------------------------------- ### Example: Sending a Signed DELETE Request to Coinswitch API Source: https://api-trading.coinswitch.co/index This section provides complete examples for making a signed DELETE request to the Coinswitch API, specifically for cancelling an order. It demonstrates how to integrate the signature generation with the HTTP request execution, including setting necessary authentication headers in both Java and Python. ```Java 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 parameters = new HashMap<>(); HashMap 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 payload, HashMap 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 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")){ ``` ```Python 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) ``` -------------------------------- ### Example JSON Response for TDS Information Source: https://api-trading.coinswitch.co/index This JSON structure illustrates a successful response from the TDS API endpoint. It provides the total TDS amount and the financial year to which it pertains. ```APIDOC { "data": { "total_tds_amount": 459.12, "financial_year": "2024-2025" } } ``` -------------------------------- ### API Endpoint: Get Trade Info Source: https://api-trading.coinswitch.co/index Provides essential details required to initiate trading. This includes exchange precision, as well as minimum and maximum values for active coins on the platform. ```APIDOC GET /trade/api/v2/tradeInfo ``` -------------------------------- ### CoinSwitch Server Time API Response Format Source: https://api-trading.coinswitch.co/index An example of the JSON structure returned by the CoinSwitch server time API, providing the `serverTime` as a Unix epoch timestamp in milliseconds. ```JSON { "serverTime": 1719905777483 } ``` -------------------------------- ### API Documentation: Futures Ticker Endpoint Details Source: https://api-trading.coinswitch.co/index Provides comprehensive API documentation for the futures ticker endpoint, specifying the HTTP method (GET), the endpoint URL, request limits, and required parameters like exchange and symbol. ```APIDOC ### HTTP Request #### METHOD `GET` #### ENDPOINT `https://coinswitch.co/trade/api/v2/futures/ticker` #### REQUEST LIMIT: `100 requests per 60 seconds` ### Request Parameters | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | exchange | string | Yes | Allowed values: "EXCHANGE_2" (case insensitive) | | symbol | string | Yes | Asset symbol whose leverage needs to be updated (BTCUSDT, ETHUSDT etc.) | Remember — Use valid API key and signature! ``` -------------------------------- ### Sample JSON Response for Order Update Event Source: https://api-trading.coinswitch.co/index An example of the JSON payload received when an order update event occurs. It includes fields such as event time, order ID, status, side, quantity, price, and symbol. ```JSON { "E": 1716390819344, "O": 1716390819339, "e": "COINSWITCHX", "S": "SELL", "V": "0.0003", "X": "OPEN", "i": "35286cf0-8c63-499f-bb43-86b326e4aa38", "o": "LIMIT", "p": "6036000", "s": "btcinr", "v": "0", "z": "0" } ``` -------------------------------- ### Example Real-time Trade Update WebSocket Response Source: https://api-trading.coinswitch.co/index Illustrates the JSON structure of a trade update message received from the WebSocket, detailing fields such as timestamp, price, quantity, exchange, symbol, and market maker status. ```JSON { "data": [ { "E": 1732691693128, "p": 0.39391, "q": 133, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true }, { "E": 1732691683370, "p": 0.39378, "q": 32, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true }, { "E": 1732691672521, "p": 0.3941, "q": 2286, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true }, { "E": 1732691662133, "p": 0.39401, "q": 1211, "e": "EXCHANGE_2", "s": "DOGEUSDT", "m": true } ] } ``` -------------------------------- ### Java Main Application Entry Point for CoinSwitch API Client Source: https://api-trading.coinswitch.co/index This is the main entry point of the Java application, demonstrating how to instantiate the `Main` class and invoke the `getOpenOrders` method. It serves as a simple example of how to initiate an API call and print the response to the console. ```Java public class Main { public static void main(String[] args) throws Exception { Main main = new Main(); String Response = main.getOpenOrders(); System.out.println(Response); } } ``` -------------------------------- ### API Reference: Get Open Orders Source: https://api-trading.coinswitch.co/index This section outlines the API endpoint for querying open trading orders. It specifies the HTTP method, the full endpoint URL, and notes the request limit for this operation. ```APIDOC HTTP Request METHOD GET ENDPOINT https://coinswitch.co/trade/api/v2/orders REQUEST LIMIT: 10000 requests per 10 second ``` -------------------------------- ### Create Order API Endpoint Reference Source: https://api-trading.coinswitch.co/index Detailed API documentation for the POST /trade/api/v2/order endpoint, outlining the HTTP method, endpoint URL, request limits, and all mandatory request parameters (side, symbol, type, price, quantity, exchange) with their types and allowed values. ```APIDOC METHOD POST ENDPOINT https://coinswitch.co/trade/api/v2/order REQUEST LIMIT: 100 requests per 10 second ``` ```APIDOC Parameter: side Type: string Mandatory: Yes Description: Allowed values: "buy"/"sell" (case insensitive) Parameter: symbol Type: string Mandatory: Yes Description: Should be in the format base_currency/quote_currency (case insensitive). The quote currency can be USDT/BTC/INR. Parameter: type Type: string Mandatory: Yes Description: Order type, currently we support only LIMIT order type Parameter: price Type: float Mandatory: Yes Description: Price at which you want to place the order Parameter: quantity Type: float Mandatory: Yes Description: Base quantity that you want to buy or sell Parameter: exchange Type: string Mandatory: Yes Description: Allowed values: "coinswitchx"/"wazirx"/"c2c1"/"c2c2" (case insensitive) ```