brokerclock 0.1.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,19 @@
1
+ ---
2
+ name: Bug report
3
+ about: A conversion or detection result that looks wrong
4
+ labels: bug
5
+ ---
6
+
7
+ **Broker server name** (optional):
8
+
9
+ **Offset you saw** (and the UTC date and time you saw it):
10
+
11
+ **Code** (a minimal example; include the bar or tick times if you can):
12
+
13
+ ```python
14
+
15
+ ```
16
+
17
+ **Expected:**
18
+
19
+ **Versions:** brokerclock, Python, pandas (if used), operating system
@@ -0,0 +1,31 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ test:
12
+ name: ${{ matrix.os }}, Python ${{ matrix.python-version }}
13
+ runs-on: ${{ matrix.os }}
14
+ strategy:
15
+ fail-fast: false
16
+ matrix:
17
+ os: [ubuntu-latest, windows-latest, macos-latest]
18
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
19
+ steps:
20
+ - uses: actions/checkout@v5
21
+ - uses: actions/setup-python@v6
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+ - name: Install
25
+ run: python -m pip install ".[dev]"
26
+ - name: Lint
27
+ run: |
28
+ python -m ruff check .
29
+ python -m ruff format --check .
30
+ - name: Test
31
+ run: python -m pytest -q
@@ -0,0 +1,65 @@
1
+ # This workflow will upload a Python Package to PyPI when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Release
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ release-build:
20
+ runs-on: ubuntu-latest
21
+
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - uses: actions/setup-python@v5
26
+ with:
27
+ python-version: "3.x"
28
+
29
+ - name: Build release distributions
30
+ run: |
31
+ python -m pip install build twine
32
+ python -m build
33
+ python -m twine check --strict dist/*
34
+
35
+ - name: Upload distributions
36
+ uses: actions/upload-artifact@v4
37
+ with:
38
+ name: release-dists
39
+ path: dist/
40
+
41
+ pypi-publish:
42
+ runs-on: ubuntu-latest
43
+ needs:
44
+ - release-build
45
+ permissions:
46
+ # IMPORTANT: this permission is mandatory for trusted publishing
47
+ id-token: write
48
+
49
+ # Dedicated environments with protections for publishing are strongly recommended.
50
+ # For more information, see: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-protection-rules
51
+ environment:
52
+ name: pypi
53
+ url: https://pypi.org/p/brokerclock
54
+
55
+ steps:
56
+ - name: Retrieve release distributions
57
+ uses: actions/download-artifact@v4
58
+ with:
59
+ name: release-dists
60
+ path: dist/
61
+
62
+ - name: Publish release distributions to PyPI
63
+ uses: pypa/gh-action-pypi-publish@release/v1
64
+ with:
65
+ packages-dir: dist/
@@ -0,0 +1,32 @@
1
+ # Byte-compiled files
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # Packaging
6
+ build/
7
+ dist/
8
+ *.egg-info/
9
+ .eggs/
10
+ wheels/
11
+
12
+ # Virtual environments
13
+ .venv/
14
+ venv/
15
+ env/
16
+
17
+ # Test and tool caches
18
+ .pytest_cache/
19
+ .hypothesis/
20
+ .ruff_cache/
21
+ .mypy_cache/
22
+ .coverage
23
+ .coverage.*
24
+ htmlcov/
25
+ .tox/
26
+ .nox/
27
+
28
+ # Editors and operating systems
29
+ .idea/
30
+ .vscode/
31
+ .DS_Store
32
+ Thumbs.db
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.1.0] - Unreleased
8
+
9
+ ### Added
10
+
11
+ - `ServerZone`: a broker server clock as an IANA time zone plus a shift in 15-minute steps, with the constructors
12
+ `us()`, `eu()`, `au()` and `fixed()`, and the conversions `offset_at()`, `to_utc()`, `to_server()` and
13
+ `server_timestamp()`. The repeated hour is resolved by an explicit `ambiguous` policy; the skipped hour raises.
14
+ - `detect()`: finds the server clock from M1 to H1 bar history alone, using the Friday 17:00 New York weekly
15
+ close, and reports the evidence: matched weeks, outliers, unexplained closes and tied candidates.
16
+ - `measure_offset()` and `check()`: measure the current offset from a fresh tick, or confirm a zone against live
17
+ ticks, refusing stale ticks instead of guessing.
18
+ - `brokerclock.pandas`: `to_utc()`, `frame_to_utc()` and `to_server_timestamps()` for whole columns and for the
19
+ arrays MetaTrader's `copy_rates_*` and `copy_ticks_*` return.
20
+ - Errors with the common base `BrokerClockError`.
21
+
22
+ [0.1.0]: https://github.com/raiez-alshamaly/brokerclock/releases/tag/v0.1.0
@@ -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.
@@ -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).