-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdata_server.py
310 lines (263 loc) · 11.5 KB
/
data_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import json
import websocket
import threading
import time
import requests
from datetime import datetime, timedelta
import logging
from collections import deque
import os
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('market_feed.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class MarketDataServer:
def __init__(self, api_key, pairs=None):
self.api_key = api_key
self.pairs = pairs or ['EUR-USD'] # Default to EUR-USD if no pairs specified
self.ws = None
self.is_running = False
self.data_buffer = {} # Buffer for each pair
self.buffer_size = 1000 # Keep last 1000 data points per pair
self.last_historical_update = {}
self.historical_update_interval = 3600 # Update historical data every hour
self.ws_lock = threading.Lock() # Lock for WebSocket operations
self.reconnect_delay = 5 # Initial reconnect delay
self.max_reconnect_delay = 60 # Maximum reconnect delay
# Initialize buffers for each pair
for pair in self.pairs:
self.data_buffer[pair] = deque(maxlen=self.buffer_size)
self.last_historical_update[pair] = 0
# Ensure data directory exists
os.makedirs('feeds/forex', exist_ok=True)
def fetch_historical_data(self, pair):
"""Fetch historical data from Polygon REST API"""
try:
# Get data for the last 24 hours
end = datetime.now()
start = end - timedelta(days=1)
url = f"https://api.polygon.io/v2/aggs/ticker/C:{pair}/range/1/minute/{start.strftime('%Y-%m-%d')}/{end.strftime('%Y-%m-%d')}?adjusted=true&sort=asc&limit=50000&apiKey={self.api_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data['resultsCount'] > 0:
formatted_data = []
for result in data['results']:
entry = {
'type': 'per-minute',
'pair': pair.replace('-', '/'),
'HH': result['h'],
'HL': result['l'],
'LH': result['h'],
'LL': result['l'],
'timestamp': result['t']
}
formatted_data.append(entry)
self.data_buffer[pair].append(entry)
# Save to file
self.save_to_json(formatted_data, pair)
logger.info(f"Historical data fetched for {pair}: {len(formatted_data)} entries")
self.last_historical_update[pair] = time.time()
return True
logger.error(f"Failed to fetch historical data for {pair}: {response.status_code}")
return False
except Exception as e:
logger.error(f"Error fetching historical data for {pair}: {str(e)}")
return False
def save_to_json(self, data, pair):
"""Save data to JSON file with proper formatting"""
filename = f'feeds/forex/{pair}.json'
try:
# If file exists, read existing data
existing_data = []
if os.path.exists(filename):
with open(filename, 'r') as f:
for line in f:
try:
existing_data.append(json.loads(line))
except json.JSONDecodeError:
continue
# Combine existing data with new data and sort by timestamp
all_data = existing_data + (data if isinstance(data, list) else [data])
all_data.sort(key=lambda x: x['timestamp'])
# Keep only the most recent data points
if len(all_data) > self.buffer_size:
all_data = all_data[-self.buffer_size:]
# Write back to file
with open(filename, 'w') as f:
for entry in all_data:
json.dump(entry, f)
f.write('\n')
except Exception as e:
logger.error(f"Error saving data to {filename}: {str(e)}")
def on_message(self, ws, message):
"""Handle incoming WebSocket messages"""
try:
data = json.loads(message)
if not isinstance(data, list) or len(data) == 0:
return
for entry in data:
output_data = None
if entry.get('ev') == 'CA': # Per-minute data
output_data = {
'type': 'per-minute',
'pair': entry['pair'],
'HH': entry['h'],
'HL': entry['l'],
'LH': entry['h'],
'LL': entry['l'],
'timestamp': entry['s']
}
elif entry.get('ev') == 'CAS': # Per-second data
output_data = {
'type': 'per-second',
'pair': entry['pair'],
'HH': entry['h'],
'HL': entry['l'],
'LH': entry['h'],
'LL': entry['l'],
'timestamp': entry['s']
}
elif entry.get('ev') == 'C': # Quote data
output_data = {
'type': 'quote',
'pair': entry['p'],
'bid': entry['b'],
'ask': entry['a'],
'timestamp': entry['t']
}
if output_data:
pair = output_data['pair'].replace('/', '-')
if pair in self.pairs:
self.data_buffer[pair].append(output_data)
self.save_to_json(output_data, pair)
except Exception as e:
logger.error(f"Error processing message: {str(e)}")
def on_error(self, ws, error):
"""Handle WebSocket errors"""
logger.error(f"WebSocket error: {str(error)}")
self.schedule_reconnect()
def on_close(self, ws, close_status_code, close_msg):
"""Handle WebSocket connection close"""
logger.info(f"WebSocket connection closed: {close_status_code} - {close_msg}")
self.schedule_reconnect()
def on_open(self, ws):
"""Handle WebSocket connection open"""
try:
logger.info("WebSocket connected")
# Reset reconnect delay on successful connection
self.reconnect_delay = 5
# Authenticate
auth_data = {"action":"auth","params": self.api_key}
ws.send(json.dumps(auth_data))
logger.info("Authentication sent")
# Subscribe to data streams for each pair
subscriptions = []
for pair in self.pairs:
subscriptions.extend([
f"CA.C:{pair}", # Per-minute aggregates
f"CAS.C:{pair}", # Per-second aggregates
f"C.C:{pair}" # Quotes
])
subscribe_data = {"action":"subscribe", "params":",".join(subscriptions)}
ws.send(json.dumps(subscribe_data))
logger.info(f"Subscribed to {len(self.pairs)} pairs")
except Exception as e:
logger.error(f"Error in on_open: {str(e)}")
self.schedule_reconnect()
def schedule_reconnect(self):
"""Schedule a reconnection attempt with exponential backoff"""
if self.is_running:
logger.info(f"Scheduling reconnect in {self.reconnect_delay} seconds")
threading.Timer(self.reconnect_delay, self.connect_websocket).start()
# Increase delay for next attempt
self.reconnect_delay = min(self.reconnect_delay * 2, self.max_reconnect_delay)
def connect_websocket(self):
"""Establish WebSocket connection with proper error handling"""
if not self.is_running:
return
with self.ws_lock:
try:
if self.ws:
self.ws.close()
self.ws = None
self.ws = websocket.WebSocketApp(
"wss://socket.polygon.io/forex",
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close
)
# Start WebSocket connection in a new thread
ws_thread = threading.Thread(
target=lambda: self.ws.run_forever(
ping_interval=30,
ping_timeout=10,
ping_payload='{"action":"ping"}'
)
)
ws_thread.daemon = True
ws_thread.start()
except Exception as e:
logger.error(f"Error connecting to WebSocket: {str(e)}")
self.schedule_reconnect()
def start(self):
"""Start the market data server"""
if self.is_running:
return
self.is_running = True
# Start historical data update thread
threading.Thread(target=self._historical_update_loop, daemon=True).start()
# Initial historical data fetch
for pair in self.pairs:
self.fetch_historical_data(pair)
# Start WebSocket connection
self.connect_websocket()
def stop(self):
"""Stop the market data server"""
self.is_running = False
with self.ws_lock:
if self.ws:
self.ws.close()
self.ws = None
def _historical_update_loop(self):
"""Background thread to periodically update historical data"""
while self.is_running:
current_time = time.time()
for pair in self.pairs:
# Update if more than update_interval has passed
if current_time - self.last_historical_update.get(pair, 0) > self.historical_update_interval:
self.fetch_historical_data(pair)
time.sleep(60) # Check every minute
def get_data(self, pair, limit=None):
"""Get the latest data for a pair"""
pair = pair.replace('/', '-')
if pair not in self.data_buffer:
return []
data = list(self.data_buffer[pair])
if limit:
data = data[-limit:]
return data
if __name__ == "__main__":
# Load API key from config
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
api_key = config.get('API_KEYS', 'POLYGON_API_KEY')
# Enable debug logging for websocket-client
websocket.enableTrace(True)
# Start server with EUR/USD pair
server = MarketDataServer(api_key, pairs=['EUR-USD'])
try:
server.start()
# Keep main thread alive
while True:
time.sleep(1)
except KeyboardInterrupt:
server.stop()