· 6 years ago · Jan 23, 2020, 05:32 PM
1from flask import Flask, request, abort
2import ast
3
4
5def parse_webhook(webhook_data):
6
7 """
8 This function takes the string from tradingview and turns it into a python dict.
9 :param webhook_data: POST data from tradingview, as a string.
10 :return: Dictionary version of string.
11 """
12
13 data = ast.literal_eval(webhook_data)
14 return data
15
16
17
18def send_order(data):
19
20 """
21 This function sends the order to the exchange using ccxt.
22 :param data: python dict, with keys as the API parameters.
23 :return: the response from the exchange.
24 """
25
26 # Send the order to the exchange, using the values from the tradingview alert.
27 print('Sending:', data['symbol'], data['type'], data['side'], data['amount'])
28 order = exchange.create_order(data['symbol'], data['type'], data['side'], data['amount'])
29 # This is the last step, the response from the exchange will tell us if it made it and what errors pop up if not.
30 print('Exchange Response:', order)
31
32# Create Flask object called app.
33app = Flask(__name__)
34
35
36# Create root to easily let us know its on/working.
37@app.route('/')
38def root():
39 return 'online'
40
41
42@app.route('/webhook', methods=['POST'])
43def webhook():
44 if request.method == 'POST':
45 # Parse the string data from tradingview into a python dict
46 data = parse_webhook(request.get_data(as_text=True))
47 # Check that the key is correct
48 symbol = data['symbol']
49 f = open(f"{symbol}.txt", "a")
50 f.write(data['symbol'] + ' ')
51 f.write(data['side'] + ' ')
52 f.write(data['amount'] + ' ')
53 f.write(data['price'])
54 f.close()
55 if True:
56 print(' [Alert Received] ')
57 print('POST Received:', data)
58 return '', 200
59 else:
60 abort(403)
61 else:
62 abort(400)
63
64
65if __name__ == '__main__':
66 app.run()