Forráskód Böngészése

Refactor into MVC pattern

Foppe Hemminga 6 éve
szülő
commit
5e5e10196e
5 módosított fájl, 149 hozzáadás és 81 törlés
  1. 0 80
      data.py
  2. 31 0
      main.py
  3. 81 0
      model.py
  4. 1 1
      stocks.py
  5. 36 0
      view.py

+ 0 - 80
data.py

@@ -1,80 +0,0 @@
-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.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}
-    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('/home/rgiskard/npc-drops/timestamp.txt', 'r') as f:
-    timestamp_stored = f.read()
-    # print("timestamp_stored: {}".format(timestamp_stored))
-    # print("timestamp_latest: {}".format(timestamp_latest))
-    if timestamp_latest == int(timestamp_stored):
-        # print(timestamp_latest)
-        # Exit when there is nothing to do
-        sys.exit()
-
-with open('/home/rgiskard/npc-drops/timestamp.txt', 'w') as f:
-    f.write("{}".format(timestamp_latest))
-
-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()

+ 31 - 0
main.py

@@ -0,0 +1,31 @@
+import model
+import sys
+import stocks
+import view
+
+"""
+    This is the controller file
+"""
+
+if __name__ == '__main__':
+    timestamp_latest = model.get_timestamp_latest()
+    timestamp_stored = model.get_timestamp_stored()
+    if timestamp_latest == timestamp_stored:
+        """Nothing to do"""
+        sys.exit()
+    # Update timestamp_stored
+    model.put_timestamp_stored(timestamp_latest)
+    timestamp_previous = model.get_timestamp_previous()
+    for stock in stocks.stocks:
+        data_previous = model.get_data(stock.stock_id, timestamp_previous)
+        data_latest = model.get_data(stock.stock_id, timestamp_latest)
+        threshold = stock[3]
+        is_drop = model.process_data(data_previous, data_latest, threshold)
+        stock_name = stock[0]
+        current_price = data_latest.current_price
+        quantity = data_latest.available_shares = data_previous.available_shares
+        message = view.create_message(
+            stock_name, timestamp_latest, current_price, quantity)
+        print(message)
+        if is_drop:
+            view.broadcast(message)

+ 81 - 0
model.py

@@ -0,0 +1,81 @@
+import database
+import psycopg2.extras
+
+
+def get_timestamp_previous():
+    """
+    Retrieve second to last timestamp from the stocks database
+    :return timestamp:
+    """
+    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()
+    this_timestamp_previous = res.timestamp
+    cursor.close()
+    db.close()
+    return this_timestamp_previous
+
+
+def get_timestamp_latest():
+    """
+    Retrieve latest timestamp from the stocks database
+    :return timestamp:
+    """
+    db = database.db
+    cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
+    query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1;"""
+    cursor.execute(query)
+    res = cursor.fetchone()
+    this_timestamp_latest = res.timestamp
+    cursor.close()
+    db.close()
+    return this_timestamp_latest
+
+
+def get_timestamp_stored():
+    """
+    Retrieve the timestamp when the program checked the database
+    :return timestamp:
+    """
+    with open('npc-drops/timestamp.txt', 'r') as f:
+        this_timestamp_stored = f.read()
+    return int(this_timestamp_stored)
+
+
+def put_timestamp_stored(this_timestamp):
+    """
+    Update timestamp when the program checked the database
+    :param this_timestamp:
+    :return:
+    """
+    with open('npc_drops/timestamp.txt', 'w') as f:
+        f.write(this_timestamp)
+
+
+def get_data(stock_id, this_timestamp):
+    db = database.db
+    cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
+    query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
+    cursor.execute(query, (stock_id, this_timestamp))
+    this_data = cursor.fetchone()
+    cursor.close()
+    db.close()
+    return this_data
+
+
+def process_data(this_data_previous, this_data_latest, this_threshold):
+    """
+    Checks if there is enough change to call it a drop
+    :param this_data_previous:
+    :param this_data_latest:
+    :param this_threshold
+    :return boolean:
+    """
+    this_drop = False
+    quantity_previous = this_data_previous.available_shares * this_data_latest.current_price
+    quantity_latest = this_data_latest.available_shares * this_data_latest.current_price
+    if quantity_latest - quantity_previous > this_threshold * 1e9:
+        this_drop = True
+    return this_drop

+ 1 - 1
stocks.py

@@ -1,6 +1,6 @@
 # stock name, stock number, max price, min(price * drop) in B
 # So this means: stock name, stock # 15 (FHC), max price $335  and a > $10B drop
-fhc = ("FHC", 15, 335, 10)
+fhc = ("FHG", 15, 335, 10)
 yaz = ("YAZ", 8, 60, 10)
 
 # Put all stocks in this set

+ 36 - 0
view.py

@@ -0,0 +1,36 @@
+import os
+from datetime import datetime
+import requests
+
+
+def create_message(name, timestamp, price, quantity):
+    """
+    Creates the string to be broadcast
+    :param name:
+    :param timestamp:
+    :param price:
+    :param quantity:
+    :return:
+    """
+    this_time = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
+    this_drop_decimal = float(quantity * price / 1e9)
+    this_message = "{}: {} dropped {} shares at ${:.2f} for a grand total of ${:.1f}B".format(
+        this_time, name, quantity, price, this_drop_decimal)
+    return this_message
+
+
+def broadcast(this_message):
+    """
+
+    :param this_message:
+    :return:
+    """
+    # development only
+    # load_dotenv()
+    url = os.environ["BROADCAST_URL"]
+    json = {'content': this_message}
+    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")))