├── .gitignore ├── Procfile ├── README.md ├── app.py ├── bollinger_band_strategy.pinescript ├── config.py ├── requirements.txt ├── templates └── dashboard.html └── tradingview-test-payloads ├── webhook_message_filled.txt └── webhook_message_format.txt /.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 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn app:app -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tradingview-alpaca-strategy-alert-webhook-heroku 2 | TradingView Strategy Alert Webhook for Alpaca and Discord, including Heroku Procfile 3 | 4 | ## YouTube Tutorial on how to use this code 5 | 6 | https://www.youtube.com/watch?v=XPTb3adEQEE 7 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | import alpaca_trade_api as tradeapi 3 | import config, json, requests 4 | 5 | app = Flask(__name__) 6 | 7 | api = tradeapi.REST(config.API_KEY, config.API_SECRET, base_url='https://paper-api.alpaca.markets') 8 | 9 | @app.route('/') 10 | def dashboard(): 11 | orders = api.list_orders() 12 | 13 | return render_template('dashboard.html', alpaca_orders=orders) 14 | 15 | @app.route('/webhook', methods=['POST']) 16 | def webhook(): 17 | webhook_message = json.loads(request.data) 18 | 19 | if webhook_message['passphrase'] != config.WEBHOOK_PASSPHRASE: 20 | return { 21 | 'code': 'error', 22 | 'message': 'nice try buddy' 23 | } 24 | 25 | price = webhook_message['strategy']['order_price'] 26 | quantity = webhook_message['strategy']['order_contracts'] 27 | symbol = webhook_message['ticker'] 28 | side = webhook_message['strategy']['order_action'] 29 | 30 | order = api.submit_order(symbol, quantity, side, 'limit', 'gtc', limit_price=price) 31 | 32 | # if a DISCORD URL is set in the config file, we will post to the discord webhook 33 | if config.DISCORD_WEBHOOK_URL: 34 | chat_message = { 35 | "username": "strategyalert", 36 | "avatar_url": "https://i.imgur.com/4M34hi2.png", 37 | "content": f"tradingview strategy alert triggered: {quantity} {symbol} @ {price}" 38 | } 39 | 40 | requests.post(config.DISCORD_WEBHOOK_URL, json=chat_message) 41 | 42 | return webhook_message -------------------------------------------------------------------------------- /bollinger_band_strategy.pinescript: -------------------------------------------------------------------------------- 1 | //@version=4 2 | // this script was taken from https://kodify.net/tradingview/strategies/bollinger-breakout/ and modified for demonstration purposes 3 | strategy(title="Bollinger Breakout", overlay=true, initial_capital=1000) 4 | 5 | smaLength = input(title="SMA Length", type=integer, defval=350) 6 | 7 | ubOffset = input(title="Upper Band Offset", type=float, defval=2.5, step=0.5) 8 | lbOffset = input(title="Lower Band Offset", type=float, defval=2.5, step=0.5) 9 | 10 | //usePosSize = input(title="Use Position Sizing?", type=bool, defval=true) 11 | //riskPerc = input(title="Risk %", type=float, defval=0.5, step=0.25) 12 | 13 | smaValue = sma(close, smaLength) 14 | stdDev = stdev(close, smaLength) 15 | 16 | upperBand = smaValue + (stdDev * ubOffset) 17 | lowerBand = smaValue - (stdDev * lbOffset) 18 | 19 | //riskEquity = (riskPerc / 100) * strategy.equity 20 | //atrCurrency = (atr(20) * syminfo.pointvalue) 21 | //posSize = usePosSize ? floor(riskEquity / atrCurrency) : 1 22 | 23 | plot(series=smaValue, title="SMA", color=teal) 24 | plot(series=upperBand, title="UB", color=green, linewidth=2) 25 | plot(series=lowerBand, title="LB", color=red, linewidth=2) 26 | 27 | enterLong = crossover(close, upperBand) 28 | exitLong = crossunder(close, smaValue) 29 | 30 | enterShort = crossunder(close, lowerBand) 31 | exitShort = crossover(close, smaValue) 32 | 33 | strategy.entry(id="long_entry", long=true, qty=10, when=enterLong) 34 | strategy.entry(id="short_entry", long=false, qty=10, when=enterShort) 35 | 36 | strategy.close(id="long_entry", when=exitLong) 37 | strategy.close(id="short_entry", when=exitShort) 38 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | API_KEY = 'youralpacaapikey' 2 | API_SECRET = 'youralpacaapisecret' 3 | 4 | WEBHOOK_PASSPHRASE = 'yourpassphrase' 5 | DISCORD_WEBHOOK_URL = False # use a string containing your discord webhook url to enable -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | gunicorn 3 | alpaca-trade-api 4 | requests -------------------------------------------------------------------------------- /templates/dashboard.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | 9 | 10 | 11 | 12 |created | 19 |symbol | 20 |type | 21 |side | 22 |qty | 23 |limit price | 24 |filled price | 25 |
---|---|---|---|---|---|---|
{{ order.created_at }} | 29 |{{ order.symbol }} | 30 |{{ order.type }} | 31 |{{ order.side }} | 32 |{{ order.qty }} | 33 |{{ order.limit_price }} | 34 |{{ order.filled_avg_price }} | 35 |