-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
88 lines (69 loc) · 2.5 KB
/
app.py
File metadata and controls
88 lines (69 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from flask import Flask, jsonify, request
# hack needed in order to use local modules
# run with python -m flask run --host=0.0.0.0
import sys, os
sys.path.append(os.getcwd())
from order.order import Order
from accounts.accounts import Accounts
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import CHARIOT
from datetime import datetime
import time
app = Flask(__name__)
oauth_lock = False
session, base_url, brk_acc = None, None, None
def renew_session_token():
if oauth_lock:
print("\nOAUTH locked, skipping renew cycle\n")
return
today = datetime.now()
print('\n', "TOK Session token refresh at ", today.strftime('%Y-%m-%d | %H:%M:%S'), '\n')
response = CHARIOT.renew_session(session)
if response.status_code != 200:
print(f"Refresh failed once, trying again in {CHARIOT.OAUTH_RETRY_MIN} minutes")
time.sleep(CHARIOT.OAUTH_RETRY_MIN*60)
response = CHARIOT.renew_session(session)
if response.status_code != 200:
print("Refresh failed twice")
def renew_access_token():
oauth_lock = True
session, base_url = CHARIOT.oauth()
oauth_lock = False
accounts = Accounts(session, base_url)
_, brk_acc = accounts.cash_balance_from_account_AUTO()
today = datetime.now()
print("\nTOK Access token generated at ", today.strftime('%Y-%m-%d | %H:%M:%S'), '\n')
renew_access_token()
accounts = Accounts(session, base_url)
scheduler = BackgroundScheduler()
scheduler.add_job(func=renew_session_token, trigger="interval", seconds=CHARIOT.OAUTH_REFRESH_MIN*60)
scheduler.add_job(func=renew_access_token, trigger=CronTrigger(hour=0, minute=0))
scheduler.start()
@app.route('/', methods=['GET'])
def get_cash():
cash = CHARIOT.get_cash_balance(session, base_url)
if cash:
return jsonify({'cash' : cash})
return jsonify({})
@app.route('/market', methods=['POST'])
def market():
data = request.form
ticker = data.get('ticker')
shares = int(data.get('shares'))
action = data.get('action')
order = Order(session, brk_acc, base_url)
call = order.place_market_order_AUTO(ticker, shares, action)
return jsonify({}), call.status_code
@app.route('/buy_limit', methods=['POST'])
def buy_limit():
data = request.form
ticker = data.get('ticker')
direction = data.get('direction')
shares = int(data.get('shares'))
stop = float(data.get('stop'))
order = Order(session, brk_acc, base_url)
call = order.place_limit_order_AUTO(ticker, shares, stop, direction)
return jsonify({}), call.status_code
if __name__ == '__main__':
app.run(debug=True, threaded=True)