| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import database
- import psycopg2.extras
- import stocks
- from dotenv import load_dotenv
- import os
- import sys
- from pprint import pprint
- from datetime import datetime
- from urllib.parse import urlencode
- # from urllib.request import Request, urlopen
- import requests
- def broadcast(name, timestamp, price, quantity, this_drop):
- # development only
- load_dotenv()
- url = os.environ["BROADCAST_URL"]
- # Create the string
- time = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
- print(time)
- this_drop_decimal = float(this_drop / 1e9)
- string = "{}: {} dropped {} shares at ${:.2f} for a grand total of ${:.1f}B".format(
- time, name, quantity, price, this_drop_decimal)
- json = {'content': string}
- print(urlencode(json).encode())
- response = requests.post(url, json=json)
- if response.status_code in [200, 204]:
- print("Webhook executed")
- else:
- print("status code {}: {}".format(response.status_code, response.content.decode("utf-8")))
- # Retrieve last and second to last timestamp from the serverS
- db = database.db
- cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
- query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1 OFFSET 1;"""
- cursor.execute(query)
- res = cursor.fetchone()
- timestamp_previous = res.timestamp
- query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1;"""
- cursor.execute(query)
- res = cursor.fetchone()
- timestamp_latest = res.timestamp
- with open('timestamp.txt', 'w+') as f:
- timestamp_stored = f.read() or 0
- if timestamp_latest != timestamp_stored:
- f.write("{}".format(timestamp_latest))
- else:
- # Exit when there is nothing to do
- sys.exit()
- print(timestamp_previous)
- print(timestamp_latest)
- for stock in stocks.stocks:
- query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
- cursor.execute(query, (stock[1], timestamp_latest))
- data_latest = cursor.fetchone()
- cursor.execute(query, (stock[1], timestamp_previous))
- data_previous = cursor.fetchone()
- pprint(data_latest)
- pprint(data_previous)
- # Calculations
- available_latest = int(data_latest.available_shares * data_latest.current_price)
- available_previous = int(data_previous.available_shares * data_previous.current_price)
- print(available_latest)
- print(available_previous)
- drop = available_latest - available_previous
- # broadcast(stock[0], timestamp_latest, data_latest.current_price, data_latest.available_shares, drop)
- if drop > stock[3] * 1e9:
- broadcast(stock[0], timestamp_latest, data_latest.current_price, data_latest.available_shares, drop)
- cursor.close()
- db.close()
|