├── .github ├── ISSUE_TEMPLATE │ ├── bug-report---.md │ ├── config.yml │ └── feature-request---.md └── workflows │ └── stale.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── assets ├── bmac.png └── logo.png ├── config.py ├── docker-compose.yml ├── handler.py ├── main.py └── requirements.txt /.github/ISSUE_TEMPLATE/bug-report---.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Bug report \U0001F41E" 3 | about: Create a bug report 4 | labels: bug 5 | 6 | --- 7 | 8 | ## Describe the bug 9 | A clear and concise description of what the bug is. 10 | 11 | ### Steps to reproduce 12 | Steps to reproduce the behavior. 13 | 14 | ### Expected behavior 15 | A clear and concise description of what you expected to happen. 16 | 17 | ### Environment 18 | - OS: [e.g. Arch Linux] 19 | - Other details that you think may affect. 20 | 21 | ### Additional context 22 | Add any other context about the problem here. 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | contact_links: 2 | - name: Question 🙋 3 | url: https://github.com/fabston/TradingView-Webhook-Bot/discussions/categories/q-a 4 | about: Ask your question in our Discussions Channel -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request---.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Feature request \U0001F680" 3 | about: Suggest an idea 4 | labels: enhancement 5 | 6 | --- 7 | 8 | ## Summary 9 | Brief explanation of the feature. 10 | 11 | ### Basic example 12 | Include a basic example or links here. 13 | 14 | ### Motivation 15 | Why are we doing this? What use cases does it support? What is the expected outcome? 16 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark and close stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | 7 | jobs: 8 | stale: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/stale@main 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | stale-issue-message: 'It looks like this has been idle a while, so I am marking it as stale. Remove the label or comment if this issue should remain open.' 17 | stale-pr-message: 'It looks like this PR has been idle a while, so I am marking it as stale. Remove the label or comment if this is still being worked on.' 18 | stale-issue-label: 'no-activity' 19 | stale-pr-label: 'no-activity' 20 | exempt-pr-labels: 'help wanted,enhancement' 21 | days-before-stale: 30 22 | days-before-close: 5 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine 2 | LABEL Auther="fabston" 3 | WORKDIR /usr/src/app 4 | COPY requirements.txt ./ 5 | RUN apk add gcc python3-dev openssl-dev musl-dev libffi-dev &&\ 6 | pip install --no-cache-dir -r requirements.txt 7 | 8 | COPY main.py handler.py config.py ./ 9 | EXPOSE 80 10 | 11 | ENTRYPOINT [ "python", "main.py" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 fabston 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Python version 5 | GitHub license 6 | GitHub issues 7 | GitHub pull requests 8 |
GitHub stars 9 | GitHub forks 10 | GitHub watchers 11 |

12 | 13 |

14 | About 15 | • 16 | Features 17 | • 18 | Installation 19 | • 20 | Images 21 | • 22 | Help 23 |

