Advertisement
BAMpas

Untitled

Jun 18th, 2025
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. import json
  2. import websocket
  3. import threading
  4. import time
  5. from datetime import datetime, timedelta
  6. import pickle
  7. import os
  8.  
  9. FINNHUB_API_KEY = "******************"
  10. STOP_HOUR = 13 # 1 PM in 24-hour format
  11. DATA_FILE = "data_spy_3hrs_250618.pkl"
  12.  
  13. # Store data
  14. my_data = []
  15. last_timestamp = None # Keep track of the last timestamp to prevent duplicates
  16.  
  17. # Load previous data if available
  18. if os.path.exists(DATA_FILE):
  19. with open(DATA_FILE, "rb") as file:
  20. my_data = pickle.load(file)
  21. if my_data:
  22. last_timestamp = my_data[-1]["timestamp"] # Get the last recorded timestamp
  23. print(f"Loaded {len(my_data)} records from previous session.")
  24.  
  25. # Function to save data
  26. def save_data():
  27. with open(DATA_FILE, "wb") as file:
  28. pickle.dump(my_data, file)
  29. print(f"Saved {len(my_data)} records to {DATA_FILE}")
  30.  
  31. def on_message(ws, message):
  32. global my_data, last_timestamp
  33. data = json.loads(message)
  34.  
  35. print(data)
  36.  
  37. # Stop collecting data after 1 PM
  38. if datetime.now().hour >= STOP_HOUR:
  39. print("1 PM reached, stopping data collection.")
  40. ws.close()
  41. return
  42.  
  43. if "data" in data:
  44. for trade in data["data"]:
  45. trade_timestamp = trade["t"] / 1000 # Convert from ms to seconds
  46.  
  47. # Only save new data (avoid duplicates)
  48. if last_timestamp is None or trade_timestamp > last_timestamp:
  49. my_data.append({
  50. "timestamp": trade_timestamp,
  51. "price": trade["p"],
  52. "volume": trade["v"]
  53. })
  54. last_timestamp = trade_timestamp # Update last timestamp
  55.  
  56. def on_error(ws, error):
  57. print("WebSocket error:", error)
  58.  
  59. def on_close(ws, close_status_code, close_msg):
  60. print("WebSocket closed.")
  61. save_data() # Save data before closing
  62.  
  63. # Only restart the WebSocket if it's before 1 PM
  64. if datetime.now().hour < STOP_HOUR:
  65. print("Reconnecting in 1 second...")
  66. time.sleep(1)
  67. start_websocket()
  68. else:
  69. print("1 PM or later – WebSocket will not restart.")
  70.  
  71. def on_open(ws):
  72. ws.send(json.dumps({"type": "subscribe", "symbol": "SPY"}))
  73. print("Subscribed to SPY")
  74.  
  75. def start_websocket():
  76. while datetime.now().hour < STOP_HOUR:
  77. try:
  78. ws = websocket.WebSocketApp(
  79. f"wss://ws.finnhub.io?token={FINNHUB_API_KEY}",
  80. on_message=on_message,
  81. on_error=on_error,
  82. on_close=on_close
  83. )
  84. ws.on_open = on_open
  85. ws.run_forever()
  86. except Exception as e:
  87. print(f"Error: {e}. Reconnecting in 1 second...")
  88. time.sleep(1)
  89.  
  90. # Wait until 6:30 AM before starting
  91. now = datetime.now()
  92. # target_time = now.replace(hour=6, minute=30, second=0, microsecond=0)
  93. # if now > target_time:
  94. # target_time += timedelta(days=1)
  95.  
  96. # print("Waiting until:", target_time)
  97. # time.sleep((target_time - now).total_seconds())
  98.  
  99. print("Starting WebSocket...")
  100. start_websocket()
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement