├── .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 | 13 |

Alpaca Dashboard

14 | 15 | this is local 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | {% for order in alpaca_orders %} 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | {% endfor %} 37 |
createdsymboltypesideqtylimit pricefilled price
{{ order.created_at }}{{ order.symbol }}{{ order.type }}{{ order.side }}{{ order.qty }}{{ order.limit_price }}{{ order.filled_avg_price }}
38 | 39 | -------------------------------------------------------------------------------- /tradingview-test-payloads/webhook_message_filled.txt: -------------------------------------------------------------------------------- 1 | { 2 | "passphrase": "somelongstring123", 3 | "time": "2020-09-05T19:47:00Z", 4 | "ticker": "AAPL", 5 | "bar": { 6 | "time": "2020-09-05T19:46:00Z", 7 | "open": 126.35, 8 | "high": 128.02, 9 | "low": 126.02, 10 | "close": 127.75, 11 | "volume": 12345 12 | }, 13 | "strategy": { 14 | "position_size": 171, 15 | "order_action": "buy", 16 | "order_contracts": 171, 17 | "order_price": 128.50, 18 | "order_id": "Close entry(s) order long", 19 | "market_position": "long", 20 | "market_position_size": 171, 21 | "prev_market_position": "flat", 22 | "prev_market_position_size": 0 23 | } 24 | } -------------------------------------------------------------------------------- /tradingview-test-payloads/webhook_message_format.txt: -------------------------------------------------------------------------------- 1 | { 2 | "passphrase": "somelongstring123", 3 | "time": "{{timenow}}", 4 | "exchange": "{{exchange}}", 5 | "ticker": "{{ticker}}", 6 | "bar": { 7 | "time": "{{time}}", 8 | "open": {{open}}, 9 | "high": {{high}}, 10 | "low": {{low}}, 11 | "close": {{close}}, 12 | "volume": {{volume}} 13 | }, 14 | "strategy": { 15 | "position_size": {{strategy.position_size}}, 16 | "order_action": "{{strategy.order.action}}", 17 | "order_contracts": {{strategy.order.contracts}}, 18 | "order_price": {{strategy.order.price}}, 19 | "order_id": "{{strategy.order.id}}", 20 | "market_position": "{{strategy.market_position}}", 21 | "market_position_size": {{strategy.market_position_size}}, 22 | "prev_market_position": "{{strategy.prev_market_position}}", 23 | "prev_market_position_size": {{strategy.prev_market_position_size}} 24 | } 25 | } --------------------------------------------------------------------------------