brokerclock 0.1.0__py3-none-any.whl
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.
- brokerclock/__init__.py +42 -0
- brokerclock/_detect.py +181 -0
- brokerclock/_errors.py +29 -0
- brokerclock/_live.py +108 -0
- brokerclock/_zone.py +231 -0
- brokerclock/pandas.py +78 -0
- brokerclock/py.typed +0 -0
- brokerclock-0.1.0.dist-info/METADATA +204 -0
- brokerclock-0.1.0.dist-info/RECORD +11 -0
- brokerclock-0.1.0.dist-info/WHEEL +4 -0
- brokerclock-0.1.0.dist-info/licenses/LICENSE +202 -0
brokerclock/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""MetaTrader broker server time to UTC and back, with daylight saving done right.
|
|
2
|
+
|
|
3
|
+
>>> from datetime import datetime, timezone
|
|
4
|
+
>>> from brokerclock import ServerZone
|
|
5
|
+
>>> zone = ServerZone.us() # GMT+2/+3 following US daylight saving, the most common broker clock
|
|
6
|
+
>>> zone.to_utc(1751371200) # a bar time as MetaTrader returns it: 2025-07-01 12:00 on the server clock
|
|
7
|
+
datetime.datetime(2025, 7, 1, 9, 0, tzinfo=datetime.timezone.utc)
|
|
8
|
+
>>> zone.server_timestamp(datetime(2025, 7, 1, 9, 0, tzinfo=timezone.utc))
|
|
9
|
+
1751371200
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from brokerclock._detect import Detection, WeekClose, detect
|
|
13
|
+
from brokerclock._errors import (
|
|
14
|
+
AmbiguousTimeError,
|
|
15
|
+
BrokerClockError,
|
|
16
|
+
NonexistentTimeError,
|
|
17
|
+
NotEnoughData,
|
|
18
|
+
OffsetOutOfRange,
|
|
19
|
+
StaleTickError,
|
|
20
|
+
ZoneMismatchError,
|
|
21
|
+
)
|
|
22
|
+
from brokerclock._live import check, measure_offset
|
|
23
|
+
from brokerclock._zone import ServerZone
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"AmbiguousTimeError",
|
|
29
|
+
"BrokerClockError",
|
|
30
|
+
"Detection",
|
|
31
|
+
"NonexistentTimeError",
|
|
32
|
+
"NotEnoughData",
|
|
33
|
+
"OffsetOutOfRange",
|
|
34
|
+
"ServerZone",
|
|
35
|
+
"StaleTickError",
|
|
36
|
+
"WeekClose",
|
|
37
|
+
"ZoneMismatchError",
|
|
38
|
+
"__version__",
|
|
39
|
+
"check",
|
|
40
|
+
"detect",
|
|
41
|
+
"measure_offset",
|
|
42
|
+
]
|
brokerclock/_detect.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Find a broker's clock rule from the weekly closes in its price history, without the PC clock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
import operator
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from collections.abc import Iterable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime, time, timedelta, timezone
|
|
12
|
+
from itertools import pairwise
|
|
13
|
+
from zoneinfo import ZoneInfo
|
|
14
|
+
|
|
15
|
+
from brokerclock._errors import NotEnoughData
|
|
16
|
+
from brokerclock._zone import _EPOCH, _MAX_OFFSET, _MIN_OFFSET, _QUARTER_HOUR, _RULES, ServerZone
|
|
17
|
+
|
|
18
|
+
_NEW_YORK = ZoneInfo("America/New_York")
|
|
19
|
+
_WEEKLY_CLOSE = time(17) # Friday 17:00 New York ends the forex week
|
|
20
|
+
_FRIDAY = 4
|
|
21
|
+
_WEEKEND_GAP = timedelta(hours=40)
|
|
22
|
+
_LATE_SLACK = timedelta(seconds=60) # a last bar may end a few seconds after 17:00 (a late tick, a fast clock)
|
|
23
|
+
_MIN_TIMEFRAME = 60
|
|
24
|
+
_MAX_TIMEFRAME = 3600
|
|
25
|
+
_MIN_WEEKS = 2
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class WeekClose:
|
|
30
|
+
"""One weekly close found in the bars.
|
|
31
|
+
|
|
32
|
+
``friday_close_utc`` is the Friday 17:00 New York instant (aware UTC), ``server_close`` the close on the server
|
|
33
|
+
clock in epoch seconds (last bar open + timeframe), and ``offset`` their difference rounded up to 15 minutes.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
friday_close_utc: datetime
|
|
37
|
+
server_close: int
|
|
38
|
+
offset: timedelta
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Detection:
|
|
43
|
+
"""The result of :func:`detect`.
|
|
44
|
+
|
|
45
|
+
``zone`` is the best-scoring server clock, or None when several clocks score the same (``candidates`` then
|
|
46
|
+
holds all of them). ``matched`` of ``total`` weeks agree with it; ``outliers`` are the weeks it does not
|
|
47
|
+
predict (for example early holiday closes), and ``unexplained`` the server close times that fit no Friday.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
zone: ServerZone | None
|
|
51
|
+
candidates: tuple[ServerZone, ...]
|
|
52
|
+
weeks: tuple[WeekClose, ...]
|
|
53
|
+
matched: int
|
|
54
|
+
total: int
|
|
55
|
+
unexplained: tuple[int, ...]
|
|
56
|
+
outliers: tuple[WeekClose, ...]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def ambiguous(self) -> bool:
|
|
60
|
+
"""True when the data cannot tell the candidates apart."""
|
|
61
|
+
return self.zone is None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def detect(bar_times: Iterable[int], timeframe: int = 3600) -> Detection:
|
|
65
|
+
"""Find the server clock from the open times of a forex major's bars.
|
|
66
|
+
|
|
67
|
+
``bar_times`` are server epoch seconds (the ``time`` column of ``copy_rates_*``) in any order; duplicates are
|
|
68
|
+
ignored. ``timeframe`` is the bar length in seconds, from 60 (M1) to 3600 (H1).
|
|
69
|
+
|
|
70
|
+
Each gap of 40 hours or more after a bar marks a weekly close at that bar's open + ``timeframe``. The forex
|
|
71
|
+
week ends on Friday at 17:00 New York, so each close gives the server's offset in that week. Each candidate
|
|
72
|
+
clock (fixed, US, EU or Australian daylight saving, any base offset) scores the weeks it predicts, and the
|
|
73
|
+
best wins. A tie means the data cannot tell the clocks apart.
|
|
74
|
+
|
|
75
|
+
What the data needs:
|
|
76
|
+
|
|
77
|
+
* a forex major such as EURUSD; metals and indices follow their exchange's hours;
|
|
78
|
+
* at least six months of H1 bars, or a span that includes March or late October to early November, when the
|
|
79
|
+
US and EU switch on different dates. Summer-only data cannot separate US from EU rules, and data without a
|
|
80
|
+
switch cannot separate a fixed clock from a switching one;
|
|
81
|
+
* bars of one hour or shorter. The close is taken as the last bar's open + ``timeframe``, so it is exact only
|
|
82
|
+
when a bar ends at the weekly close; longer bars end on the server's 4-hour or day boundaries, which hide
|
|
83
|
+
the switch weeks, so they are rejected. Use M15 or shorter for clocks with 30- or 45-minute offsets.
|
|
84
|
+
|
|
85
|
+
Running it on two majors and comparing the results is good practice.
|
|
86
|
+
|
|
87
|
+
A broker's week ends at or before 17:00 New York, never after, so each offset is rounded up to the next 15
|
|
88
|
+
minutes (after allowing 60 seconds for a bar that ends just past 17:00). Closes less than 14 minutes early
|
|
89
|
+
(16:50 in M5 bars, 16:47 or later in M1 bars) are read correctly. A week that ends 14 minutes or more early
|
|
90
|
+
(16:40, say) reads 15 minutes off: if only some weeks do that they become ``outliers``; if every week does,
|
|
91
|
+
the whole result is 15 minutes off, for example GMT+1:45/+2:45 instead of GMT+2/+3. H1 bars are not
|
|
92
|
+
affected, because the last H1 bar still ends at 17:00.
|
|
93
|
+
|
|
94
|
+
Raises ``NotEnoughData`` when fewer than two weekly closes match a Friday.
|
|
95
|
+
|
|
96
|
+
>>> monday = 1736121600 # 2025-01-06 00:00 on a GMT+2 server, which is Sunday 17:00 New York
|
|
97
|
+
>>> bars = [monday + week * 7 * 86400 + hour * 3600 for week in range(3) for hour in range(120)]
|
|
98
|
+
>>> result = detect(bars) # three weeks of H1 bars: two weekly closes
|
|
99
|
+
>>> result.total, result.weeks[0].offset
|
|
100
|
+
(2, datetime.timedelta(seconds=7200))
|
|
101
|
+
>>> result.ambiguous # January only: no switch, so several clocks fit
|
|
102
|
+
True
|
|
103
|
+
>>> [str(zone) for zone in result.candidates]
|
|
104
|
+
['GMT+2/+3 (US daylight saving)', 'GMT+2/+3 (EU daylight saving)', 'GMT+1/+2 (AU daylight saving)', 'GMT+2 (fixed)']
|
|
105
|
+
"""
|
|
106
|
+
if isinstance(timeframe, bool) or not isinstance(timeframe, numbers.Integral):
|
|
107
|
+
raise ValueError(f"timeframe must be a whole number of seconds, got {timeframe!r}")
|
|
108
|
+
if not _MIN_TIMEFRAME <= timeframe <= _MAX_TIMEFRAME:
|
|
109
|
+
raise ValueError(f"timeframe must be between 60 and 3600 seconds (M1 to H1), got {timeframe}")
|
|
110
|
+
weeks: list[WeekClose] = []
|
|
111
|
+
unexplained: list[int] = []
|
|
112
|
+
for close in _weekly_closes(bar_times, int(timeframe)):
|
|
113
|
+
week = _week_close(close)
|
|
114
|
+
if week is None:
|
|
115
|
+
unexplained.append(close)
|
|
116
|
+
else:
|
|
117
|
+
weeks.append(week)
|
|
118
|
+
if len(weeks) < _MIN_WEEKS:
|
|
119
|
+
raise NotEnoughData(
|
|
120
|
+
f"found {len(weeks)} weekly close(s) that match a Friday ({len(unexplained)} more do not); "
|
|
121
|
+
f"need {_MIN_WEEKS}"
|
|
122
|
+
)
|
|
123
|
+
candidates, matched = _best_zones(weeks)
|
|
124
|
+
outliers = tuple(w for w in weeks if all(z.offset_at(w.friday_close_utc) != w.offset for z in candidates))
|
|
125
|
+
return Detection(
|
|
126
|
+
zone=candidates[0] if len(candidates) == 1 else None,
|
|
127
|
+
candidates=candidates,
|
|
128
|
+
weeks=tuple(weeks),
|
|
129
|
+
matched=matched,
|
|
130
|
+
total=len(weeks),
|
|
131
|
+
unexplained=tuple(unexplained),
|
|
132
|
+
outliers=outliers,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _weekly_closes(bar_times: Iterable[int], timeframe: int) -> list[int]:
|
|
137
|
+
"""Server close times of the bars followed by a weekend-sized gap."""
|
|
138
|
+
gap = int(_WEEKEND_GAP.total_seconds())
|
|
139
|
+
times = sorted({operator.index(t) for t in bar_times})
|
|
140
|
+
return [bar + timeframe for bar, following in pairwise(times) if following - (bar + timeframe) >= gap]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _week_close(server_close: int) -> WeekClose | None:
|
|
144
|
+
"""Match a server close to the Friday 17:00 New York that puts it within -12 h..+14 h, if there is one."""
|
|
145
|
+
wall = _EPOCH + timedelta(seconds=server_close)
|
|
146
|
+
# Within that range the server's date is the Friday itself or the Saturday after it.
|
|
147
|
+
for days_back in (0, 1):
|
|
148
|
+
day = wall.date() - timedelta(days=days_back)
|
|
149
|
+
if day.weekday() != _FRIDAY:
|
|
150
|
+
continue
|
|
151
|
+
friday = datetime.combine(day, _WEEKLY_CLOSE, tzinfo=_NEW_YORK).astimezone(timezone.utc)
|
|
152
|
+
offset = wall - friday.replace(tzinfo=None)
|
|
153
|
+
if _MIN_OFFSET <= offset <= _MAX_OFFSET:
|
|
154
|
+
return WeekClose(friday, server_close, _round_up_quarter(offset))
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _round_up_quarter(offset: timedelta) -> timedelta:
|
|
159
|
+
"""Round a measured weekly-close offset up to 15 minutes: brokers close at or before 17:00, never after."""
|
|
160
|
+
return _QUARTER_HOUR * math.ceil((offset - _LATE_SLACK) / _QUARTER_HOUR)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _best_zones(weeks: list[WeekClose]) -> tuple[tuple[ServerZone, ...], int]:
|
|
164
|
+
"""The clocks that predict the most weeks, and how many weeks that is."""
|
|
165
|
+
votes: Counter[ServerZone] = Counter()
|
|
166
|
+
for week in weeks:
|
|
167
|
+
for key, standard in _RULES.values():
|
|
168
|
+
tz = ZoneInfo(key)
|
|
169
|
+
daylight = tz.dst(week.friday_close_utc.astimezone(tz))
|
|
170
|
+
zone = _valid_zone(key, week.offset - daylight - standard)
|
|
171
|
+
if zone is not None:
|
|
172
|
+
votes[zone] += 1
|
|
173
|
+
best = max(votes.values())
|
|
174
|
+
return tuple(zone for zone, count in votes.items() if count == best), best
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _valid_zone(key: str, shift: timedelta) -> ServerZone | None:
|
|
178
|
+
try:
|
|
179
|
+
return ServerZone(key, shift)
|
|
180
|
+
except ValueError:
|
|
181
|
+
return None
|
brokerclock/_errors.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Exceptions raised by brokerclock. All of them are ``ValueError`` subclasses."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BrokerClockError(ValueError):
|
|
5
|
+
"""Base class of every brokerclock error."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AmbiguousTimeError(BrokerClockError):
|
|
9
|
+
"""A server wall time occurs twice (the hour repeated when daylight saving ends)."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NonexistentTimeError(BrokerClockError):
|
|
13
|
+
"""A server wall time never occurs (the hour skipped when daylight saving starts)."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NotEnoughData(BrokerClockError):
|
|
17
|
+
"""The bar history holds fewer than two weekly closes that can be matched to a Friday."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class StaleTickError(BrokerClockError):
|
|
21
|
+
"""A tick time is not a whole quarter hour away from the PC clock: the tick is old or the PC clock is off."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class OffsetOutOfRange(BrokerClockError):
|
|
25
|
+
"""A measured offset lies outside the possible UTC offsets, -12 h to +14 h."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ZoneMismatchError(BrokerClockError):
|
|
29
|
+
"""A live tick contradicts the server zone: the zone is wrong or the PC clock is behind."""
|
brokerclock/_live.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Measure or confirm the server clock from live tick times and the PC clock."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numbers
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from datetime import datetime, timedelta
|
|
9
|
+
|
|
10
|
+
from brokerclock._errors import NonexistentTimeError, OffsetOutOfRange, StaleTickError, ZoneMismatchError
|
|
11
|
+
from brokerclock._zone import _MAX_OFFSET, _MIN_OFFSET, _QUARTER_HOUR, ServerZone, _nearest_quarter, _require_aware
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def measure_offset(
|
|
15
|
+
server_times: Iterable[float], now: float | datetime | None = None, *, tolerance: float = 60
|
|
16
|
+
) -> timedelta:
|
|
17
|
+
"""Measure the server's current UTC offset from the freshest tick time.
|
|
18
|
+
|
|
19
|
+
``server_times`` are tick times in server epoch seconds (``tick.time``, or ``tick.time_msc / 1000``); the
|
|
20
|
+
largest is used. ``now`` is the current UTC time as epoch seconds or an aware datetime, and defaults to the PC
|
|
21
|
+
clock. The offset is ``freshest - now`` rounded to 15 minutes.
|
|
22
|
+
|
|
23
|
+
Raises ``OffsetOutOfRange`` when the offset is outside -12 h to +14 h, and ``StaleTickError`` when the
|
|
24
|
+
unrounded difference is more than ``tolerance`` seconds from the offset: the tick is not fresh, or the PC
|
|
25
|
+
clock is off by more than ``tolerance``.
|
|
26
|
+
|
|
27
|
+
A tick that is stale by close to a multiple of 15 minutes passes this test with a wrong offset, so measure
|
|
28
|
+
only while the symbols trade, or prefer :func:`check` against a zone found by :func:`detect`.
|
|
29
|
+
|
|
30
|
+
>>> measure_offset([1751382000], now=1751371200.6) # a tick from 0.6 s ago, 3 hours ahead of UTC
|
|
31
|
+
datetime.timedelta(seconds=10800)
|
|
32
|
+
"""
|
|
33
|
+
if isinstance(tolerance, bool) or not 0 <= tolerance < _QUARTER_HOUR.total_seconds() / 2:
|
|
34
|
+
raise ValueError(f"tolerance must be at least 0 and under 450 seconds, got {tolerance!r}")
|
|
35
|
+
raw = timedelta(seconds=float(_freshest(server_times)) - _now_seconds(now))
|
|
36
|
+
offset = _nearest_quarter(raw)
|
|
37
|
+
if not _MIN_OFFSET <= offset <= _MAX_OFFSET:
|
|
38
|
+
raise OffsetOutOfRange(
|
|
39
|
+
f"the freshest tick is {raw.total_seconds() / 3600:+.2f} h from the PC clock, outside -12 h to +14 h: "
|
|
40
|
+
"the tick is old (market closed?) or the PC clock is wrong"
|
|
41
|
+
)
|
|
42
|
+
residual = (raw - offset).total_seconds()
|
|
43
|
+
if abs(residual) > tolerance:
|
|
44
|
+
raise StaleTickError(
|
|
45
|
+
f"the freshest tick is {residual:+.1f} s off a whole quarter hour from the PC clock: "
|
|
46
|
+
f"either the tick is not fresh or the PC clock is off by more than {tolerance} s"
|
|
47
|
+
)
|
|
48
|
+
return offset
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check(
|
|
52
|
+
zone: ServerZone,
|
|
53
|
+
server_times: Iterable[float],
|
|
54
|
+
now: float | datetime | None = None,
|
|
55
|
+
*,
|
|
56
|
+
tolerance: float = 60,
|
|
57
|
+
max_age: float = 300,
|
|
58
|
+
) -> bool:
|
|
59
|
+
"""Check live tick times against ``zone``.
|
|
60
|
+
|
|
61
|
+
The age of the freshest tick is ``now`` minus its UTC time under ``zone``. ``server_times`` and ``now`` are as
|
|
62
|
+
in :func:`measure_offset`. Three outcomes:
|
|
63
|
+
|
|
64
|
+
* ``ZoneMismatchError`` when the tick is more than ``tolerance`` seconds in the future: the zone is behind
|
|
65
|
+
the real server clock, or the PC clock is behind.
|
|
66
|
+
* ``True`` when the tick is at most ``max_age`` seconds old: a fresh tick agrees with the zone.
|
|
67
|
+
* ``False`` when the tick is older: nothing can be confirmed, because the market is closed or quiet, or the
|
|
68
|
+
zone is ahead of the real one.
|
|
69
|
+
|
|
70
|
+
A tick in an hour the clock repeats is checked against both occurrences.
|
|
71
|
+
|
|
72
|
+
>>> from brokerclock import ServerZone
|
|
73
|
+
>>> check(ServerZone.us(), [1751382000], now=1751371200.6) # 2025-07-01 12:00 server is 09:00 UTC
|
|
74
|
+
True
|
|
75
|
+
"""
|
|
76
|
+
if tolerance < 0 or max_age < 0:
|
|
77
|
+
raise ValueError(f"tolerance and max_age must be at least 0, got {tolerance!r} and {max_age!r}")
|
|
78
|
+
freshest = _freshest(server_times)
|
|
79
|
+
try:
|
|
80
|
+
earlier = zone.to_utc(freshest, ambiguous="earlier")
|
|
81
|
+
except NonexistentTimeError as exc:
|
|
82
|
+
raise ZoneMismatchError(f"tick time {freshest} falls in an hour that {zone} skips") from exc
|
|
83
|
+
later = zone.to_utc(freshest, ambiguous="later")
|
|
84
|
+
current = _now_seconds(now)
|
|
85
|
+
if current - earlier.timestamp() < -tolerance:
|
|
86
|
+
raise ZoneMismatchError(
|
|
87
|
+
f"under {zone} the freshest tick is from {earlier:%Y-%m-%d %H:%M:%S} UTC, in the future: "
|
|
88
|
+
"the zone is behind the real server clock or the PC clock is behind"
|
|
89
|
+
)
|
|
90
|
+
return any(-tolerance <= current - tick.timestamp() <= max_age for tick in (earlier, later))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _freshest(server_times: Iterable[float]) -> float:
|
|
94
|
+
freshest = max(server_times, default=None)
|
|
95
|
+
if freshest is None:
|
|
96
|
+
raise ValueError("server_times is empty")
|
|
97
|
+
return freshest
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _now_seconds(now: float | datetime | None) -> float:
|
|
101
|
+
if now is None:
|
|
102
|
+
return time.time()
|
|
103
|
+
if isinstance(now, datetime):
|
|
104
|
+
_require_aware(now, "now")
|
|
105
|
+
return now.timestamp()
|
|
106
|
+
if isinstance(now, bool) or not isinstance(now, numbers.Real):
|
|
107
|
+
raise TypeError(f"now must be epoch seconds or an aware datetime, got {now!r}")
|
|
108
|
+
return float(now)
|
brokerclock/_zone.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""The broker's server clock: the wall clock of an IANA time zone plus a fixed shift."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime, timedelta, timezone
|
|
9
|
+
from functools import cache
|
|
10
|
+
from typing import Literal
|
|
11
|
+
from zoneinfo import ZoneInfo, available_timezones
|
|
12
|
+
|
|
13
|
+
from brokerclock._errors import AmbiguousTimeError, NonexistentTimeError
|
|
14
|
+
|
|
15
|
+
AmbiguousPolicy = Literal["raise", "earlier", "later"]
|
|
16
|
+
|
|
17
|
+
# MetaTrader epoch numbers count seconds from this moment on the server's own wall clock, so it has no time zone.
|
|
18
|
+
_EPOCH = datetime(1970, 1, 1) # noqa: DTZ001
|
|
19
|
+
_SECOND = timedelta(seconds=1)
|
|
20
|
+
_HOUR = timedelta(hours=1)
|
|
21
|
+
_QUARTER_HOUR = timedelta(minutes=15)
|
|
22
|
+
_MIN_OFFSET = timedelta(hours=-12)
|
|
23
|
+
_MAX_OFFSET = timedelta(hours=14)
|
|
24
|
+
_MAX_SHIFT_HOURS = 26
|
|
25
|
+
_AMBIGUOUS_POLICIES = ("raise", "earlier", "later")
|
|
26
|
+
|
|
27
|
+
# Daylight-saving rule -> (IANA zone that follows it, that zone's standard UTC offset).
|
|
28
|
+
_RULES: dict[str, tuple[str, timedelta]] = {
|
|
29
|
+
"US": ("America/New_York", timedelta(hours=-5)),
|
|
30
|
+
"EU": ("Europe/London", timedelta(0)),
|
|
31
|
+
"AU": ("Australia/Sydney", timedelta(hours=10)),
|
|
32
|
+
"fixed": ("UTC", timedelta(0)),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ServerZone:
|
|
38
|
+
"""A broker server clock: the wall clock of ``zone`` (an IANA key) plus ``shift``.
|
|
39
|
+
|
|
40
|
+
``shift`` is a multiple of 15 minutes, at most 26 hours either way, and the resulting UTC offset must lie
|
|
41
|
+
between -12 h and +14 h. The constructors cover the usual broker clocks:
|
|
42
|
+
|
|
43
|
+
>>> str(ServerZone.us())
|
|
44
|
+
'GMT+2/+3 (US daylight saving)'
|
|
45
|
+
>>> str(ServerZone.eu(1))
|
|
46
|
+
'GMT+1/+2 (EU daylight saving)'
|
|
47
|
+
>>> str(ServerZone.fixed(5.75))
|
|
48
|
+
'GMT+5:45 (fixed)'
|
|
49
|
+
>>> str(ServerZone("Europe/Athens"))
|
|
50
|
+
'Europe/Athens'
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
zone: str
|
|
54
|
+
shift: timedelta = timedelta(0)
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
if self.zone not in _iana_keys():
|
|
58
|
+
raise ValueError(f"unknown IANA time zone key: {self.zone!r}")
|
|
59
|
+
if not isinstance(self.shift, timedelta):
|
|
60
|
+
raise TypeError(f"shift must be a datetime.timedelta, got {type(self.shift).__name__}")
|
|
61
|
+
if self.shift % _QUARTER_HOUR or abs(self.shift) > _MAX_SHIFT_HOURS * _HOUR:
|
|
62
|
+
raise ValueError(f"shift must be a multiple of 15 minutes within 26 hours, got {self.shift!r}")
|
|
63
|
+
year = datetime.now(timezone.utc).year
|
|
64
|
+
for month in (1, 7):
|
|
65
|
+
offset = self.offset_at(datetime(year, month, 1, tzinfo=timezone.utc))
|
|
66
|
+
if not _MIN_OFFSET <= offset <= _MAX_OFFSET:
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"{self.zone} shifted by {self.shift!r} gives GMT{_format_offset(offset)}, outside -12 h to +14 h"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def us(cls, base_hours: float = 2) -> ServerZone:
|
|
73
|
+
"""New York wall clock plus ``base_hours + 5`` h: GMT+base in winter, GMT+base+1 in summer, US dates.
|
|
74
|
+
|
|
75
|
+
The default, GMT+2/+3, is the most common broker clock: its midnight is 17:00 in New York, when the
|
|
76
|
+
forex day rolls over.
|
|
77
|
+
"""
|
|
78
|
+
return cls._from_rule("US", base_hours)
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def eu(cls, base_hours: float = 2) -> ServerZone:
|
|
82
|
+
"""London wall clock plus ``base_hours``: GMT+base in winter, GMT+base+1 in summer, EU dates.
|
|
83
|
+
|
|
84
|
+
``eu()`` is GMT+2/+3 and ``eu(1)`` is GMT+1/+2, both switching on the last Sundays of March and October.
|
|
85
|
+
"""
|
|
86
|
+
return cls._from_rule("EU", base_hours)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def au(cls, base_hours: float = 2) -> ServerZone:
|
|
90
|
+
"""Sydney wall clock plus ``base_hours - 10`` h: GMT+base+1 from October to April, GMT+base otherwise."""
|
|
91
|
+
return cls._from_rule("AU", base_hours)
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def fixed(cls, hours: float) -> ServerZone:
|
|
95
|
+
"""A clock that never switches: UTC plus ``hours`` (0.25 steps, so ``fixed(5.75)`` is GMT+5:45)."""
|
|
96
|
+
return cls._from_rule("fixed", hours)
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def _from_rule(cls, rule: str, base_hours: float) -> ServerZone:
|
|
100
|
+
key, standard = _RULES[rule]
|
|
101
|
+
return cls(key, _hours(base_hours) - standard)
|
|
102
|
+
|
|
103
|
+
def __str__(self) -> str:
|
|
104
|
+
for rule, (key, standard) in _RULES.items():
|
|
105
|
+
if self.zone == key:
|
|
106
|
+
base = standard + self.shift
|
|
107
|
+
if rule == "fixed":
|
|
108
|
+
return f"GMT{_format_offset(base)} (fixed)"
|
|
109
|
+
return f"GMT{_format_offset(base)}/{_format_offset(base + _HOUR)} ({rule} daylight saving)"
|
|
110
|
+
return f"{self.zone} {_format_offset(self.shift)}" if self.shift else self.zone
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def _tz(self) -> ZoneInfo:
|
|
114
|
+
return ZoneInfo(self.zone)
|
|
115
|
+
|
|
116
|
+
def offset_at(self, instant: datetime) -> timedelta:
|
|
117
|
+
"""Return the server's UTC offset at an aware ``instant``.
|
|
118
|
+
|
|
119
|
+
>>> ServerZone.us().offset_at(datetime(2025, 3, 20, tzinfo=timezone.utc)) # US summer time, EU not yet
|
|
120
|
+
datetime.timedelta(seconds=10800)
|
|
121
|
+
>>> ServerZone.eu().offset_at(datetime(2025, 3, 20, tzinfo=timezone.utc))
|
|
122
|
+
datetime.timedelta(seconds=7200)
|
|
123
|
+
"""
|
|
124
|
+
_require_aware(instant, "instant")
|
|
125
|
+
return instant.astimezone(self._tz).utcoffset() + self.shift
|
|
126
|
+
|
|
127
|
+
def to_utc(self, server_time: float | datetime, *, ambiguous: AmbiguousPolicy = "raise") -> datetime:
|
|
128
|
+
"""Convert a server time to an aware UTC datetime.
|
|
129
|
+
|
|
130
|
+
``server_time`` is epoch seconds as MetaTrader returns them (``time``, or ``time_msc / 1000``), or a naive
|
|
131
|
+
datetime of server wall time. An aware datetime raises ``TypeError``, because it is unclear whether it was
|
|
132
|
+
already converted.
|
|
133
|
+
|
|
134
|
+
A wall time in the hour repeated when daylight saving ends is resolved by ``ambiguous``: ``"raise"`` raises
|
|
135
|
+
``AmbiguousTimeError``, ``"earlier"`` takes the first occurrence and ``"later"`` the second. A wall time in
|
|
136
|
+
the hour skipped when daylight saving starts raises ``NonexistentTimeError``.
|
|
137
|
+
|
|
138
|
+
>>> zone = ServerZone.us()
|
|
139
|
+
>>> zone.to_utc(1735693200) # 2025-01-01 01:00 on the server clock
|
|
140
|
+
datetime.datetime(2024, 12, 31, 23, 0, tzinfo=datetime.timezone.utc)
|
|
141
|
+
>>> zone.to_utc(datetime(2025, 7, 1, 12, 0))
|
|
142
|
+
datetime.datetime(2025, 7, 1, 9, 0, tzinfo=datetime.timezone.utc)
|
|
143
|
+
"""
|
|
144
|
+
if ambiguous not in _AMBIGUOUS_POLICIES:
|
|
145
|
+
raise ValueError(f"ambiguous must be one of {_AMBIGUOUS_POLICIES}, got {ambiguous!r}")
|
|
146
|
+
wall = _server_wall(server_time)
|
|
147
|
+
local = wall - self.shift
|
|
148
|
+
tz = self._tz
|
|
149
|
+
earlier = local.replace(tzinfo=tz, fold=0).astimezone(timezone.utc)
|
|
150
|
+
later = local.replace(tzinfo=tz, fold=1).astimezone(timezone.utc)
|
|
151
|
+
if earlier == later:
|
|
152
|
+
return earlier
|
|
153
|
+
if earlier.astimezone(tz).replace(tzinfo=None) != local:
|
|
154
|
+
raise NonexistentTimeError(f"server time {wall} falls in the hour that {self} skips")
|
|
155
|
+
if ambiguous == "raise":
|
|
156
|
+
raise AmbiguousTimeError(f"server time {wall} occurs twice in {self}; pass ambiguous='earlier' or 'later'")
|
|
157
|
+
return earlier if ambiguous == "earlier" else later
|
|
158
|
+
|
|
159
|
+
def to_server(self, instant: datetime) -> datetime:
|
|
160
|
+
"""Return the naive server wall time at an aware ``instant``.
|
|
161
|
+
|
|
162
|
+
>>> ServerZone.us().to_server(datetime(2025, 7, 1, 9, 0, tzinfo=timezone.utc))
|
|
163
|
+
datetime.datetime(2025, 7, 1, 12, 0)
|
|
164
|
+
"""
|
|
165
|
+
offset = self.offset_at(instant)
|
|
166
|
+
return instant.astimezone(timezone.utc).replace(tzinfo=None) + offset
|
|
167
|
+
|
|
168
|
+
def server_timestamp(self, instant: datetime) -> int:
|
|
169
|
+
"""Return the server-wall epoch seconds of an aware ``instant``, flooring any fraction of a second.
|
|
170
|
+
|
|
171
|
+
Pass these numbers to ``copy_rates_range``, ``copy_ticks_range`` and ``history_deals_get``, and as the
|
|
172
|
+
``expiration`` of an order: MetaTrader reads all of them as server wall time. An int also avoids the
|
|
173
|
+
terminal reading a naive datetime in the PC's local zone.
|
|
174
|
+
|
|
175
|
+
>>> ServerZone.us().server_timestamp(datetime(2025, 7, 1, 9, 0, 0, 999999, tzinfo=timezone.utc))
|
|
176
|
+
1751371200
|
|
177
|
+
"""
|
|
178
|
+
return (self.to_server(instant) - _EPOCH) // _SECOND
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@cache
|
|
182
|
+
def _iana_keys() -> frozenset[str]:
|
|
183
|
+
return frozenset(available_timezones())
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _hours(value: float) -> timedelta:
|
|
187
|
+
"""Turn a number of hours in 0.25 steps into a timedelta."""
|
|
188
|
+
valid = (
|
|
189
|
+
isinstance(value, (int, float))
|
|
190
|
+
and not isinstance(value, bool)
|
|
191
|
+
and math.isfinite(value)
|
|
192
|
+
and abs(value) <= _MAX_SHIFT_HOURS
|
|
193
|
+
and float(value * 4).is_integer()
|
|
194
|
+
)
|
|
195
|
+
if not valid:
|
|
196
|
+
raise ValueError(f"hours must be an int or float in 0.25 steps, got {value!r}")
|
|
197
|
+
return timedelta(minutes=round(value * 60))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _require_aware(value: object, name: str) -> None:
|
|
201
|
+
if not isinstance(value, datetime) or value.utcoffset() is None:
|
|
202
|
+
raise TypeError(f"{name} must be an aware datetime (with tzinfo), got {value!r}")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _server_wall(server_time: float | datetime) -> datetime:
|
|
206
|
+
"""Turn epoch seconds or a naive datetime of server wall time into a naive datetime."""
|
|
207
|
+
if isinstance(server_time, datetime):
|
|
208
|
+
if server_time.utcoffset() is not None:
|
|
209
|
+
raise TypeError("server_time must be naive server wall time or epoch seconds, not an aware datetime")
|
|
210
|
+
return server_time
|
|
211
|
+
if isinstance(server_time, bool) or not isinstance(server_time, numbers.Real):
|
|
212
|
+
raise TypeError(f"server_time must be epoch seconds or a naive datetime, got {server_time!r}")
|
|
213
|
+
if isinstance(server_time, numbers.Integral):
|
|
214
|
+
return _EPOCH + timedelta(seconds=int(server_time))
|
|
215
|
+
seconds = float(server_time)
|
|
216
|
+
if not math.isfinite(seconds):
|
|
217
|
+
raise ValueError(f"server_time must be finite, got {server_time!r}")
|
|
218
|
+
return _EPOCH + timedelta(seconds=seconds)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _nearest_quarter(offset: timedelta) -> timedelta:
|
|
222
|
+
"""Round to the nearest 15 minutes, halves up."""
|
|
223
|
+
return _QUARTER_HOUR * math.floor(offset / _QUARTER_HOUR + 0.5)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _format_offset(offset: timedelta) -> str:
|
|
227
|
+
"""Format an offset as +2, -3:30 or +5:45."""
|
|
228
|
+
minutes = offset // timedelta(minutes=1)
|
|
229
|
+
sign = "-" if minutes < 0 else "+"
|
|
230
|
+
hours, minutes = divmod(abs(minutes), 60)
|
|
231
|
+
return f"{sign}{hours}:{minutes:02d}" if minutes else f"{sign}{hours}"
|
brokerclock/pandas.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Vectorized conversions for whole pandas columns. Needs pandas: ``pip install "brokerclock[pandas]"``.
|
|
2
|
+
|
|
3
|
+
>>> import brokerclock.pandas as bcpd
|
|
4
|
+
>>> from brokerclock import ServerZone
|
|
5
|
+
>>> utc = bcpd.to_utc([1751371200, 1751374800], ServerZone.us()) # 12:00 and 13:00 on the server clock
|
|
6
|
+
>>> [str(t) for t in utc]
|
|
7
|
+
['2025-07-01 09:00:00+00:00', '2025-07-01 10:00:00+00:00']
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
from brokerclock._zone import _EPOCH, ServerZone
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import pandas as pd
|
|
18
|
+
except ImportError as exc:
|
|
19
|
+
raise ImportError('brokerclock.pandas needs pandas: pip install "brokerclock[pandas]"') from exc
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
import numpy as np
|
|
23
|
+
import numpy.typing as npt
|
|
24
|
+
|
|
25
|
+
Times = pd.Series | pd.DatetimeIndex
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_utc(
|
|
29
|
+
values: npt.ArrayLike,
|
|
30
|
+
zone: ServerZone,
|
|
31
|
+
*,
|
|
32
|
+
unit: str = "s",
|
|
33
|
+
ambiguous: str | npt.ArrayLike = "infer",
|
|
34
|
+
nonexistent: str = "raise",
|
|
35
|
+
) -> Times:
|
|
36
|
+
"""Convert server epoch numbers to aware UTC times.
|
|
37
|
+
|
|
38
|
+
``values`` is a Series, Index or array of server epoch numbers in ``unit`` (``"s"`` for ``time``, ``"ms"`` for
|
|
39
|
+
``time_msc``). A Series comes back as a Series with the same index; anything else as a DatetimeIndex.
|
|
40
|
+
|
|
41
|
+
``ambiguous`` and ``nonexistent`` are passed to pandas' ``tz_localize``. The default ``"infer"`` resolves the
|
|
42
|
+
repeated hour when the values are in time order, as bars and ticks are, and raises when it cannot (for example
|
|
43
|
+
a single value, or one merged H1 bar). A value in a skipped hour raises by default. Both errors are pandas'
|
|
44
|
+
own: ``ValueError`` in pandas 3, pytz's ``AmbiguousTimeError`` or ``NonExistentTimeError`` in pandas 2.
|
|
45
|
+
"""
|
|
46
|
+
times = pd.to_datetime(values, unit=unit) - zone.shift
|
|
47
|
+
local = _datetimes(times).tz_localize(zone.zone, ambiguous=ambiguous, nonexistent=nonexistent)
|
|
48
|
+
return _datetimes(local).tz_convert("UTC")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def frame_to_utc(
|
|
52
|
+
frame: pd.DataFrame | np.ndarray, zone: ServerZone, column: str = "time", **kwargs: Any
|
|
53
|
+
) -> pd.DataFrame:
|
|
54
|
+
"""Return a copy of ``frame`` with ``column`` converted by :func:`to_utc`.
|
|
55
|
+
|
|
56
|
+
``frame`` is a DataFrame or the structured array that ``copy_rates_*`` and ``copy_ticks_*`` return.
|
|
57
|
+
``kwargs`` go to :func:`to_utc`; for tick arrays pass ``column="time_msc", unit="ms"``.
|
|
58
|
+
"""
|
|
59
|
+
out = frame.copy() if isinstance(frame, pd.DataFrame) else pd.DataFrame(frame)
|
|
60
|
+
out[column] = to_utc(out[column], zone, **kwargs)
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def to_server_timestamps(index_or_series: Times, zone: ServerZone) -> npt.NDArray[np.int64]:
|
|
65
|
+
"""Convert aware times to server epoch seconds (int64, fractions of a second floored).
|
|
66
|
+
|
|
67
|
+
The inverse of :func:`to_utc`, for building query bounds or comparing with MetaTrader data.
|
|
68
|
+
"""
|
|
69
|
+
times = pd.DatetimeIndex(index_or_series)
|
|
70
|
+
if times.tz is None:
|
|
71
|
+
raise TypeError("to_server_timestamps needs aware times (for example UTC), got naive ones")
|
|
72
|
+
wall = times.tz_convert(zone.zone).tz_localize(None) + zone.shift
|
|
73
|
+
return ((wall - pd.Timestamp(_EPOCH)) // pd.Timedelta(seconds=1)).to_numpy(dtype="int64")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _datetimes(times: Times) -> Any:
|
|
77
|
+
"""The object that carries the datetime methods: ``.dt`` for a Series, the index itself otherwise."""
|
|
78
|
+
return times.dt if isinstance(times, pd.Series) else times
|
brokerclock/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: brokerclock
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MetaTrader broker server time to UTC and back, with daylight saving done right.
|
|
5
|
+
Project-URL: Homepage, https://github.com/raiez-alshamaly/brokerclock
|
|
6
|
+
Project-URL: Source, https://github.com/raiez-alshamaly/brokerclock
|
|
7
|
+
Project-URL: Issues, https://github.com/raiez-alshamaly/brokerclock/issues
|
|
8
|
+
Author-email: Raeez alshamaly <github@raeez-alshamaly.com>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: algorithmic trading,backtesting,broker,daylight saving,dst,forex,fx,gmt offset,metatrader,metatrader5,mt4,mt5,pandas,server time,time zone,timezone,trading,utc
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: tzdata; sys_platform == 'win32'
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: hypothesis>=6; extra == 'dev'
|
|
29
|
+
Requires-Dist: pandas>=2.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff==0.17.0; extra == 'dev'
|
|
32
|
+
Provides-Extra: pandas
|
|
33
|
+
Requires-Dist: pandas>=2.0; extra == 'pandas'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# brokerclock — MetaTrader broker server time to UTC (and back), with daylight saving done right
|
|
37
|
+
|
|
38
|
+
MetaTrader 5 does not give you UTC. The `time` and `time_msc` values that `copy_rates_*`, `copy_ticks_*`,
|
|
39
|
+
`history_deals_get` and `history_orders_get` return are the broker's **server clock written as epoch seconds**,
|
|
40
|
+
even though they look like Unix timestamps. If you searched for "MT5 server time UTC", "broker GMT offset" or
|
|
41
|
+
"copy_rates time zone", this is why your bars are two or three hours off.
|
|
42
|
+
|
|
43
|
+
- Most brokers run **GMT+2 in winter and GMT+3 in summer, switching with US daylight saving**: New York time plus
|
|
44
|
+
7 hours, so the forex day starts at server midnight, 17:00 in New York.
|
|
45
|
+
- A fixed offset breaks for weeks every year. `+3` is wrong all winter, and even a European daylight-saving rule is
|
|
46
|
+
wrong for about three weeks in March and one week around the start of November, when the US and Europe switch
|
|
47
|
+
on different dates.
|
|
48
|
+
- The server clock works in the other direction too: the date arguments of `copy_rates_range` and friends, and an
|
|
49
|
+
order's `expiration`, are read as server time.
|
|
50
|
+
|
|
51
|
+
brokerclock models the server clock as an IANA time zone plus a shift, so every conversion uses the rule in force at
|
|
52
|
+
that moment. It finds the rule from price history alone, confirms it against live ticks, and converts single values
|
|
53
|
+
or whole pandas columns. It needs only the standard library (plus `tzdata` on Windows) and never imports
|
|
54
|
+
`MetaTrader5`, so it runs and tests on any operating system.
|
|
55
|
+
|
|
56
|
+
## Install (after the first release)
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install brokerclock
|
|
60
|
+
pip install "brokerclock[pandas]" # with the pandas helpers
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Python 3.10 or newer.
|
|
64
|
+
|
|
65
|
+
## Quick start
|
|
66
|
+
|
|
67
|
+
### 1. Find the broker's clock from H1 EURUSD bars
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import MetaTrader5 as mt5
|
|
71
|
+
|
|
72
|
+
import brokerclock
|
|
73
|
+
|
|
74
|
+
mt5.initialize()
|
|
75
|
+
|
|
76
|
+
# About a year of H1 bars of a forex major.
|
|
77
|
+
rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_H1, 0, 6500)
|
|
78
|
+
result = brokerclock.detect(rates["time"], timeframe=3600)
|
|
79
|
+
print(result.zone) # GMT+2/+3 (US daylight saving)
|
|
80
|
+
print(f"{result.matched} of {result.total} weeks agree")
|
|
81
|
+
zone = result.zone
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
If `result.ambiguous` is true, the bars cannot separate the clocks in `result.candidates` (summer-only data, for
|
|
85
|
+
example): fetch a longer span. Running the same check on a second major is good practice. Once known, the clock is a
|
|
86
|
+
constant you can keep in your configuration, such as `brokerclock.ServerZone.us()`.
|
|
87
|
+
|
|
88
|
+
### 2. Convert bars to UTC
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import brokerclock.pandas as bcpd
|
|
92
|
+
|
|
93
|
+
bars = bcpd.frame_to_utc(rates, zone) # a DataFrame whose "time" column is aware UTC
|
|
94
|
+
print(bars[["time", "close"]].tail(3))
|
|
95
|
+
|
|
96
|
+
first_bar = zone.to_utc(rates["time"][0]) # one value, without pandas: an aware UTC datetime
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 3. Query by UTC and set an order expiration
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from datetime import datetime, timedelta, timezone
|
|
103
|
+
|
|
104
|
+
# Bars of March 2025 in UTC terms. Pass server-clock ints: a naive datetime would go through the PC's time zone.
|
|
105
|
+
start = datetime(2025, 3, 1, tzinfo=timezone.utc)
|
|
106
|
+
end = datetime(2025, 4, 1, tzinfo=timezone.utc)
|
|
107
|
+
march = mt5.copy_rates_range("EURUSD", mt5.TIMEFRAME_H1, zone.server_timestamp(start), zone.server_timestamp(end))
|
|
108
|
+
|
|
109
|
+
# A pending order that expires four hours from now.
|
|
110
|
+
expiry = datetime.now(timezone.utc) + timedelta(hours=4)
|
|
111
|
+
request = {
|
|
112
|
+
"action": mt5.TRADE_ACTION_PENDING,
|
|
113
|
+
"symbol": "EURUSD",
|
|
114
|
+
"volume": 0.1,
|
|
115
|
+
"type": mt5.ORDER_TYPE_BUY_LIMIT,
|
|
116
|
+
"price": 1.05,
|
|
117
|
+
"type_time": mt5.ORDER_TIME_SPECIFIED,
|
|
118
|
+
"expiration": zone.server_timestamp(expiry),
|
|
119
|
+
}
|
|
120
|
+
mt5.order_send(request)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### 4. Check the clock against live ticks
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
tick = mt5.symbol_info_tick("EURUSD")
|
|
127
|
+
if brokerclock.check(zone, [tick.time_msc / 1000]):
|
|
128
|
+
print("live ticks agree with", zone)
|
|
129
|
+
else:
|
|
130
|
+
print("no fresh tick to confirm it: the market is closed, or the zone is ahead of the server")
|
|
131
|
+
|
|
132
|
+
# Without a known zone: the current offset, while the market trades.
|
|
133
|
+
print(brokerclock.measure_offset([tick.time_msc / 1000])) # 3:00:00 in summer, 2:00:00 in winter
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`check` raises `ZoneMismatchError` when the tick would be from the future under that zone (the zone is behind the
|
|
137
|
+
server, or the PC clock is behind). `measure_offset` raises `StaleTickError` or `OffsetOutOfRange` instead of
|
|
138
|
+
guessing when the tick is not fresh.
|
|
139
|
+
|
|
140
|
+
## Broker clock conventions
|
|
141
|
+
|
|
142
|
+
| Server clock | Winter | Summer | Switch dates | `ServerZone` |
|
|
143
|
+
|---|---|---|---|---|
|
|
144
|
+
| New York close, the most common | GMT+2 | GMT+3 | US: second Sunday of March, first Sunday of November | `ServerZone.us()` |
|
|
145
|
+
| EU rule | GMT+2 | GMT+3 | EU: last Sundays of March and October | `ServerZone.eu()` |
|
|
146
|
+
| EU rule, central European | GMT+1 | GMT+2 | EU | `ServerZone.eu(1)` |
|
|
147
|
+
| Australian rule | GMT+2 (April to October) | GMT+3 (October to April) | AU: first Sundays of October and April | `ServerZone.au()` |
|
|
148
|
+
| Fixed GMT | GMT+0 | GMT+0 | none | `ServerZone.fixed(0)` |
|
|
149
|
+
| Fixed GMT+2 | GMT+2 | GMT+2 | none | `ServerZone.fixed(2)` |
|
|
150
|
+
| Any other clock | | | | `ServerZone.us(3)`, `ServerZone.fixed(5.75)`, `ServerZone("Asia/Tokyo")`, `ServerZone("Europe/Berlin", timedelta(hours=1))` |
|
|
151
|
+
|
|
152
|
+
A `ServerZone` is the wall clock of an IANA zone plus a shift in 15-minute steps; `str(zone)` describes it, for
|
|
153
|
+
example `GMT+2/+3 (US daylight saving)`.
|
|
154
|
+
|
|
155
|
+
## How detection works
|
|
156
|
+
|
|
157
|
+
1. A gap of 40 hours or more after a bar is a weekend; that bar's end is the weekly close on the server clock.
|
|
158
|
+
2. The forex week ends on Friday at 17:00 New York, so each close gives the server's offset that week. Brokers close
|
|
159
|
+
at or before 17:00, never after, so the offset is rounded up to the next 15 minutes.
|
|
160
|
+
3. Every candidate clock (fixed, or US, EU or Australian daylight saving, at any base offset) predicts each week.
|
|
161
|
+
4. The clock that predicts the most weeks wins; the weeks it misses are `outliers` (early holiday closes), and closes
|
|
162
|
+
that fit no Friday are `unexplained`.
|
|
163
|
+
5. A tie means the data cannot tell the clocks apart, and `zone` is `None`: use a longer span.
|
|
164
|
+
|
|
165
|
+
Detection needs a forex major and bars from M1 to H1 (`timeframe` 60 to 3600 seconds; longer bars are rejected
|
|
166
|
+
because they end on the server's own 4-hour or day boundaries and hide the switch weeks). Use M15 or shorter for
|
|
167
|
+
clocks with 30- or 45-minute offsets. The data should cover at least six months, or a span that includes March or
|
|
168
|
+
late October to early November.
|
|
169
|
+
|
|
170
|
+
## API
|
|
171
|
+
|
|
172
|
+
| Name | Purpose |
|
|
173
|
+
|---|---|
|
|
174
|
+
| `ServerZone(zone, shift)`, `.us()`, `.eu()`, `.au()`, `.fixed()` | the server clock |
|
|
175
|
+
| `zone.to_utc(server_time, ambiguous="raise")` | server epoch seconds or naive server datetime to aware UTC |
|
|
176
|
+
| `zone.server_timestamp(instant)`, `zone.to_server(instant)` | aware instant to server epoch int, or naive server datetime |
|
|
177
|
+
| `zone.offset_at(instant)` | the server's UTC offset at an aware instant |
|
|
178
|
+
| `detect(bar_times, timeframe=3600)` | the clock from M1 to H1 bar history, as a `Detection` |
|
|
179
|
+
| `measure_offset(server_times, now=None, tolerance=60)` | the current offset from a fresh tick and the PC clock |
|
|
180
|
+
| `check(zone, server_times, now=None, tolerance=60, max_age=300)` | whether live ticks agree with a zone |
|
|
181
|
+
| `brokerclock.pandas`: `to_utc`, `frame_to_utc`, `to_server_timestamps` | the same conversions for whole columns |
|
|
182
|
+
|
|
183
|
+
The library's own errors share the base class `BrokerClockError`, a `ValueError`: `AmbiguousTimeError`,
|
|
184
|
+
`NonexistentTimeError`, `NotEnoughData`, `StaleTickError`, `OffsetOutOfRange` and `ZoneMismatchError`. Invalid
|
|
185
|
+
arguments raise a plain `ValueError` or `TypeError`.
|
|
186
|
+
|
|
187
|
+
## Limitations
|
|
188
|
+
|
|
189
|
+
- When a broker switches the clock of 24/7 symbols (crypto CFDs) is broker-specific, so bars of those symbols right
|
|
190
|
+
at a switch can be an hour off.
|
|
191
|
+
- Metals and indices follow their own exchange hours; detect the clock from a forex major.
|
|
192
|
+
- Live measurement depends on the PC clock; keep automatic time sync on.
|
|
193
|
+
- A broker's demo and live servers can run different clocks; detect each one.
|
|
194
|
+
- A broker that changes its clock may rewrite its history in the new clock; detect again after a change.
|
|
195
|
+
- Weekly closes less than 14 minutes before 17:00 New York are handled (16:50 in M5 bars, 16:47 or later in M1
|
|
196
|
+
bars). If the last bar of a week ends 14 minutes or more early (16:40, say), that week reads 15 minutes off. A
|
|
197
|
+
few such weeks become `outliers`; if every week ends that way, the whole result is 15 minutes off, for example
|
|
198
|
+
GMT+1:45/+2:45 instead of GMT+2/+3. H1 bars avoid this, because the last H1 bar still ends at 17:00.
|
|
199
|
+
|
|
200
|
+
## Notes
|
|
201
|
+
|
|
202
|
+
Not affiliated with MetaQuotes. MetaTrader is a trademark of MetaQuotes Ltd.
|
|
203
|
+
|
|
204
|
+
Copyright 2026 Raeez alshamaly. Licensed under the Apache License, Version 2.0; see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
brokerclock/__init__.py,sha256=KHzdfk2fFG_M-KxiYA8dUXkjyoNCtebEaH3RoOsbjMI,1243
|
|
2
|
+
brokerclock/_detect.py,sha256=yP1wZNX0G5E8otdNjwJmP0K3ZUFamQSB4optDAqJPw4,8461
|
|
3
|
+
brokerclock/_errors.py,sha256=nFLMvmnShtPom5_nLqPVvp-T5CSYF9UlPYrd4O13Xag,1031
|
|
4
|
+
brokerclock/_live.py,sha256=M-rr6Agvi51QdnY8KCC-6KTgVmWcm86Ctj3Hyg6MoVY,5083
|
|
5
|
+
brokerclock/_zone.py,sha256=wjhS5iwZPYsFVhFC-cUSzxNamQhfddFXkkxBvOtgk40,10447
|
|
6
|
+
brokerclock/pandas.py,sha256=whwFw_AhBNaz-XW4GWUkacWKof1-16c3lvEACVQiTl0,3375
|
|
7
|
+
brokerclock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
brokerclock-0.1.0.dist-info/METADATA,sha256=1PuXtcEmQIkOPcBLPAgzfY2KacEwH-o_e7NNPk76DDQ,10275
|
|
9
|
+
brokerclock-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
10
|
+
brokerclock-0.1.0.dist-info/licenses/LICENSE,sha256=6N4ac5NFfpyIdot45rp5BiL777BAzkgZTCyw8bbU6f8,11562
|
|
11
|
+
brokerclock-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
https://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
https://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|