data.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import database
  2. import psycopg2.extras
  3. import stocks
  4. from dotenv import load_dotenv
  5. import os
  6. from pprint import pprint
  7. from datetime import datetime
  8. from urllib.parse import urlencode
  9. # from urllib.request import Request, urlopen
  10. import requests
  11. def broadcast(name, timestamp, price, quantity, this_drop):
  12. # development only
  13. load_dotenv()
  14. url = os.environ["BROADCAST_URL"]
  15. # Create the string
  16. time = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
  17. print(time)
  18. this_drop_decimal = float(this_drop / 1e9)
  19. string = "{}: {} dropped {} shares at ${:.2f} for a grand total of ${:.1f}B".format(
  20. time, name, quantity, price, this_drop_decimal)
  21. json = {'content': string}
  22. print(urlencode(json).encode())
  23. response = requests.post(url, json=json)
  24. if response.status_code in [200, 204]:
  25. print("Webhook executed")
  26. else:
  27. print("status code {}: {}".format(response.status_code, response.content.decode("utf-8")))
  28. # Retrieve last and second to last timestamp from the serverS
  29. db = database.db
  30. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  31. query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1 OFFSET 1;"""
  32. cursor.execute(query)
  33. res = cursor.fetchone()
  34. timestamp_previous = res.timestamp
  35. query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1;"""
  36. cursor.execute(query)
  37. res = cursor.fetchone()
  38. timestamp_latest = res.timestamp
  39. print(timestamp_previous)
  40. print(timestamp_latest)
  41. for stock in stocks.stocks:
  42. query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
  43. cursor.execute(query, (stock[1], timestamp_latest))
  44. data_latest = cursor.fetchone()
  45. cursor.execute(query, (stock[1], timestamp_previous))
  46. data_previous = cursor.fetchone()
  47. pprint(data_latest)
  48. pprint(data_previous)
  49. # Calculations
  50. available_latest = int(data_latest.available_shares * data_latest.current_price)
  51. available_previous = int(data_previous.available_shares * data_previous.current_price)
  52. print(available_latest)
  53. print(available_previous)
  54. drop = available_latest - available_previous
  55. # broadcast(stock[0], timestamp_latest, data_latest.current_price, data_latest.available_shares, drop)
  56. if drop > stock[3] * 1e9:
  57. broadcast(stock[0], timestamp_latest, data_latest.current_price, data_latest.available_shares, drop)
  58. cursor.close()
  59. db.close()