How to Connect TradingView Alerts to Your Python Project

For those that use TradingView a lot to build and test strategies, one of the troubles I ran into was connecting the alerts to Python so that I can use the alerts to trigger a trade automatically on Python.

But the issue I’ve faced was that TradingView doesn’t have a pubically available API that I can connect to, so getting the alerts into my Python project was going to be a challenge. Here’s a quick post on how I solved that problem.

Overview of the Solution

  1. Trigger alerts to a Discord Webhook
  2. Use Discord.Py to listen for the message
  3. Create a Discord Bot to send the alerts to the Discord Channel
  4. When message came through into my python program, do something

Resources

I won’t go over the step by step in much detail but I will link all of the best resouces I’ve used to build this project, and the code I use to listen for the messages.

Install the Discord.py library

pip install discord.py

Python code to listen for the message from Discord and print the message to the console.

import discord

client = discord.Client()
token = 'INSERT CLIENT TOKEN

@client.event
async def on_message(message):
    print(message.content)

client.run(token)

Practical Use of the Code

Here’s what I am currently using the code for. Right now, as the message comes in, it’s either coming in as a buy or sell signal with the price it triggered at.

Then I process it through my holdings and cash available to see if the trade should be triggered based on my targets set on my portfolio.

If the order meets all the requirements, then the trade is executed using the Interactives Brokers TWS API. Limit price is set to my signal price to make sure I’m not surprised by the execution price because of the few seconds of delay.

Stay tuned to the blog and I’ll provide more updates to the project.

Related