API Trading made easy with CoinSwitch PRO: A how-to guide

API Trading Setup Guide for CoinSwitch Pro

API trading or Application Programming Interface trading is a technique to automate the trading process. While extremely useful and popular, API trading involves using basic coding in languages like Python and Java, which can be a bit confusing for users who are trying API trading for the first time.

Yes, manual trading is a good option. But, if you wish to automate the trading process so that you can trade 24*7, then you might want to try the API trading option. Read our detailed blog post API trading vs. manual trading to learn more.

And here’s a not-to-be-missed limited-time offer for you if you are a new API trader: New traders need not pay any fee on all API trades for the first 30 days

We will simplify the API trading process for you so that you can start your automated trading journey with ease.

Prerequisite:

Here is a step-by-step guide to API Trading. 

Getting Started with API Trading set-up 

Step 1: API Key Generation

  • On the API trading home page, you will find the ‘Get Exclusive API Access’ tab. 
  • If you have already logged in, you will see the ‘Generate My Key’ button on your screen. 
  • Click on the ‘Generate My Key’ button. 
  • Upon clicking, an OTP will be sent to your registered mobile number
  • Enter the OTP and press enter. 

Your API Key and your Secret Key will now be visible on your screen. 

API Key 

  • Note down your API key in a safe place. 
  • Your API key will be visible on the screen when you trade.

Secret Key 

  • Copy your Secret Key and save it in a safe place 
  • It won’t be visible again once you refresh the page. 
  • You should never share your Secret Key with anyone. 
  • In case you forget your secret key or misplace it, you can press the ‘Delete Key’ button on the API trading page to delete your existing API and Secret Key and generate new ones. 

Now that we have generated the API and Secret Key, we will proceed to the next step. 

PRO Tip: Never share your API key/secret key with anyone. If the API keys were accidentally compromised, please get the key deactivated and raise a request for new key generation.

Step 2: API Set-Up on your system 

API trading uses computer programming languages. The CoinSwitch Pro API trading supports Python and Java programming languages.
You can select your preferred programming language before you start this part of the API trading setup process.
We will first discuss the steps for Python, followed by Java. Therefore, if you are planning to use Java, you can skip to the Java set-up steps using the side navigation bar. 

Python environment set-up 

Before we get started with Python environment set-up on your system, we have somethings that can help you with the set-up process. Click on the link below to watch the video explaining the Python environment set-up on your system. Additionally, the video also provides a set-by-set guide to your first order creation using your API keys. Watch the video below to start your API trading journey with ease and confidence.

Combine the steps in the video with the written steps below to get a full-proof guide for API trading environment set-up on your system.

You can set up the Python environment on your computer using two different programs:

  1. PyCharm 
  2. VSCode 

We will start with PyCharm. 

Setup With PyCharm

To set up a Python file in PyCharm, follow the instructions given below:

Install PyCharm

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) 
  • Now select “New” -> “Python File”. Give the file a meaningful name and press Enter.

Write your Python code or paste the 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. 
  • PyCharm provides features like syntax highlighting, code completion, and debugging assistance to help you during development.

Install dependency
Open PyCharm Terminal and run the 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.

Congrats! You have successfully set up the environment for API Trading using PyCharm.

Setup With VSCode

Download VSCode according to your system’s compatibility.
Click on the mentioned icon on the left panel in VSCode, search for Python extension, and install it

Mac Set-Up Steps

Open the terminal using the command Ctrl + `

Set up a virtual environment to run Python scripts via:

python3 -m venv venv
source venv/bin/activate

Upgrade pip to install required libraries

pip install --upgrade pip

Install required libraries

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

Run the python script

python <file_name_on_system>.py

Windows Set-Up Steps

Open the command prompt using the command Cmd + R, type cmd, and press Enter

Set up a virtual environment to run a Python script via:

pip install virtualenv
virtualenv myenv
myenv\Scripts\activate

Upgrade pip to install required libraries

pip install --upgrade pip

Install required libraries

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 script

python <file_name_on_system>.py

Java Client

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

Install IntelliJ IDEA

Install Gradle

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 the 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.”

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

Get Set Go!

You have successfully installed the API trading environment on your system using the system and the language of your choice. Now is the time to put it to test by executing your first trade. Here are the prerequisites to execute a successful trade:

  1. Go through the API Documentation available on CoinSwitch Pro.  
  2. Familiarize yourself with the language you are planning to use ie. Python or Java.
  3. Load your wallet with some amount of money so that you can execute your first API trade. 

Brace yourself, you are about to write the very first code of your life. 

Write your First Code

Step 1

Add the received secret_key and API_key that you generated to the given placeholders in the given script at the lines mentioned below:

Python Code:

secret_key = "<secret_key generated>"
api_key = "<api_key generated>"
api_trading_client = ApiTradingClient(secret_key, api_key)

Java Code:

public class ApiConfig {
    public static final String API_KEY = "<api_key generated>";
    public static final String SECRET_KEY = "<secret_key generated>";}

What is an Endpoint in API?

The document will talk something about Endpoints. Before we move ahead, it is important to understand what an Endpoint is. 

An API endpoint is a specific location within an API that accepts requests and sends back responses. It’s a way for different systems and applications to communicate with each other, by sending and receiving information and instructions via the endpoint.

Now when we talk about Endpoints, you will know that it is basically how your API is going to interact with the CoinSwitch API to execute the command. 

General information on Endpoints used in CoinSwitch API trading

  • The base endpoint is: https://coinswitch.co
  • All timestamps are in milliseconds and in the IST timezone.
  • GET request parameters are sent as a string of key-value params.

Now that you know what an endpoint is, it is time to verify your API and Secret key so that you can execute a trade. 

Verification and Authentication of Keys

Use the code below to verify and authenticate your keys:

Python Code:

#validate_keys
print(api_trading_client.validate_keys())

Java Code:

//check connection
public String ValidateKeys() throws Exception {
    HashMap<String, String> parameters = new HashMap<>();
    HashMap<String, Object> payload = new HashMap<>();
    String response = this.makeRequest("GET", ApiConfig.VALIDATE_API, payload, parameters);

    return response;

}

Query Parameters: None

If your keys match and are verified, you will get the following response:

Success Response:

Response Code: 200

{"message":"Valid Access"}

In case your keys do not match and are thus not verified, you will get the following response: 

Failure Response:

Response Code: 401

{"message":"Invalid Access"}

In case of failed key verification, you can Delete the key and generate a new one using the step mentioned at the beginning of this article. 

You have come a long way, now is the time to move on to the exciting part. Let’s try our hands at executing a trade using the API environment that you so meticulously set up on your system. 

Trading Endpoints

There are various trading endpoints that you can use to execute different types of orders. These trading endpoints are:

  1. Create Order
  2. Cancel Order
  3. Portfolio
  4. Open Orders 
  5. Close Orders

Let’s under the Create Order trade endpoint with an example. 

Create Order

Use the code below to place an order on a particular exchange:

Python Code:

#create order



payload = {
   "side":"sell",
   "symbol":"BTC/INR",
   "type":"limit",
   "price":2300000,
   "quantity":0.00005,
   "exchange":"coinswitchx"
}
print(api_trading_client.create_order(payload=payload))

Java Code:

//create order
public String createOrder() throws  Exception{
        HashMap<String, String> parameters = new HashMap<>();
        HashMap<String, Object> payload = new HashMap<>();
        payload.put("side", "sell");
        payload.put("symbol", "BTC/INR");
        payload.put("quantity", 0.00005);
	 payload.put("price", 2300000);
        payload.put("type", "limit");
        payload.put("exchange", "coinswitchx");    
        String response = this.makeRequest("POST", ApiConfig.CREATE_ORDER, payload, parameters);
        return response;
    }

Query Parameters:

NameTypeMandatoryDescription
sideSTRINGYesAllowed values:
“buy”
“sell”
(case insensitive)
symbolSTRINGYesShould be in the format
base_currency/quote_currency
(case insensitive)
typeSTRINGYesOrder Type like LIMIT
priceFLOATYesPrice at which you want to place the order
quantityFLOATYesBase quantity that you want to buy or sell.
exchangeSTRINGYesAllowed values:
“coinswitchx”
“wazirx”
(case insensitive)

PRO Tip: After you create an order, it might take some time for it to get executed on the exchange. So please be patient and plan your trades accordingly.

Once you execute the above query, you will get one of the following responses.

Response: 

Status Code: 200 

{
   "data":{
      "order_id":"927db2d9-643c-47a3-9c0f-78741ac95cf5",
      "symbol":"BTC/INR",
      "price":2300000, # price at which Order was placed by the user
      "average_price":0, # price at which the order got executed
      "orig_qty":5e-05, # quantity at which order was placed
      "executed_qty":0, # quantity that got executed
      "status":"OPEN",
      "side":"SELL",
      "exchange":"coinswitchx",
      "order_source":"API_TRADING",
      "created_time":1689661638000, # time stamp in mili seconds 
      "updated_time":1689661639000   # time stamp in mili seconds
   }
}

Status Details:

  • OPEN: Order is in open state and not executed at all. 
  • PARTIALLY_EXECUTED: The order is executed partially and the order is still open
  • CANCELED: The user has canceled the order.
  • EXECUTED: The order was Executed in the exchange.
  • EXPIRED: The order expired.
  • DISCARDED: Order cannot be processed. (It is not placed on the exchange)

If you get the EXECUTED response, it means your trade was successfully executed. Hurry! It is time to celebrate as you have made your first API trading transaction. You are now an API trader and you will not pay any commission on your trades for the first 30 days. So make the most of this, but do proper research as cryptos are unregulated products and thus can be risky. 

Error Response

Alas, if you get any of the below responses, it means your trade wasn’t successful. You will have to go through the error message to figure out what went wrong and rectify it.

You can execute the trade again after addressing the issue. 

Status Code: 422
{ 

"message": "Input price must be of type number"

}
Status Code: 400
{ 

"message": "Amount is more than available balance" 

}
Status Code: 401
{ 

"message": "Invalid access" 

}

There is a lot more to API trading than just executing trades. We recommend that you go through our API trading Documentation to know the code to perform tasks like:

Cancelling an order
Checking your Portfolio
Checking all your open orders
Getting Candlestick Data of a coin on an exchange and much more. 

CoinSwitch Pro’s API trading facility offers a number of functionalities and is very easy to use. We recommend that you spend some time with this product to familiarize yourself with its working to make the most of API trading.

Disclaimer: Crypto products and NFTs are unregulated and can be highly risky. There may be no regulatory recourse for any loss from such transactions. The information provided in this post is not to be considered investment/financial advice from CoinSwitch. Any action taken upon the information shall be at the user’s risk.

Share this:

IN THIS ARTICLE

Subscribe to our newsletter

Weekly crypto updates and insights delivered to your inbox.

Browse our Newsletter Archive for past editions.

SnowSnow

Thank you for subscribing!
Please verify your email to start receiving the latest issues from Switch in your Inbox.
Powered by

Weekly updates from the cryptosphere and the world of finance delivered to your inbox.

Build your crypto portfolio on the
CoinSwitch app today

Scan the QR code below or find us on Google Play
Store or Apple App Store.

Build your crypto portfolio on the
CoinSwitch app today

Scan the QR code below or find us on Google Play Store or Apple App Store.

Weekly updates from the cryptosphere and the world of finance delivered to your inbox.