Automating your trading strategy has never been more accessible. With the right tools—TradingView, Python, and Heroku—you can create a powerful, cloud-based trading bot that executes trades based on real-time signals. This guide walks you through building a complete trading bot framework from scratch, integrating alerts from TradingView into automated Binance trades via a secure Python backend hosted on Heroku.
Whether you're a developer exploring algorithmic trading or a trader looking to automate strategies, this step-by-step tutorial ensures you’ll have a functional system ready for live markets—with room to scale and optimize.
Part 1: Setting Up a TradingView Alert Webhook
To begin, we need to generate trading signals using TradingView. These signals will trigger webhooks that notify your Python server whenever a trade condition is met.
Step 1: Choose Your Trading Pair
Select the cryptocurrency pair you'd like to trade. For this example, we’ll use ADA/USD on Binance US.
Step 2: Open Pine Editor
At the bottom of the TradingView chart interface, click on “Pine Editor” to access the script editor.
Step 3: Paste the Sample Pine Script
Copy and paste the following script into the editor:
//@version=4
strategy("ADA SMA", overlay=true, initial_capital=25, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
start_date = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)
start_month = input(title="Start Month", type=input.integer, defval=5, minval=1, maxval=12)
start_year = input(title="Start Year", type=input.integer, defval=2021)
end_date = input(title="End Date", type=input.integer, defval=6, minval=1, maxval=31)
end_month = input(title="End Month", type=input.integer, defval=9, minval=1, maxval=12)
end_year = input(title="End Year", type=input.integer, defval=2021)
between_dates = (time >= timestamp(start_year, start_month, start_date, 7, 0)) and (time < timestamp(end_year, end_month, end_date, 23, 59))
fast_ma_period = input(title="Fast MA", type=input.integer, defval=2)
slow_ma_period = input(title="Slow MA", type=input.integer, defval=5)
fast_ma = sma(close, fast_ma_period)
slow_ma = sma(close, slow_ma_period)
plot(fast_ma, color=color.green, linewidth=1)
plot(slow_ma, color=color.yellow, linewidth=3)
buy_condition = crossover(fast_ma, slow_ma)
sell_condition = crossunder(fast_ma, slow_ma)
if between_dates
strategy.entry("ADA door", strategy.long, when=buy_condition)
strategy.close("ADA door", when=sell_condition)⚠️ Note: This is a basic moving average crossover strategy for demonstration purposes. It is not guaranteed to be profitable. Always conduct thorough backtesting and research before deploying real capital.
Step 4: Add Script to Chart
Click “Add to Chart” and verify that the moving averages appear on your chart. Then switch to the Strategy Tester tab to review historical performance.
Step 5: Create an Alert
Click the alarm clock icon in the top toolbar to set up an alert.
- Under Condition, select “ADA SMA” (the name of your strategy).
- In the Message field, paste the following JSON payload:
{
"passphrase": "abcdefgh",
"time": "{{timenow}}",
"exchange": "{{exchange}}",
"ticker": "{{ticker}}",
"bar": {
"time": "{{time}}",
"open": {{open}},
"high": {{high}},
"low": {{low}},
"close": {{close}},
"volume": {{volume}}
},
"strategy": {
"position_size": {{strategy.position_size}},
"order_action": "{{strategy.order.action}}",
"order_contracts": {{strategy.order.contracts}},
"order_price": {{strategy.order.price}},
"order_id": "{{strategy.order.id}}",
"market_position": "{{strategy.market_position}}",
"market_position_size": {{strategy.market_position_size}},
"prev_market_position": "{{strategy.prev_market_position}}",
"prev_market_position_size": {{strategy.prev_market_position_size}}
}
}This structured data will be sent to your server each time the alert triggers.
👉 Get started with automated trading today — build your own bot securely.
Part 2: Set Up Binance API Key
Your bot needs secure access to your exchange account to place trades. Here’s how to set up API keys on Binance.
- Log in to your Binance US account.
- Click your profile dropdown and select “API Management.”
- Enter a label (e.g.,
TradingBot) and click Create. - Confirm via email.
- Save both the API Key and Secret Key securely. The secret key will not be shown again after refresh.
🔐 Never expose these keys in public repositories or client-side code.
These credentials will authenticate your Python app with Binance’s API.
Part 3: Configure Environment Variables
To keep sensitive data secure, store API keys as environment variables.
On Windows:
- Search for “Environment Variables” in the Start menu.
- Click “Environment Variables…”
- Under User Variables, click New… and add:
| Variable Name | Value | Notes |
|---|---|---|
API_KEY | [Your Binance API Key] | From Part 2 |
API_SECRET | [Your Binance Secret Key] | From Part 2 |
WEBHOOK_PASSPHRASE | abcdefgh | Must match the one in TradingView |
Click OK to save.
Part 4: Set Up Your Python Project Workspace
We’ll use Flask to build a webhook receiver and python-binance to interact with the exchange.
Step 1: Install PyCharm
Download and install PyCharm Community Edition for an easy development environment.
Step 2: Create New Project
Open PyCharm and create a new project with a virtual environment.
Step 3: Install Dependencies
Create a file named requirements.txt with:
flask
gunicorn
python-binanceIn the terminal, run:
pip3 install -r requirements.txtStep 4: Build the Flask App
Create app.py with the following code:
import json, os
from binance.client import Client
from binance.enums import *
from flask import Flask, request
app = Flask(__name__)
client = Client(os.environ.get('API_KEY'), os.environ.get('API_SECRET'), tld='us')
def order(side, quantity, symbol, order_price, passphrase, order_type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC):
try:
print(f"{passphrase} {symbol} Sending order {order_type} - {side} {quantity} {symbol} at {order_price}.")
# Uncomment below when going live:
# order = client.create_order(symbol=symbol, side=side, type=order_type, quantity=quantity, timeInForce=timeInForce, price=order_price)
print(f" {passphrase} {symbol} Not Executed order {order_type} - {side} {quantity} {symbol} at {order_price}.")
except Exception as e:
print("An exception occurred - {}".format(e))
return False
return True
@app.route('/')
def welcome():
return "This is my first trading bot"
@app.route('/webhook', methods=['POST'])
def webhook():
data = json.loads(request.data)
if data['passphrase'] != os.environ.get('WEBHOOK_PASSPHRASE'):
return {"code": "error", "message": "Nice try, invalid passphrase"}
side = data['strategy']['order_action'].upper()
quantity = data['strategy']['order_contracts']
ticker = data['ticker'].upper()
order_price = data['strategy']['order_price']
order_response = order(side, quantity, ticker, order_price, data['passphrase'])
if order_response:
return {"code": "success", "message": "Order executed."}
else:
print("Order Failed.")
return {"code": "error", "message": "Order Failed."}Keep orders commented during testing.
👉 Securely connect your exchange account and start automating trades now.
Part 5: Test Using a REST Client
Use Insomnia or any REST client to simulate incoming webhook requests.
- Download Insomnia.
- Create a new POST request to
http://127.0.0.1:5000/webhook. - Set body type to JSON and paste this sample payload:
{
"passphrase": "abcdefgh",
"time": "2020-09-06T01:44:17Z",
"exchange": "BINANCE",
"ticker": "ADAUSD",
"bar": {
"time": "2020-09-06T01:43:00Z",
"open": 0.002748,
"high": 0.0027486,
"low": 0.002748,
"close": 0.0027486,
"volume": 150177
},
"strategy": {
"position_size": 1000,
"order_action": "buy",
"order_contracts": 10,
"order_price": 1.5,
"order_id": "ADA door",
"market_position": "long",
"market_position_size": 10000,
"prev_market_position": "flat",
"prev_market_position_size": 0
}
}- Click Send and check the response.
Common Binance API errors include insufficient balance (-2010), lot size violations (-1013), or price precision issues (-1111). Handle these in your logic for robustness.
Part 6: Initialize Git Repository
Version control is essential for deployment.
- Install Git.
- In your project directory, run:
git init
git config --global user.email "[email protected]"Part 7: Deploy on Heroku
Heroku hosts your Flask app in the cloud.
- Sign up at heroku.com.
- Install the Heroku CLI.
- Run:
heroku login
heroku git:remote -a your-app-name- Add environment variables under Settings > Config Vars in Heroku Dashboard.
- Deploy:
git add .
git commit -am "Initial commit"
git push heroku master- Scale the web dyno:
heroku ps:scale web=1- Check logs:
heroku logs --tailFix common errors like H14 (no web processes) by verifying your Procfile contains web: gunicorn app:app with no file extension.
Part 8: Go Live
Now it’s time to activate real trading.
- Uncomment the
client.create_order(...)line inapp.py. - Commit changes to Heroku.
- Update your TradingView alert’s webhook URL to:
https://your-app-name.herokuapp.com/webhook- Monitor logs and Binance app for executed trades.
🎉 You’re now running an automated trading bot!
Frequently Asked Questions
Q: Can I use exchanges other than Binance?
Yes! Any exchange with a REST API and Python library—like Coinbase Pro or KuCoin—can be integrated by modifying the client initialization and order logic.
Q: Is it safe to store API keys in environment variables?
Yes, as long as they’re not exposed in version control or logs. Never commit .env files or print secrets in code.
Q: Why am I getting error code H14 on Heroku?
H14 means no web dynos are running. Fix it by scaling manually (heroku ps:scale web=1) or ensuring your Procfile is correctly named and formatted.
Q: How do I prevent invalid order sizes?
Implement server-side validation in Python to round quantities and prices according to exchange rules (e.g., lot size, min notional).
Q: Can I backtest my Pine Script strategy?
Absolutely. Use TradingView’s Strategy Tester tab to analyze performance across historical data before going live.
Q: What happens if my bot receives duplicate alerts?
Add deduplication logic using timestamps or order IDs to avoid repeated trades.
Final Thoughts
Building a trading bot with TradingView, Python, and Heroku combines powerful tools into an efficient automation pipeline. While this framework provides a solid foundation, consider enhancing it with risk management, position sizing logic, and multi-exchange support.
👉 Take your automated trading further — explore advanced tools and features today.
By focusing on security, reliability, and clean architecture, you can create scalable systems that evolve with your trading goals.