dukascript 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 drui9
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: dukascript
3
+ Version: 0.0.0
4
+ Summary: Download tick data from Dukascopy Bank SA to local cache, and simulate time-ordered price streams
5
+ Author-email: Eghosa Osayande <osayandeeghosam@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 drui9
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/Eghosa-Osayande/dukascript
28
+ Keywords: tick-data,forex-data,tick-api,ticks,dukascopy
29
+ Classifier: License :: OSI Approved :: MIT License
30
+ Classifier: Programming Language :: Python
31
+ Classifier: Programming Language :: Python :: 3
32
+ Requires-Python: >=3.10
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: pandas
36
+ Requires-Dist: requests
37
+ Provides-Extra: dev
38
+ Requires-Dist: build; extra == "dev"
39
+ Requires-Dist: twine; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # dukascript
43
+
44
+ Download and stream historical data from Dukascopy Bank SA.
@@ -0,0 +1,3 @@
1
+ # dukascript
2
+
3
+ Download and stream historical data from Dukascopy Bank SA.
@@ -0,0 +1,423 @@
1
+ import pandas as pd
2
+ import requests
3
+ from datetime import datetime, timedelta
4
+ import json
5
+ import random
6
+ import string
7
+ from time import sleep
8
+ import logging
9
+
10
+ from .instruments import *
11
+
12
+ TIME_UNIT_MONTH = "MONTH"
13
+ TIME_UNIT_WEEK = "WEEK"
14
+ TIME_UNIT_DAY = "DAY"
15
+ TIME_UNIT_HOUR = "HOUR"
16
+ TIME_UNIT_MIN = "MIN"
17
+ TIME_UNIT_SEC = "SEC"
18
+ TIME_UNIT_TICK = "TICK"
19
+
20
+ INTERVAL_MONTH_1 = f"1{TIME_UNIT_MONTH}"
21
+ INTERVAL_WEEK_1 = f"1{TIME_UNIT_WEEK}"
22
+ INTERVAL_DAY_1 = f"1{TIME_UNIT_DAY}"
23
+ INTERVAL_HOUR_4 = f"4{TIME_UNIT_HOUR}"
24
+ INTERVAL_HOUR_1 = f"1{TIME_UNIT_HOUR}"
25
+ INTERVAL_MIN_30 = f"30{TIME_UNIT_MIN}"
26
+ INTERVAL_MIN_15 = f"15{TIME_UNIT_MIN}"
27
+ INTERVAL_MIN_10 = f"10{TIME_UNIT_MIN}"
28
+ INTERVAL_MIN_5 = f"5{TIME_UNIT_MIN}"
29
+ INTERVAL_MIN_1 = f"1{TIME_UNIT_MIN}"
30
+ INTERVAL_SEC_30 = f"30{TIME_UNIT_SEC}"
31
+ INTERVAL_SEC_10 = f"10{TIME_UNIT_SEC}"
32
+ INTERVAL_SEC_1 = f"1{TIME_UNIT_SEC}"
33
+ INTERVAL_TICK = TIME_UNIT_TICK
34
+
35
+ INTERVALS_SET = {
36
+ INTERVAL_MONTH_1,
37
+ INTERVAL_WEEK_1,
38
+ INTERVAL_DAY_1,
39
+ INTERVAL_HOUR_4,
40
+ INTERVAL_HOUR_1,
41
+ INTERVAL_MIN_30,
42
+ INTERVAL_MIN_15,
43
+ INTERVAL_MIN_10,
44
+ INTERVAL_MIN_5,
45
+ INTERVAL_MIN_1,
46
+ INTERVAL_SEC_30,
47
+ INTERVAL_SEC_10,
48
+ INTERVAL_SEC_1,
49
+ }
50
+
51
+ OFFER_SIDE_BID = "B"
52
+ OFFER_SIDE_ASK = "A"
53
+
54
+
55
+ def _get_custom_logger(debug=False):
56
+ logger = logging.getLogger("DUKASCRIPT")
57
+ logger.setLevel(logging.DEBUG if debug else logging.INFO)
58
+
59
+ if not logger.handlers:
60
+ # Formatter
61
+ formatter = logging.Formatter("[%(levelname)s] %(message)s")
62
+
63
+ # Console Handler
64
+ ch = logging.StreamHandler()
65
+ ch.setLevel(logging.DEBUG if debug else logging.INFO)
66
+ ch.setFormatter(formatter)
67
+
68
+ logger.addHandler(ch)
69
+
70
+ return logger
71
+
72
+
73
+ def _is_valid_api_interval(interval):
74
+ return True if interval in INTERVALS_SET else False
75
+
76
+
77
+ def _resample_to_nearest(
78
+ timestamp: datetime,
79
+ time_unit: str,
80
+ interval_value: int,
81
+ ) -> datetime:
82
+ # Round to the nearest time unit based on the interval value
83
+ if time_unit == TIME_UNIT_SEC:
84
+ subtraction = timestamp.second % interval_value
85
+ return timestamp - timedelta(
86
+ seconds=subtraction,
87
+ microseconds=timestamp.microsecond,
88
+ )
89
+ elif time_unit == TIME_UNIT_MIN:
90
+ subtraction = timestamp.minute % interval_value
91
+ return timestamp - timedelta(
92
+ minutes=subtraction,
93
+ seconds=timestamp.second,
94
+ microseconds=timestamp.microsecond,
95
+ )
96
+ elif time_unit == TIME_UNIT_HOUR:
97
+ subtraction = timestamp.hour % interval_value
98
+ return timestamp - timedelta(
99
+ hours=subtraction,
100
+ minutes=timestamp.minute,
101
+ seconds=timestamp.second,
102
+ microseconds=timestamp.microsecond,
103
+ )
104
+ elif time_unit == TIME_UNIT_DAY:
105
+ subtraction = timestamp.day % interval_value
106
+ return timestamp - timedelta(
107
+ days=subtraction,
108
+ hours=timestamp.hour,
109
+ minutes=timestamp.minute,
110
+ seconds=timestamp.second,
111
+ microseconds=timestamp.microsecond,
112
+ )
113
+ elif time_unit == TIME_UNIT_WEEK:
114
+ subtraction = (timestamp.weekday() + 1) % (interval_value * 7)
115
+ return timestamp - timedelta(
116
+ days=subtraction,
117
+ hours=timestamp.hour,
118
+ minutes=timestamp.minute,
119
+ seconds=timestamp.second,
120
+ microseconds=timestamp.microsecond,
121
+ )
122
+ elif time_unit == TIME_UNIT_MONTH:
123
+ month = (timestamp.month // interval_value) + 1
124
+ return datetime(timestamp.year, month, 1, 0, 0, 0, 0, timestamp.tzinfo)
125
+ elif time_unit == TIME_UNIT_TICK:
126
+ return timestamp
127
+
128
+ raise NotImplementedError(f"resampling not implemented for {time_unit}")
129
+
130
+
131
+ def _get_dataframe_columns_for_timeunit(time_unit: str) -> list[str]:
132
+
133
+ ohlc_df = ["timestamp", "open", "high", "low", "close", "volume"]
134
+ tick_df = ["timestamp", "bidPrice", "askPrice", "bidVolume", "askVolume"]
135
+
136
+ df = {
137
+ TIME_UNIT_DAY: ohlc_df,
138
+ TIME_UNIT_HOUR: ohlc_df,
139
+ TIME_UNIT_MIN: ohlc_df,
140
+ TIME_UNIT_MONTH: ohlc_df,
141
+ TIME_UNIT_SEC: ohlc_df,
142
+ TIME_UNIT_TICK: tick_df,
143
+ TIME_UNIT_WEEK: ohlc_df,
144
+ }[time_unit]
145
+
146
+ return df
147
+
148
+
149
+ def _fetch(
150
+ instrument: str,
151
+ interval: str,
152
+ offer_side: str,
153
+ last_update: int,
154
+ logger: logging.Logger = logging.getLogger(),
155
+ limit: int = None,
156
+ ):
157
+ characters = string.ascii_letters + string.digits
158
+ jsonp = f"_callbacks____{''.join(random.choices(characters, k=9))}"
159
+
160
+ query_params = {
161
+ "path": "chart/json3",
162
+ "splits": "true",
163
+ "stocks": "true",
164
+ "time_direction": "N",
165
+ "jsonp": jsonp,
166
+ "last_update": f"{int(last_update)}",
167
+ "offer_side": f"{offer_side}",
168
+ "instrument": f"{instrument}",
169
+ "interval": f"{interval}",
170
+ }
171
+
172
+ if limit is not None:
173
+ # max limit is 30_000
174
+ query_params["limit"] = f"{int(limit)}"
175
+
176
+ base_url = "https://freeserv.dukascopy.com/2.0/index.php"
177
+
178
+ headers = {
179
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0",
180
+ "Host": "freeserv.dukascopy.com",
181
+ "Referer": "https://freeserv.dukascopy.com/2.0/?path=chart/index&showUI=true&showTabs=true&showParameterToolbar=true&showOfferSide=true&allowInstrumentChange=true&allowPeriodChange=true&allowOfferSideChange=true&showAdditionalToolbar=true&showExportImportWorkspace=true&allowSocialSharing=true&showUndoRedoButtons=true&showDetachButton=true&presentationType=candle&axisX=true&axisY=true&legend=true&timeline=true&showDateSeparators=true&showZoom=true&showScrollButtons=true&showAutoShiftButton=true&crosshair=true&borders=false&freeMode=false&theme=Pastelle&uiColor=%23000&availableInstruments=l%3A&instrument=EUR/USD&period=5&offerSide=BID&timezone=0&live=true&allowPan=true&width=100%25&height=700&adv=popup&lang=en",
182
+ }
183
+
184
+ logger.debug("query params: %s", query_params)
185
+
186
+ response = requests.get(base_url, headers=headers, params=query_params)
187
+
188
+ jsonText = response.text.removeprefix(f"{jsonp}(").removesuffix(");")
189
+
190
+ return json.loads(jsonText)
191
+
192
+
193
+ def _stream(
194
+ instrument: str,
195
+ interval: str,
196
+ offer_side: str,
197
+ start: datetime,
198
+ end: datetime = None,
199
+ max_retries: int = 7,
200
+ limit: int = None,
201
+ logger: logging.Logger = logging.getLogger(),
202
+ ):
203
+ no_of_retries = 0
204
+ cursor = int(start.timestamp() * 1000)
205
+ end_timestamp = None
206
+ if end is not None:
207
+ end_timestamp = end.timestamp() * 1000
208
+
209
+ is_first_iteration = True
210
+
211
+ logging.info(f"Start Date :{start.isoformat()}")
212
+ logging.info(f"End Date :{'' if end is None else end.isoformat()}")
213
+
214
+ while True:
215
+ try:
216
+
217
+ lastUpdates = _fetch(
218
+ instrument=instrument,
219
+ interval=interval,
220
+ offer_side=offer_side,
221
+ last_update=cursor,
222
+ limit=limit,
223
+ )
224
+
225
+ if not is_first_iteration and lastUpdates[0][0] == cursor:
226
+ lastUpdates = lastUpdates[1:]
227
+
228
+ if len(lastUpdates) < 1:
229
+ if end is not None:
230
+ break
231
+ else:
232
+ continue
233
+
234
+ for row in lastUpdates:
235
+ if end_timestamp is not None and row[0] > end_timestamp:
236
+ return
237
+ if interval == INTERVAL_TICK:
238
+ row[-1] = row[-1] / 1_000_000
239
+ row[-2] = row[-2] / 1_000_000
240
+ yield row
241
+ cursor = row[0]
242
+
243
+ logger.info(
244
+ f"current timestamp :{datetime.fromtimestamp(cursor/1000).isoformat()}"
245
+ )
246
+
247
+ no_of_retries = 0
248
+ is_first_iteration = False
249
+
250
+ except Exception as e:
251
+ import traceback
252
+
253
+ stacktrace = traceback.format_exc()
254
+ no_of_retries += 1
255
+ if max_retries is not None and (no_of_retries - 1) > max_retries:
256
+ logger.debug("error fetching")
257
+ logger.debug(e, stacktrace)
258
+ raise e
259
+ else:
260
+ logger.debug("an error occured", e)
261
+ logger.debug(e, stacktrace)
262
+ logger.debug("retrying")
263
+ sleep(1)
264
+ continue
265
+
266
+
267
+ def fetch(
268
+ instrument: str,
269
+ interval_value: str,
270
+ time_unit: str,
271
+ offer_side: str,
272
+ start: datetime,
273
+ end: datetime,
274
+ max_retries: int = 7,
275
+ limit: int = 30_000, # max 30_000
276
+ debug=False,
277
+ ):
278
+ logger = _get_custom_logger(debug)
279
+ columns = _get_dataframe_columns_for_timeunit(time_unit)
280
+
281
+ data = []
282
+
283
+ interval = (
284
+ time_unit if time_unit == TIME_UNIT_TICK else f"{interval_value}{time_unit}"
285
+ )
286
+
287
+ if not _is_valid_api_interval(interval):
288
+ raise ValueError("allowed intervals ", INTERVALS_SET)
289
+
290
+ datafeed = _stream(
291
+ instrument=instrument,
292
+ interval=interval,
293
+ offer_side=offer_side,
294
+ start=start,
295
+ end=end,
296
+ max_retries=max_retries,
297
+ limit=limit,
298
+ logger=logger,
299
+ )
300
+
301
+ for row in datafeed:
302
+ data.append(row)
303
+
304
+ df = pd.DataFrame(data=data, columns=columns)
305
+ df["timestamp"] = pd.to_datetime(
306
+ df["timestamp"],
307
+ unit="ms",
308
+ utc=True,
309
+ )
310
+ df = df.set_index("timestamp")
311
+ return df
312
+
313
+
314
+ def live_fetch(
315
+ instrument: str,
316
+ interval_value: int,
317
+ time_unit: str,
318
+ offer_side: str,
319
+ start: datetime,
320
+ end: datetime,
321
+ max_retries: int = 7,
322
+ limit: int = 30_000, # max 30_000
323
+ debug=False,
324
+ ):
325
+ logger = _get_custom_logger(debug)
326
+
327
+ # validate time unit
328
+ _resample_to_nearest(
329
+ datetime.now(),
330
+ time_unit,
331
+ interval_value,
332
+ )
333
+
334
+ open, high, low, close, volume = None, 0, 0, 0, 0
335
+
336
+ price_index = {
337
+ OFFER_SIDE_BID: 1,
338
+ OFFER_SIDE_ASK: 2,
339
+ }[offer_side]
340
+
341
+ volume_index = {
342
+ OFFER_SIDE_BID: -2,
343
+ OFFER_SIDE_ASK: -1,
344
+ }[offer_side]
345
+
346
+ last_timestamp = None
347
+
348
+ columns = _get_dataframe_columns_for_timeunit(time_unit)
349
+ df = pd.DataFrame(columns=columns)
350
+ df["timestamp"] = pd.to_datetime(
351
+ df["timestamp"],
352
+ unit="ms",
353
+ utc=True,
354
+ )
355
+ df = df.set_index("timestamp")
356
+
357
+ datafeed = _stream(
358
+ instrument=instrument,
359
+ interval=INTERVAL_TICK,
360
+ offer_side=offer_side,
361
+ start=start,
362
+ end=end,
363
+ max_retries=max_retries,
364
+ limit=limit,
365
+ logger=logger,
366
+ )
367
+
368
+ for row in datafeed:
369
+
370
+ timestamp = _resample_to_nearest(
371
+ pd.to_datetime(
372
+ row[0],
373
+ unit="ms",
374
+ utc=True,
375
+ ),
376
+ time_unit,
377
+ interval_value,
378
+ )
379
+
380
+ if time_unit == TIME_UNIT_TICK:
381
+ df.loc[timestamp] = [
382
+ *row[1:],
383
+ ]
384
+ yield df
385
+ continue
386
+
387
+ if last_timestamp == None:
388
+ last_timestamp = timestamp.timestamp()
389
+
390
+ if timestamp.timestamp() != last_timestamp:
391
+ if open is not None:
392
+ df.loc[timestamp] = [
393
+ open,
394
+ high,
395
+ low,
396
+ close,
397
+ volume,
398
+ ]
399
+
400
+ yield df
401
+ last_timestamp = timestamp.timestamp()
402
+ open = None
403
+
404
+ if open is None:
405
+ open = row[price_index]
406
+ close = open
407
+ low = open
408
+ high = open
409
+ volume = 0
410
+
411
+ close = row[price_index]
412
+ high = max(high, close)
413
+ low = min(low, close)
414
+ volume += row[volume_index]
415
+
416
+ df.loc[timestamp] = [
417
+ open,
418
+ high,
419
+ low,
420
+ close,
421
+ volume,
422
+ ]
423
+ yield df