Building a simple Trading Bot using Python, TradingView and CoinDCX APIs

Sairav Dev
7 min readJul 20, 2021

--

Photo by Tech Daily on Unsplash

Below is all you need to kickstart with your own trading bot. We will build the bot using Python, TradingView for signals , and CoinDCX(an Indian crypto exchange) to place orders.

The functionality of our trading app can be summarized as follows:-

  1. The application will get alerts from TradingView regarding the signal(s) of your choice of strategy. For example MA, EMA, MACD, Supertrend etc. These alerts will mention whether the Indictor is positive for a buy or a sell. This logic we’ll handle at the TradingView end.
  2. The app will simply store the signals and based on what combination of criteria (if ema says buy and supertrend is also buy, let's BUY), we’ll place an order from the application using CoinDCX APIs.
  3. The same applies while closing the order, we’ll get signals from the TradingView platform, and based on the indicators, we will close the trade.
CryptoTradingBot Functionality Overview #Bitcoin
TradingBot Workflow

We’ll be breaking down this into the following parts:-

  1. Overview
  2. TradingView indicator and alerts
  3. Bot/Application coding with CoinDCX APIs, deployed on PythonAnywhere to keep it running 24x7.

1 . Overview :

Consider the following chart, we are gonna use just Supertrend strategy for the simplicity of the tutorial. MATIC/USDT Binance, since CoinDCX uses binance as the source, we are gonna look at the binance chart. You may use another exchange instead of CoinDCX and look at their chart respectively.

Supertrend Strategy for TradingBot Example
MATIC/USDT — Binance — 5m chart with Supertrend strategy

Now, according to Supertrend , when the buy signal is generated ( at the green candle close ~1.13275), we will trigger an alert for our app and let it know that uptrend has started , it’s time to buy some MATIC/USDT . And when this buy becomes sell / downtrend(at the close of the candle ~1.157), or when the stoploss hits (having a stoploss is very important as part of managing your risks of trades , you can set that value in your app) , we sell . That simple .

2 . TradingView indicator and alerts :

  • Open your choice of trading pair time frame (5 minute?) chart and add Supertrend (click on fx and look for Supertrend) to it .
Selecting Strategy/Indicator from TradingView for TradeBot
Supertrend — Indicator & Strategies

Now , Click on the alarm clock icon (screenshot below) that says — ‘ Create Alert ’ and select the fields as shown below :-

  • Condition — Supertrend , Supertrend-Buy (to trigger a buy alert) or Supertrend-Sell (to trigger a sell alert)
  • Select Once per bar close (so on every bar close only , the alert will trigger)
  • Select webhook url (Here will go the url to your bot application end point which will receive the alert data in json format , so basically this will be a POST mapping end point whose request body we will send/hook from TradingView).
Create TradingView Alert — Supertrend
TradingView | Create Alert | Supertrend |

Now in the last section “Message” , is where we send our json data . Something like this :

Providing JSON Message in Alert for the Python BOT application to consume
Message — The JSON request body for our webhook API
{
“side”:”buy”,
“time”: “{{timenow}}”,
“ticker”:”{{ticker}}” ,
“strategy”: “supertrend”,
“exchange”: “{{exchange}}”,
“bar”: {
“open”:{{open}},
“high”:{{high}},
“low”:{{low}},
“close”:{{close}},
“volume”:{{volume}}
}
}
  • All the fields within the {{}} placeholder will be replaced by real-time values when the alert is triggered. So all the values related to candle, high, low, closing price, you can use in your application as well for whatever logic you might wanna implement.

This is it, we now have an alert every time there is a change in market direction, and we can take position accordingly through our app.

Note — Similar to supertrend , TradingView has defined a whole bunch of conditions to play around with. (Ex. In condition — You can choose the market value .ie MATICUSDT , and subcondition you can choose Crossing Up EMA — 200 ?) , So every time a candle closes above EMA-200 , the alert will trigger .

MATICUSDT crossing up EMA 200 condition — TradingView Alert Trigger
MATICUSDT crossing up EMA 200 condition
TradingView — Conditions available for Triggering Alert
Conditions available for Triggering Alert

So based on your indicators, you can leverage them accordingly.

3 . Python Flask App / Bot Application

You can either start with the app development in your local machine and move to hosting on PythonAnywhere later when you are comfortable with the code , or directly start there as the interface is pretty easy .

You can create your main file “app.py” and start your code inside it , as you can see we have a route for “/webhook” , that will receive the data from TradingView request . (So our webhook url for alert will be — http://your-webapp-at-pythonanywhere.com/webhook) — to be mentioned while creating alert on Tradingview.

from flask import Flask,request
from flask_mysqldb import MySQL
import calendar
app = Flask(__name__)@app.route(‘/webhook’,methods=[‘POST’])
def webhook():
# Generating a timestamp.
timeStamp = int(round(time.time() * 1000))
webhook_data = json.loads(request.data)market = webhook_data[‘ticker’]

Now that we have our webhook_data , in order to place orders , follow the CoinDCX APIs , you will find python snippet to place order :

import hashlib
import base64
import json
import time
import requests

# Enter your API Key and Secret here. If you don't have one, you can generate it from the website.
key = "XXXX"
secret = "YYYY"

# python3
secret_bytes = bytes(secret, encoding='utf-8')
# python2
secret_bytes = bytes(secret)

# Generating a timestamp.
timeStamp = int(round(time.time() * 1000))

body = {
"side": "buy", #Toggle between 'buy' or 'sell'.
"order_type": "limit_order", #Toggle between a 'market_order' or 'limit_order'.
"market": "SNTBTC", #Replace 'SNTBTC' with your desired market pair.
"price_per_unit": 0.03244, #This parameter is only required for a 'limit_order'
"total_quantity": 400, #Replace this with the quantity you want
"timestamp": timeStamp
}

json_body = json.dumps(body, separators = (',', ':'))

signature = hmac.new(secret_bytes, json_body.encode(), hashlib.sha256).hexdigest()

url = "https://api.coindcx.com/exchange/v1/orders/create"

headers = {
'Content-Type': 'application/json',
'X-AUTH-APIKEY': key,
'X-AUTH-SIGNATURE': signature
}

response = requests.post(url, data = json_body, headers = headers)
data = response.json()
print(data)

This snippet is all you need to place any order , buy or sell . So simply add this in the app.py , and start placing orders .

  • You may use APIs of your choice of exchange which you trade from like binance , bitmex etc. and place orders accordingly . The key was to get real-time data when any of the technical analysis is giving a signal , which we got from TradingView alerts .

You can simply put this app.py in your PythonAnywhere directory . Follow this to setup your PythonAnywhere web-app using Flask. You can also follow this video by Aditya Pai Thon YT to check how to deploy flask app .

— — — — — — — — — — — — — — — — — — — — — — — — — — —

Important Notes —

  • TradingView Alerts can be used using a Pro-subscription, which you can get for free in a 30-day trial.
  • PythonAnywhere — While using PythonAnywhere consoles to run my app after making frequent changes, I maxed out CPU seconds per day, and once you do that, your processes run in tarpit , meaning they will run on low priority. So to get more CPU seconds, I switched to a Hacker Account ($5/month) , which I found to be worth it for me, as I wanted to do things faster and this is the cheapest of all that solves my purpose. This is totally optional, CPU seconds are reset daily, so you can still wait and continue the next day.

=======================================

>> This was a very simple example and will not make you definite profits, you might lose a good amount with this strategy. You would want to use multiple strategies and combine them to get a solid confirmation for your trades. Also, your bot can be more intelligent than this, you can have your own stats (use candlesticks APIs to derive trends or even strategies) . If you do that, you might not even need the TradingView alerts and can let your bot take that charge of analysis, writing the strategy formulas, and then do the trading.

Talking of Customizing strategies, you can check out TradingView Pine script that allows writing your own strategies through which also you can have your own alerts.

References :

Referrals :

--

--