24 | 25 | ## About 26 | The **TradingView Webhook Bot** ⚙️ listens to [TradingView](https://tradingview.com) alerts via [webhooks](https://www.tradingview.com/support/solutions/43000529348-i-want-to-know-more-about-webhooks/) using [flask](https://flask.palletsprojects.com/en/1.1.x/). 27 | All alerts can be instantly sent to Telegram, Discord, Twitter and/or Email. 28 | 29 | > 📊 If you are looking for an exchange to trade on, I can recommend **Bybit**. 30 | > **[Sign up now](https://partner.bybit.com/b/20882)** and receive up to **$30,000** in Deposit Rewards! 31 | 32 | ## Features 33 | - Telegram Support using the [Python Telegram](https://github.com/python-telegram-bot/python-telegram-bot) libary. 34 | - Discord Support using [webhooks](https://support.discord.com/hc/de/articles/228383668-Webhooks-verwenden). 35 | - Slack Support using [webhooks](https://api.slack.com/messaging/webhooks). 36 | - Twitter Support using the [tweepy](https://github.com/tweepy/tweepy) libary. 37 | - Email Support using [smtplib](https://docs.python.org/3/library/smtplib.html). 38 | - Alert channels can be enabled or disabled in [`config.py`](https://github.com/fabston/TradingView-Webhook-Bot/blob/master/config.py). 39 | - Dynamically send alerts to different Telegram and/or Discord channels. 40 | - TradingView `{{close}}`, `{{exchange}}` etc. variables support. Read more [here](https://www.tradingview.com/blog/en/introducing-variables-in-alerts-14880/). 41 | 42 | ## Installation 43 | > ⚠️ Best to run the bot on a VPS. I can recommend Hetzner's CX11 VPS for 3.79€/month. [Sign up](https://hetzner.cloud/?ref=tQ1NdT8zbfNY) now and receive **€20 free** credits. 44 | 1. Clone this repository `git clone https://github.com/fabston/TradingView-Webhook-Bot.git` 45 | 1. Create your virtual environment `python3 -m venv TradingView-Webhook-Bot` 46 | 1. Activate it `source TradingView-Webhook-Bot/bin/activate && cd TradingView-Webhook-Bot` 47 | 1. Install all requirements `pip install -r requirements.txt` 48 | 1. Edit and update [`config.py`](https://github.com/fabston/TradingView-Webhook-Bot/blob/master/config.py) 49 | 1. Setup TradingView alerts. An example alert message would be: 50 | ```json 51 | { 52 | "key": "9T2q394M92", 53 | "telegram": "-1001277977502", 54 | "discord": "789842341870960670/BFeBBrCt-w2Z9RJ2wlH6TWUjM5bJuC29aJaJ5OQv9sE6zCKY_AlOxxFwRURkgEl852s3", 55 | "slack": "T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX", 56 | "msg": "Long *#{{ticker}}* at `{{close}}`" 57 | } 58 | ``` 59 | - `key` is mandatory! It has to match with `sec_key` in [`config.py`](https://github.com/fabston/TradingView-Webhook-Bot/blob/master/config.py). It's an extra security measurement to ensure nobody else is executing your alerts 60 | - `telegram`, `discord`, `slack` is optional. If it is not set it will fall back to the config.py settings 61 | - `msg` can be anything. Markdown for [Telegram](https://core.telegram.org/api/entities) and [Discord](https://support.discord.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-) is supported as well 62 | - TradingViews variables like `{{close}}`, `{{exchange}}` etc. work too. More can be found [here](https://www.tradingview.com/blog/en/introducing-variables-in-alerts-14880/) 63 | - Your webhook url would be `http:///webhook` 64 | 1. If you use a firewall be sure to open the corresponding port 65 | 1. Run the bot with `python main.py` 66 | 1. [PM2](https://github.com/fabston/TradingView-Webhook-Bot/issues/28#issuecomment-766301062) can help you in running the app in the background / on system boot. 67 | 68 | ### Forward Port 80 to 8080 using NGINX 69 | 70 | *It is recommended to run flask on a different port like 8080. It is then necessary to forward port 80 to 8080.* 71 | 72 | 1. Install the necessary packages: `sudo apt-get install nginx` 73 | 1. Edit the NGINX configuration file: `sudo nano /etc/nginx/sites-enabled/tv_webhook` 74 | 1. Add the following content: 75 | ```nginx 76 | server { 77 | listen 80; 78 | 79 | server_name ; 80 | 81 | location / { 82 | proxy_pass http://127.0.0.1:8080; # Forward traffic to port 8080 83 | proxy_set_header Host $host; 84 | proxy_set_header X-Real-IP $remote_addr; 85 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Pass client's IP address 86 | proxy_set_header X-Forwarded-Proto $scheme; 87 | } 88 | } 89 | ``` 90 | 1. Restart NGINX `sudo service nginx restart` 91 | 92 | ### Docker 93 | 1. Clone this repository `git clone https://github.com/fabston/TradingView-Webhook-Bot.git` 94 | 1. Edit and update [`config.py`](https://github.com/fabston/TradingView-Webhook-Bot/blob/master/config.py) 95 | 1. `docker-compose build` 96 | 1. `docker-compose up` 97 | 98 | ## Images 99 | ![Webhook Bot](https://i.imgur.com/vZA42cc.png) 100 | 101 | ## How can I help? 102 | All kinds of contributions are welcome 🙌! The most basic way to show your support is to `⭐️ star` the project, or raise [`🐞 issues`](https://github.com/fabston/TradingView-Webhook-Bot/issues/new/choose). 103 | 104 | *** 105 | 106 |

107 | Buy Me A Coffee 108 |

