main.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import model
  2. import sys
  3. import stocks
  4. import view
  5. import database
  6. """
  7. This is the controller file
  8. """
  9. def process_drop(this_stock):
  10. """
  11. Processes call when the action is "DROP"
  12. :param this_stock:
  13. :return:
  14. """
  15. global db
  16. global timestamp_previous
  17. global timestamp_latest
  18. stock_id = this_stock[1]
  19. data_previous = model.get_data(stock_id, timestamp_previous, db)
  20. data_latest = model.get_data(stock_id, timestamp_latest, db)
  21. threshold = this_stock[3]
  22. max_price = this_stock[2]
  23. is_drop = model.process_data(data_previous, data_latest, max_price, threshold)
  24. current_price = float(data_latest.current_price)
  25. quantity = data_latest.available_shares - data_previous.available_shares
  26. stock_name = this_stock[0]
  27. message = view.create_message(
  28. stock_name, timestamp_latest, current_price, quantity)
  29. print(message)
  30. if is_drop:
  31. view.broadcast(message)
  32. def process_forecast(this_stock):
  33. """
  34. Processes FORECAST requests
  35. :param this_stock:
  36. :return:
  37. """
  38. global db
  39. global timestamp_previous
  40. global timestamp_latest
  41. stock_id = this_stock[1]
  42. data_previous = model.get_data(stock_id, timestamp_previous, db)
  43. data_latest = model.get_data(stock_id, timestamp_latest, db)
  44. available = this_stock[3]
  45. max_price = this_stock[2]
  46. forecast_previous = data_previous.forecast
  47. forecast_latest = data_latest.forecast
  48. is_forecast_changed = model.process_forecast(data_previous, data_latest, max_price, available)
  49. current_price = float(data_latest.current_price)
  50. quantity = data_latest.available_shares - data_previous.available_shares
  51. stock_name = this_stock[0]
  52. current_quantity = data_latest.available_shares
  53. message = view.create_message(
  54. stock_name, timestamp_latest, current_price, quantity, current_quantity, forecast_previous, forecast_latest)
  55. print(message)
  56. if is_forecast_changed:
  57. view.broadcast(message)
  58. if __name__ == '__main__':
  59. db = database.db
  60. timestamp_latest = model.get_timestamp_latest(db) # global
  61. timestamp_stored = model.get_timestamp_stored() # global
  62. if timestamp_latest == timestamp_stored:
  63. """Nothing to do"""
  64. sys.exit()
  65. # Update timestamp_stored
  66. model.put_timestamp_stored(timestamp_latest)
  67. timestamp_previous = model.get_timestamp_previous(db) # global
  68. for stock in stocks.stocks:
  69. action = stock[-1]
  70. if action == "DROP":
  71. process_drop(stock)
  72. if action == "FORECAST":
  73. process_forecast(stock)
  74. db.close()