109 | -------------------------------------------------------------------------------- /assets/bmac.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabston/TradingView-Webhook-Bot/7eff8f9e9e13f350d7a3f258329285eb3a0bbd37/assets/bmac.png -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabston/TradingView-Webhook-Bot/7eff8f9e9e13f350d7a3f258329285eb3a0bbd37/assets/logo.png -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------- # 2 | # Plugin Name : TradingView-Webhook-Bot # 3 | # Author Name : fabston # 4 | # File Name : config.py # 5 | # ----------------------------------------------- # 6 | 7 | # TradingView Example Alert Message: 8 | # { 9 | # "key":"9T2q394M92", "telegram":"-1001298977502", "discord":"789842349670960670/BFeBBrCt-w2Z9RJ2wlH6TWUjM5bJuC29aJaJ5OQv9sE6zCKY_AlOxxFwRURkgEl852s3", "msg":"Long #{{ticker}} at `{{close}}`" 10 | # } 11 | 12 | sec_key = ( 13 | "" # Can be anything. Has to match with "key" in your TradingView alert message 14 | ) 15 | 16 | # Telegram Settings 17 | send_telegram_alerts = False 18 | tg_token = "" # Bot token. Get it from @Botfather 19 | channel = 0 # Channel ID (ex. -1001487568087) 20 | 21 | # Discord Settings 22 | send_discord_alerts = False 23 | discord_webhook = "" # Discord Webhook URL (https://support.discordapp.com/hc/de/articles/228383668-Webhooks-verwenden) 24 | 25 | # Slack Settings 26 | send_slack_alerts = False 27 | slack_webhook = "" # Slack Webhook URL (https://api.slack.com/messaging/webhooks) 28 | 29 | # Twitter Settings 30 | send_twitter_alerts = False 31 | tw_ckey = "" 32 | tw_csecret = "" 33 | tw_atoken = "" 34 | tw_asecret = "" 35 | 36 | # Email Settings 37 | send_email_alerts = False 38 | email_sender = "" # Your email address 39 | email_receivers = ["", ""] # Receivers, can be multiple 40 | email_subject = "Trade Alert!" 41 | 42 | email_port = 465 # SMTP SSL Port (ex. 465) 43 | email_host = "" # SMTP host (ex. smtp.gmail.com) 44 | email_user = "" # SMTP Login credentials 45 | email_password = "" # SMTP Login credentials 46 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: '3.9' 3 | services: 4 | tradingview-webhook-bot: 5 | build: . 6 | container_name: tradingview-webhook-bot 7 | ports: 8 | - '80:80' 9 | restart: unless-stopped -------------------------------------------------------------------------------- /handler.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------- # 2 | # Plugin Name : TradingView-Webhook-Bot # 3 | # Author Name : fabston # 4 | # File Name : handler.py # 5 | # ----------------------------------------------- # 6 | 7 | import smtplib 8 | import ssl 9 | from email.mime.text import MIMEText 10 | 11 | import tweepy 12 | from discord_webhook import DiscordEmbed, DiscordWebhook 13 | from slack_webhook import Slack 14 | from telegram import Bot 15 | 16 | import config 17 | 18 | 19 | def send_alert(data): 20 | msg = data["msg"].encode("latin-1", "backslashreplace").decode("unicode_escape") 21 | if config.send_telegram_alerts: 22 | tg_bot = Bot(token=config.tg_token) 23 | try: 24 | tg_bot.sendMessage( 25 | data["telegram"], 26 | msg, 27 | parse_mode="MARKDOWN", 28 | ) 29 | except KeyError: 30 | tg_bot.sendMessage( 31 | config.channel, 32 | msg, 33 | parse_mode="MARKDOWN", 34 | ) 35 | except Exception as e: 36 | print("[X] Telegram Error:\n>", e) 37 | 38 | if config.send_discord_alerts: 39 | try: 40 | webhook = DiscordWebhook( 41 | url="https://discord.com/api/webhooks/" + data["discord"] 42 | ) 43 | embed = DiscordEmbed(title=msg) 44 | webhook.add_embed(embed) 45 | webhook.execute() 46 | except KeyError: 47 | webhook = DiscordWebhook( 48 | url="https://discord.com/api/webhooks/" + config.discord_webhook 49 | ) 50 | embed = DiscordEmbed(title=msg) 51 | webhook.add_embed(embed) 52 | webhook.execute() 53 | except Exception as e: 54 | print("[X] Discord Error:\n>", e) 55 | 56 | if config.send_slack_alerts: 57 | try: 58 | slack = Slack(url="https://hooks.slack.com/services/" + data["slack"]) 59 | slack.post(text=msg) 60 | except KeyError: 61 | slack = Slack( 62 | url="https://hooks.slack.com/services/" + config.slack_webhook 63 | ) 64 | slack.post(text=msg) 65 | except Exception as e: 66 | print("[X] Slack Error:\n>", e) 67 | 68 | if config.send_twitter_alerts: 69 | tw_auth = tweepy.OAuthHandler(config.tw_ckey, config.tw_csecret) 70 | tw_auth.set_access_token(config.tw_atoken, config.tw_asecret) 71 | tw_api = tweepy.API(tw_auth) 72 | try: 73 | tw_api.update_status( 74 | status=msg.replace("*", "").replace("_", "").replace("`", "") 75 | ) 76 | except Exception as e: 77 | print("[X] Twitter Error:\n>", e) 78 | 79 | if config.send_email_alerts: 80 | try: 81 | email_msg = MIMEText( 82 | msg.replace("*", "").replace("_", "").replace("`", "") 83 | ) 84 | email_msg["Subject"] = config.email_subject 85 | email_msg["From"] = config.email_sender 86 | email_msg["To"] = config.email_sender 87 | context = ssl.create_default_context() 88 | with smtplib.SMTP_SSL( 89 | config.email_host, config.email_port, context=context 90 | ) as server: 91 | server.login(config.email_user, config.email_password) 92 | server.sendmail( 93 | config.email_sender, config.email_receivers, email_msg.as_string() 94 | ) 95 | server.quit() 96 | except Exception as e: 97 | print("[X] Email Error:\n>", e) 98 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------- # 2 | # Plugin Name : TradingView-Webhook-Bot # 3 | # Author Name : fabston # 4 | # File Name : main.py # 5 | # ----------------------------------------------- # 6 | 7 | from handler import send_alert 8 | import config 9 | import time 10 | from flask import Flask, request, jsonify 11 | 12 | app = Flask(__name__) 13 | 14 | 15 | def get_timestamp(): 16 | timestamp = time.strftime("%Y-%m-%d %X") 17 | return timestamp 18 | 19 | 20 | @app.route("/webhook", methods=["POST"]) 21 | def webhook(): 22 | whitelisted_ips = ['52.89.214.238', '34.212.75.30', '54.218.53.128', '52.32.178.7'] 23 | client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) 24 | if client_ip not in whitelisted_ips: 25 | return jsonify({'message': 'Unauthorized'}), 401 26 | try: 27 | if request.method == "POST": 28 | data = request.get_json() 29 | if data["key"] == config.sec_key: 30 | print(get_timestamp(), "Alert Received & Sent!") 31 | send_alert(data) 32 | return jsonify({'message': 'Webhook received successfully'}), 200 33 | 34 | else: 35 | print("[X]", get_timestamp(), "Alert Received & Refused! (Wrong Key)") 36 | return jsonify({'message': 'Unauthorized'}), 401 37 | 38 | except Exception as e: 39 | print("[X]", get_timestamp(), "Error:\n>", e) 40 | return jsonify({'message': 'Error'}), 400 41 | 42 | 43 | if __name__ == "__main__": 44 | from waitress import serve 45 | 46 | serve(app, host="0.0.0.0", port=8080) 47 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.4 2 | APScheduler==3.6.3 3 | black==21.5b1 4 | cachetools==4.2.2 5 | certifi==2021.5.30 6 | chardet==4.0.0 7 | click==8.0.1 8 | discord-webhook==0.14.0 9 | flake8==3.9.2 10 | Flask==2.0.1 11 | idna==2.10 12 | isort==5.8.0 13 | itsdangerous==2.0.1 14 | Jinja2==3.0.1 15 | MarkupSafe==2.0.1 16 | mccabe==0.6.1 17 | mypy-extensions==0.4.3 18 | oauthlib==3.1.1 19 | pathspec==0.8.1 20 | pycodestyle==2.7.0 21 | pyflakes==2.3.1 22 | PySocks==1.7.1 23 | python-telegram-bot==13.6 24 | pytz==2021.1 25 | regex==2021.4.4 26 | requests==2.25.1 27 | requests-oauthlib==1.3.0 28 | six==1.16.0 29 | slack-webhook==1.0.6 30 | toml==0.10.2 31 | tornado==6.1 32 | tweepy==3.10.0 33 | tzlocal==2.1 34 | urllib3==1.26.5 35 | waitress==2.1.1 36 | Werkzeug==2.0.1 37 | --------------------------------------------------------------------------------