otcharts 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.
- otcharts-0.1.0/.github/workflows/ci.yml +36 -0
- otcharts-0.1.0/.github/workflows/release.yml +66 -0
- otcharts-0.1.0/.gitignore +8 -0
- otcharts-0.1.0/CHANGELOG.md +14 -0
- otcharts-0.1.0/LICENSE +21 -0
- otcharts-0.1.0/PKG-INFO +201 -0
- otcharts-0.1.0/README.md +155 -0
- otcharts-0.1.0/pyproject.toml +41 -0
- otcharts-0.1.0/src/otcharts/__init__.py +24 -0
- otcharts-0.1.0/src/otcharts/client.py +238 -0
- otcharts-0.1.0/src/otcharts/errors.py +77 -0
- otcharts-0.1.0/tests/test_client.py +168 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
# A client is only as trustworthy as its last green run, and the thing most
|
|
8
|
+
# likely to break it is a change at the other end rather than a commit here.
|
|
9
|
+
schedule:
|
|
10
|
+
- cron: "0 6 * * 1"
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
test:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
strategy:
|
|
16
|
+
fail-fast: false
|
|
17
|
+
matrix:
|
|
18
|
+
python: ["3.8", "3.10", "3.12", "3.13"]
|
|
19
|
+
steps:
|
|
20
|
+
- uses: actions/checkout@v4
|
|
21
|
+
- uses: actions/setup-python@v5
|
|
22
|
+
with:
|
|
23
|
+
python-version: ${{ matrix.python }}
|
|
24
|
+
- name: Run tests
|
|
25
|
+
run: PYTHONPATH=src python -m unittest discover -s tests -v
|
|
26
|
+
|
|
27
|
+
build:
|
|
28
|
+
runs-on: ubuntu-latest
|
|
29
|
+
steps:
|
|
30
|
+
- uses: actions/checkout@v4
|
|
31
|
+
- uses: actions/setup-python@v5
|
|
32
|
+
with:
|
|
33
|
+
python-version: "3.12"
|
|
34
|
+
- run: pip install build twine
|
|
35
|
+
- run: python -m build
|
|
36
|
+
- run: twine check dist/*
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
name: publish to PyPI
|
|
2
|
+
|
|
3
|
+
# Publishes on a GitHub Release, so cutting a release is the deliberate act and
|
|
4
|
+
# nothing reaches PyPI from an ordinary push.
|
|
5
|
+
on:
|
|
6
|
+
release:
|
|
7
|
+
types: [published]
|
|
8
|
+
workflow_dispatch: # lets a release be re-run by hand if PyPI hiccups
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
# Never publish something the tests have not passed. The push workflow already
|
|
12
|
+
# runs them, but a release can be cut from any commit, so they run again here
|
|
13
|
+
# against exactly the tree being shipped.
|
|
14
|
+
test:
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
strategy:
|
|
17
|
+
matrix:
|
|
18
|
+
python: ["3.8", "3.12", "3.13"]
|
|
19
|
+
steps:
|
|
20
|
+
- uses: actions/checkout@v4
|
|
21
|
+
- uses: actions/setup-python@v5
|
|
22
|
+
with:
|
|
23
|
+
python-version: ${{ matrix.python }}
|
|
24
|
+
- run: PYTHONPATH=src python -m unittest discover -s tests -v
|
|
25
|
+
|
|
26
|
+
build:
|
|
27
|
+
needs: test
|
|
28
|
+
runs-on: ubuntu-latest
|
|
29
|
+
steps:
|
|
30
|
+
- uses: actions/checkout@v4
|
|
31
|
+
- uses: actions/setup-python@v5
|
|
32
|
+
with:
|
|
33
|
+
python-version: "3.12"
|
|
34
|
+
- run: pip install build twine
|
|
35
|
+
- run: python -m build
|
|
36
|
+
- run: twine check dist/*
|
|
37
|
+
# The tag must match the version in pyproject.toml, or you publish 0.1.0
|
|
38
|
+
# from a tag that says v0.2.0 and nobody can tell which is which later.
|
|
39
|
+
- name: Tag must match the packaged version
|
|
40
|
+
if: github.event_name == 'release'
|
|
41
|
+
run: |
|
|
42
|
+
TAG="${GITHUB_REF_NAME#v}"
|
|
43
|
+
VER=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
|
|
44
|
+
echo "tag=$TAG packaged=$VER"
|
|
45
|
+
[ "$TAG" = "$VER" ] || { echo "::error::tag $TAG != version $VER"; exit 1; }
|
|
46
|
+
- uses: actions/upload-artifact@v4
|
|
47
|
+
with:
|
|
48
|
+
name: dist
|
|
49
|
+
path: dist/
|
|
50
|
+
|
|
51
|
+
publish:
|
|
52
|
+
needs: build
|
|
53
|
+
runs-on: ubuntu-latest
|
|
54
|
+
# Trusted Publishing: GitHub proves this workflow's identity to PyPI over
|
|
55
|
+
# OIDC and PyPI issues a short-lived token itself. No API token is created,
|
|
56
|
+
# stored, or pasted anywhere -- so there is no long-lived secret to leak,
|
|
57
|
+
# and nobody has to handle one.
|
|
58
|
+
environment: pypi
|
|
59
|
+
permissions:
|
|
60
|
+
id-token: write
|
|
61
|
+
steps:
|
|
62
|
+
- uses: actions/download-artifact@v4
|
|
63
|
+
with:
|
|
64
|
+
name: dist
|
|
65
|
+
path: dist/
|
|
66
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release. Reads `/v1/venues`, `/v1/candles` and `/v1/stream` from the OTCharts
|
|
6
|
+
data API across five books: Pocket Option, Quotex, IQ Option, BinoDex, and the real
|
|
7
|
+
institutional FX feed.
|
|
8
|
+
|
|
9
|
+
- No dependencies outside the standard library; `pandas` is an optional extra.
|
|
10
|
+
- One exception per refusal, including the distinction between `429` from your own
|
|
11
|
+
quota, `429` from your own concurrent-stream limit, and `503` from the service's
|
|
12
|
+
overall ceiling — three different problems that share two status codes.
|
|
13
|
+
- Selective stream reconnection: transport failures and `HouseBusy` are retried,
|
|
14
|
+
authentication and plan refusals are not.
|
otcharts-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OTCharts
|
|
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.
|
otcharts-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: otcharts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Market data from OTC broker books (Pocket Option, Quotex, IQ Option, BinoDex) and the real FX market, as JSON. No dependencies.
|
|
5
|
+
Project-URL: Homepage, https://otcharts.com
|
|
6
|
+
Project-URL: Documentation, https://otcharts.com/api.html
|
|
7
|
+
Project-URL: Source, https://github.com/otcharts/otcharts-python
|
|
8
|
+
Project-URL: Issues, https://github.com/otcharts/otcharts-python/issues
|
|
9
|
+
Author: OTCharts
|
|
10
|
+
License: MIT License
|
|
11
|
+
|
|
12
|
+
Copyright (c) 2026 OTCharts
|
|
13
|
+
|
|
14
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
15
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
16
|
+
in the Software without restriction, including without limitation the rights
|
|
17
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
18
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
19
|
+
furnished to do so, subject to the following conditions:
|
|
20
|
+
|
|
21
|
+
The above copyright notice and this permission notice shall be included in all
|
|
22
|
+
copies or substantial portions of the Software.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
25
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
26
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
27
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
28
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
|
+
SOFTWARE.
|
|
31
|
+
License-File: LICENSE
|
|
32
|
+
Keywords: binary options,binodex api,candles,forex,iq option api,market data,otc,pocket option api,quotex api,trading
|
|
33
|
+
Classifier: Development Status :: 4 - Beta
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
36
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
41
|
+
Classifier: Typing :: Typed
|
|
42
|
+
Requires-Python: >=3.8
|
|
43
|
+
Provides-Extra: pandas
|
|
44
|
+
Requires-Dist: pandas>=1.0; extra == 'pandas'
|
|
45
|
+
Description-Content-Type: text/markdown
|
|
46
|
+
|
|
47
|
+
# otcharts
|
|
48
|
+
|
|
49
|
+
Market data from OTC broker books — **Pocket Option, Quotex, IQ Option, BinoDex** —
|
|
50
|
+
and the real institutional FX market, as JSON. One dependency-free Python package.
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install otcharts
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from otcharts import Client
|
|
58
|
+
|
|
59
|
+
otc = Client() # reads OTCHARTS_API_KEY
|
|
60
|
+
bars = otc.candles("iq", "EURUSD-OTC", tf=60, limit=300)
|
|
61
|
+
print(bars[-1].close)
|
|
62
|
+
|
|
63
|
+
for tick in otc.stream("quotex", "EURUSD_otc"): # live, reconnects on drop
|
|
64
|
+
print(tick.time, tick.price)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Read this before you install
|
|
68
|
+
|
|
69
|
+
**This reads prices. It does not place trades.** No orders, no positions, no account
|
|
70
|
+
balance. If you came here looking for a way to automate trading on one of these
|
|
71
|
+
platforms, this is the wrong package and you should stop here rather than pay for it.
|
|
72
|
+
|
|
73
|
+
**You never give anyone your broker password.** Unlike the community wrappers, this
|
|
74
|
+
does not log in as you, drive a browser, or hold your broker session. It talks to an
|
|
75
|
+
HTTP API with a key that is yours, and the connection to the venue is held on the
|
|
76
|
+
server side.
|
|
77
|
+
|
|
78
|
+
**Not affiliated** with Pocket Option, Quotex, IQ Option, or BinoDex. Their names
|
|
79
|
+
appear here to say which price feed the data comes from, nothing more.
|
|
80
|
+
|
|
81
|
+
## Why this exists
|
|
82
|
+
|
|
83
|
+
None of these platforms publishes an official API. What exists is a handful of
|
|
84
|
+
community wrappers that log in with your credentials, drive Selenium past a CAPTCHA,
|
|
85
|
+
and break quietly when the platform changes its socket format. They are often good
|
|
86
|
+
work, and if you need to place orders they are the only route there is.
|
|
87
|
+
|
|
88
|
+
But if all you wanted was the prices, that is a lot of moving parts — and a lot of
|
|
89
|
+
risk to an account — to read a number. This package reads the number.
|
|
90
|
+
|
|
91
|
+
## Install
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
pip install otcharts # no dependencies
|
|
95
|
+
pip install 'otcharts[pandas]' # adds .dataframe()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Requires Python 3.8+. The package imports nothing outside the standard library, so it
|
|
99
|
+
cannot conflict with whatever you already have pinned.
|
|
100
|
+
|
|
101
|
+
## Getting a key
|
|
102
|
+
|
|
103
|
+
1. Buy a data plan at [otcharts.com/pricing](https://otcharts.com/pricing.html#api)
|
|
104
|
+
2. Create a key on your [account page](https://otcharts.com/account.html) — it is shown
|
|
105
|
+
once, and only a hash is stored, so nobody can recover it afterwards, including us
|
|
106
|
+
3. `export OTCHARTS_API_KEY=otc_live_...`
|
|
107
|
+
|
|
108
|
+
## The books, and their symbol formats
|
|
109
|
+
|
|
110
|
+
Ids are **not** portable between books. This catches everyone once:
|
|
111
|
+
|
|
112
|
+
| venue | book | a symbol looks like |
|
|
113
|
+
|---|---|---|
|
|
114
|
+
| `otc` | Pocket Option | `EURUSD_otc`, `#AAPL_otc` (equities take a `#`) |
|
|
115
|
+
| `quotex` | Quotex | `EURUSD_otc` |
|
|
116
|
+
| `iq` | IQ Option | `EURUSD-OTC` (hyphen, uppercase) |
|
|
117
|
+
| `binodex` | BinoDex | `EUR/USD-OTC` (slash), `TRX-OTC` |
|
|
118
|
+
| `forex` | Real market, institutional feed | `EURUSD` |
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
otc.venues() # every book, and whether your plan opens it
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Errors that tell you what to do
|
|
125
|
+
|
|
126
|
+
The API distinguishes its refusals, and so does this package. In particular
|
|
127
|
+
**`429` means two different things**, and they have different fixes:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from otcharts import QuotaExceeded, TooManyStreams, HouseBusy, PlanError
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
...
|
|
134
|
+
except QuotaExceeded: # 429 on a request — daily request quota spent
|
|
135
|
+
...
|
|
136
|
+
except TooManyStreams: # 429 on a stream — YOUR account's concurrent limit
|
|
137
|
+
... # close one of your streams
|
|
138
|
+
except HouseBusy as e: # 503 — the service as a whole is at its ceiling.
|
|
139
|
+
time.sleep(e.retry_after) # not your fault, not fixed by upgrading
|
|
140
|
+
except PlanError: # 402 — key is fine, plan does not open this book
|
|
141
|
+
...
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`AuthError` (401) is worth one note: a password reset revokes every API key on the
|
|
145
|
+
account, so a key that worked yesterday may simply have been revoked.
|
|
146
|
+
|
|
147
|
+
## Streaming
|
|
148
|
+
|
|
149
|
+
One symbol per stream, because one stream is one held connection to that book.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
for tick in otc.stream("otc", "EURUSD_otc"):
|
|
153
|
+
...
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Reconnection is on by default and is deliberately selective. Dropped sockets and
|
|
157
|
+
`HouseBusy` are retried — `HouseBusy` after the delay the server asks for. A revoked
|
|
158
|
+
key or a plan that does not open the book is **not** retried, because it will fail
|
|
159
|
+
identically forever and a client hammering a 402 in a loop is a client that gets
|
|
160
|
+
limited. Pass `reconnect=False` to handle it yourself.
|
|
161
|
+
|
|
162
|
+
## pandas
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
df = otc.dataframe("quotex", "EURUSD_otc", tf=60, limit=1000)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Optional on purpose — most callers want JSON, and a 60MB install to read five prices
|
|
169
|
+
is rude.
|
|
170
|
+
|
|
171
|
+
## One thing about this data
|
|
172
|
+
|
|
173
|
+
An instrument named after gold or EUR/USD on an OTC book is **the venue's own price**,
|
|
174
|
+
not the underlying market, and it can drift from it. That is how these books work. If
|
|
175
|
+
you are modelling this data, treat each series as its own thing rather than as a proxy
|
|
176
|
+
for the market it is named after — and note that `venue="forex"` carries the real
|
|
177
|
+
institutional feed, so the two can be compared directly.
|
|
178
|
+
|
|
179
|
+
## Development
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
git clone https://github.com/otcharts/otcharts-python
|
|
183
|
+
cd otcharts-python
|
|
184
|
+
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The tests run against a real HTTP server on loopback rather than a mocked transport,
|
|
188
|
+
so the headers, the status handling and the SSE parsing are genuinely exercised. No
|
|
189
|
+
test touches the network.
|
|
190
|
+
|
|
191
|
+
## Links
|
|
192
|
+
|
|
193
|
+
- [API reference](https://otcharts.com/api.html) — one page, the whole contract
|
|
194
|
+
- [Pocket Option API](https://otcharts.com/pocket-option-api.html) ·
|
|
195
|
+
[Quotex API](https://otcharts.com/quotex-api.html) ·
|
|
196
|
+
[IQ Option API](https://otcharts.com/iq-option-api.html) ·
|
|
197
|
+
[BinoDex API](https://otcharts.com/binodex-api.html)
|
|
198
|
+
|
|
199
|
+
## Licence
|
|
200
|
+
|
|
201
|
+
MIT. Nothing here is financial advice and no result is promised.
|
otcharts-0.1.0/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# otcharts
|
|
2
|
+
|
|
3
|
+
Market data from OTC broker books — **Pocket Option, Quotex, IQ Option, BinoDex** —
|
|
4
|
+
and the real institutional FX market, as JSON. One dependency-free Python package.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install otcharts
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from otcharts import Client
|
|
12
|
+
|
|
13
|
+
otc = Client() # reads OTCHARTS_API_KEY
|
|
14
|
+
bars = otc.candles("iq", "EURUSD-OTC", tf=60, limit=300)
|
|
15
|
+
print(bars[-1].close)
|
|
16
|
+
|
|
17
|
+
for tick in otc.stream("quotex", "EURUSD_otc"): # live, reconnects on drop
|
|
18
|
+
print(tick.time, tick.price)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Read this before you install
|
|
22
|
+
|
|
23
|
+
**This reads prices. It does not place trades.** No orders, no positions, no account
|
|
24
|
+
balance. If you came here looking for a way to automate trading on one of these
|
|
25
|
+
platforms, this is the wrong package and you should stop here rather than pay for it.
|
|
26
|
+
|
|
27
|
+
**You never give anyone your broker password.** Unlike the community wrappers, this
|
|
28
|
+
does not log in as you, drive a browser, or hold your broker session. It talks to an
|
|
29
|
+
HTTP API with a key that is yours, and the connection to the venue is held on the
|
|
30
|
+
server side.
|
|
31
|
+
|
|
32
|
+
**Not affiliated** with Pocket Option, Quotex, IQ Option, or BinoDex. Their names
|
|
33
|
+
appear here to say which price feed the data comes from, nothing more.
|
|
34
|
+
|
|
35
|
+
## Why this exists
|
|
36
|
+
|
|
37
|
+
None of these platforms publishes an official API. What exists is a handful of
|
|
38
|
+
community wrappers that log in with your credentials, drive Selenium past a CAPTCHA,
|
|
39
|
+
and break quietly when the platform changes its socket format. They are often good
|
|
40
|
+
work, and if you need to place orders they are the only route there is.
|
|
41
|
+
|
|
42
|
+
But if all you wanted was the prices, that is a lot of moving parts — and a lot of
|
|
43
|
+
risk to an account — to read a number. This package reads the number.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install otcharts # no dependencies
|
|
49
|
+
pip install 'otcharts[pandas]' # adds .dataframe()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Requires Python 3.8+. The package imports nothing outside the standard library, so it
|
|
53
|
+
cannot conflict with whatever you already have pinned.
|
|
54
|
+
|
|
55
|
+
## Getting a key
|
|
56
|
+
|
|
57
|
+
1. Buy a data plan at [otcharts.com/pricing](https://otcharts.com/pricing.html#api)
|
|
58
|
+
2. Create a key on your [account page](https://otcharts.com/account.html) — it is shown
|
|
59
|
+
once, and only a hash is stored, so nobody can recover it afterwards, including us
|
|
60
|
+
3. `export OTCHARTS_API_KEY=otc_live_...`
|
|
61
|
+
|
|
62
|
+
## The books, and their symbol formats
|
|
63
|
+
|
|
64
|
+
Ids are **not** portable between books. This catches everyone once:
|
|
65
|
+
|
|
66
|
+
| venue | book | a symbol looks like |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| `otc` | Pocket Option | `EURUSD_otc`, `#AAPL_otc` (equities take a `#`) |
|
|
69
|
+
| `quotex` | Quotex | `EURUSD_otc` |
|
|
70
|
+
| `iq` | IQ Option | `EURUSD-OTC` (hyphen, uppercase) |
|
|
71
|
+
| `binodex` | BinoDex | `EUR/USD-OTC` (slash), `TRX-OTC` |
|
|
72
|
+
| `forex` | Real market, institutional feed | `EURUSD` |
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
otc.venues() # every book, and whether your plan opens it
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Errors that tell you what to do
|
|
79
|
+
|
|
80
|
+
The API distinguishes its refusals, and so does this package. In particular
|
|
81
|
+
**`429` means two different things**, and they have different fixes:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from otcharts import QuotaExceeded, TooManyStreams, HouseBusy, PlanError
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
...
|
|
88
|
+
except QuotaExceeded: # 429 on a request — daily request quota spent
|
|
89
|
+
...
|
|
90
|
+
except TooManyStreams: # 429 on a stream — YOUR account's concurrent limit
|
|
91
|
+
... # close one of your streams
|
|
92
|
+
except HouseBusy as e: # 503 — the service as a whole is at its ceiling.
|
|
93
|
+
time.sleep(e.retry_after) # not your fault, not fixed by upgrading
|
|
94
|
+
except PlanError: # 402 — key is fine, plan does not open this book
|
|
95
|
+
...
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`AuthError` (401) is worth one note: a password reset revokes every API key on the
|
|
99
|
+
account, so a key that worked yesterday may simply have been revoked.
|
|
100
|
+
|
|
101
|
+
## Streaming
|
|
102
|
+
|
|
103
|
+
One symbol per stream, because one stream is one held connection to that book.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
for tick in otc.stream("otc", "EURUSD_otc"):
|
|
107
|
+
...
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Reconnection is on by default and is deliberately selective. Dropped sockets and
|
|
111
|
+
`HouseBusy` are retried — `HouseBusy` after the delay the server asks for. A revoked
|
|
112
|
+
key or a plan that does not open the book is **not** retried, because it will fail
|
|
113
|
+
identically forever and a client hammering a 402 in a loop is a client that gets
|
|
114
|
+
limited. Pass `reconnect=False` to handle it yourself.
|
|
115
|
+
|
|
116
|
+
## pandas
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
df = otc.dataframe("quotex", "EURUSD_otc", tf=60, limit=1000)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Optional on purpose — most callers want JSON, and a 60MB install to read five prices
|
|
123
|
+
is rude.
|
|
124
|
+
|
|
125
|
+
## One thing about this data
|
|
126
|
+
|
|
127
|
+
An instrument named after gold or EUR/USD on an OTC book is **the venue's own price**,
|
|
128
|
+
not the underlying market, and it can drift from it. That is how these books work. If
|
|
129
|
+
you are modelling this data, treat each series as its own thing rather than as a proxy
|
|
130
|
+
for the market it is named after — and note that `venue="forex"` carries the real
|
|
131
|
+
institutional feed, so the two can be compared directly.
|
|
132
|
+
|
|
133
|
+
## Development
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
git clone https://github.com/otcharts/otcharts-python
|
|
137
|
+
cd otcharts-python
|
|
138
|
+
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The tests run against a real HTTP server on loopback rather than a mocked transport,
|
|
142
|
+
so the headers, the status handling and the SSE parsing are genuinely exercised. No
|
|
143
|
+
test touches the network.
|
|
144
|
+
|
|
145
|
+
## Links
|
|
146
|
+
|
|
147
|
+
- [API reference](https://otcharts.com/api.html) — one page, the whole contract
|
|
148
|
+
- [Pocket Option API](https://otcharts.com/pocket-option-api.html) ·
|
|
149
|
+
[Quotex API](https://otcharts.com/quotex-api.html) ·
|
|
150
|
+
[IQ Option API](https://otcharts.com/iq-option-api.html) ·
|
|
151
|
+
[BinoDex API](https://otcharts.com/binodex-api.html)
|
|
152
|
+
|
|
153
|
+
## Licence
|
|
154
|
+
|
|
155
|
+
MIT. Nothing here is financial advice and no result is promised.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "otcharts"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Market data from OTC broker books (Pocket Option, Quotex, IQ Option, BinoDex) and the real FX market, as JSON. No dependencies."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
authors = [{ name = "OTCharts" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"pocket option api", "quotex api", "iq option api", "binodex api",
|
|
15
|
+
"binary options", "otc", "market data", "forex", "candles", "trading",
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.8",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Office/Business :: Financial",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
# Nothing. That is the point -- see the README.
|
|
29
|
+
dependencies = []
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
pandas = ["pandas>=1.0"]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://otcharts.com"
|
|
36
|
+
Documentation = "https://otcharts.com/api.html"
|
|
37
|
+
Source = "https://github.com/otcharts/otcharts-python"
|
|
38
|
+
Issues = "https://github.com/otcharts/otcharts-python/issues"
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["src/otcharts"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""OTCharts — market data from OTC broker books, as JSON.
|
|
2
|
+
|
|
3
|
+
pip install otcharts
|
|
4
|
+
|
|
5
|
+
from otcharts import Client
|
|
6
|
+
otc = Client() # reads OTCHARTS_API_KEY
|
|
7
|
+
bars = otc.candles("iq", "EURUSD-OTC", tf=60, limit=300)
|
|
8
|
+
|
|
9
|
+
Reads prices. Does not place trades, and never asks for broker credentials.
|
|
10
|
+
Not affiliated with any broker named in this package.
|
|
11
|
+
"""
|
|
12
|
+
from .client import Candle, Client, Tick, Venue
|
|
13
|
+
from .errors import (
|
|
14
|
+
AuthError, HouseBusy, NotFound, OTChartsError, PlanError,
|
|
15
|
+
QuotaExceeded, TooManyStreams, TransportError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
__all__ = [
|
|
20
|
+
"Client", "Candle", "Tick", "Venue",
|
|
21
|
+
"OTChartsError", "AuthError", "PlanError", "NotFound",
|
|
22
|
+
"QuotaExceeded", "TooManyStreams", "HouseBusy", "TransportError",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""A small client for the OTCharts data API.
|
|
2
|
+
|
|
3
|
+
Deliberately depends on nothing outside the standard library. The other clients
|
|
4
|
+
in this corner of the ecosystem pull in Selenium, a websocket stack and a
|
|
5
|
+
validation library before they read their first price, because they have to log
|
|
6
|
+
in as you and drive a real browser past a CAPTCHA. This one talks to an HTTP API
|
|
7
|
+
with a bearer token, which needs none of that -- so `pip install otcharts`
|
|
8
|
+
installs one package and cannot conflict with anything you already have.
|
|
9
|
+
|
|
10
|
+
from otcharts import Client
|
|
11
|
+
|
|
12
|
+
otc = Client() # reads OTCHARTS_API_KEY
|
|
13
|
+
bars = otc.candles("quotex", "EURUSD_otc", tf=60, limit=300)
|
|
14
|
+
for tick in otc.stream("quotex", "EURUSD_otc"):
|
|
15
|
+
print(tick.time, tick.price)
|
|
16
|
+
|
|
17
|
+
This reads market data. It does not place orders, hold positions, or touch a
|
|
18
|
+
broker account, and it never asks for broker credentials -- see the README.
|
|
19
|
+
"""
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import time
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.parse
|
|
25
|
+
import urllib.request
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
|
|
28
|
+
from .errors import (
|
|
29
|
+
AuthError, HouseBusy, NotFound, OTChartsError, PlanError,
|
|
30
|
+
QuotaExceeded, TooManyStreams, TransportError,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
__all__ = ["Client", "Candle", "Tick", "Venue"]
|
|
34
|
+
|
|
35
|
+
DEFAULT_BASE = "https://otcharts.com"
|
|
36
|
+
USER_AGENT = "otcharts-python/0.1.0 (+https://github.com/otcharts/otcharts-python)"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Candle:
|
|
41
|
+
"""One recorded bar. `time` is the bar's OPEN, in whole seconds UTC."""
|
|
42
|
+
time: int
|
|
43
|
+
open: float
|
|
44
|
+
high: float
|
|
45
|
+
low: float
|
|
46
|
+
close: float
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def _from(cls, d):
|
|
50
|
+
return cls(int(d["time"]), float(d["open"]), float(d["high"]),
|
|
51
|
+
float(d["low"]), float(d["close"]))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Tick:
|
|
56
|
+
"""One live price. `time` is whole seconds UTC."""
|
|
57
|
+
time: int
|
|
58
|
+
price: float
|
|
59
|
+
symbol: str = ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class Venue:
|
|
64
|
+
"""A book, and whether your plan opens it."""
|
|
65
|
+
id: str
|
|
66
|
+
open: bool
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Client:
|
|
70
|
+
"""Talks to the OTCharts data API.
|
|
71
|
+
|
|
72
|
+
The key is read from OTCHARTS_API_KEY when not passed, so it never has to
|
|
73
|
+
appear in the source of whatever you are building.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self, api_key=None, base_url=DEFAULT_BASE, timeout=30):
|
|
77
|
+
key = api_key or os.environ.get("OTCHARTS_API_KEY", "")
|
|
78
|
+
if not key:
|
|
79
|
+
raise AuthError(
|
|
80
|
+
"no API key: pass api_key= or set OTCHARTS_API_KEY. "
|
|
81
|
+
"Make one at https://otcharts.com/account.html")
|
|
82
|
+
self.api_key = key
|
|
83
|
+
self.base_url = base_url.rstrip("/")
|
|
84
|
+
self.timeout = timeout
|
|
85
|
+
|
|
86
|
+
# ── plumbing ───────────────────────────────────────────────────────────
|
|
87
|
+
def _request(self, path, params=None, stream=False):
|
|
88
|
+
url = self.base_url + path
|
|
89
|
+
if params:
|
|
90
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
91
|
+
req = urllib.request.Request(url, headers={
|
|
92
|
+
"Authorization": "Bearer " + self.api_key,
|
|
93
|
+
"User-Agent": USER_AGENT,
|
|
94
|
+
"Accept": "text/event-stream" if stream else "application/json",
|
|
95
|
+
})
|
|
96
|
+
try:
|
|
97
|
+
return urllib.request.urlopen(req, timeout=None if stream else self.timeout)
|
|
98
|
+
except urllib.error.HTTPError as e:
|
|
99
|
+
raise self._refusal(e, stream) from None
|
|
100
|
+
except (urllib.error.URLError, OSError) as e:
|
|
101
|
+
raise TransportError(f"could not reach {self.base_url}: {e}") from None
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _refusal(e, stream):
|
|
105
|
+
"""Turn an HTTP status into the exception that says what to DO."""
|
|
106
|
+
try:
|
|
107
|
+
body = e.read().decode("utf-8", "replace")
|
|
108
|
+
except Exception:
|
|
109
|
+
body = ""
|
|
110
|
+
try:
|
|
111
|
+
msg = json.loads(body).get("error") or body
|
|
112
|
+
except Exception:
|
|
113
|
+
msg = body
|
|
114
|
+
s = e.code
|
|
115
|
+
if s == 401:
|
|
116
|
+
return AuthError(msg or "key refused", s, body)
|
|
117
|
+
if s == 402:
|
|
118
|
+
return PlanError(msg or "your plan does not open this", s, body)
|
|
119
|
+
if s == 404:
|
|
120
|
+
return NotFound(msg or "no such venue or symbol", s, body)
|
|
121
|
+
if s == 429:
|
|
122
|
+
# Same status, two different problems. On a stream it means the
|
|
123
|
+
# account is at its own concurrent-stream limit; elsewhere it means
|
|
124
|
+
# the daily request quota is spent. Telling them apart is the whole
|
|
125
|
+
# reason this function exists.
|
|
126
|
+
cls = TooManyStreams if stream else QuotaExceeded
|
|
127
|
+
return cls(msg or "limit reached", s, body)
|
|
128
|
+
if s == 503:
|
|
129
|
+
try:
|
|
130
|
+
wait = int(e.headers.get("Retry-After") or 30)
|
|
131
|
+
except (TypeError, ValueError):
|
|
132
|
+
wait = 30
|
|
133
|
+
return HouseBusy(msg or "the service is at its stream ceiling",
|
|
134
|
+
s, body, retry_after=wait)
|
|
135
|
+
return OTChartsError(msg or f"HTTP {s}", s, body)
|
|
136
|
+
|
|
137
|
+
# ── endpoints ──────────────────────────────────────────────────────────
|
|
138
|
+
def venues(self):
|
|
139
|
+
"""Every book, and whether your plan opens it.
|
|
140
|
+
|
|
141
|
+
All five are always listed whatever you hold -- a short list could not
|
|
142
|
+
tell a plan limit from a missing feature.
|
|
143
|
+
"""
|
|
144
|
+
with self._request("/v1/venues") as r:
|
|
145
|
+
data = json.loads(r.read().decode())
|
|
146
|
+
return [Venue(v["id"], bool(v.get("open"))) for v in data.get("venues", [])]
|
|
147
|
+
|
|
148
|
+
def candles(self, venue, symbol, tf=60, limit=300):
|
|
149
|
+
"""Recorded bars from the venue's own history, oldest first.
|
|
150
|
+
|
|
151
|
+
tf is in seconds; limit is 1-5000.
|
|
152
|
+
"""
|
|
153
|
+
if not 1 <= limit <= 5000:
|
|
154
|
+
raise ValueError("limit must be between 1 and 5000")
|
|
155
|
+
with self._request("/v1/candles", {
|
|
156
|
+
"venue": venue, "symbol": symbol, "tf": tf, "limit": limit,
|
|
157
|
+
}) as r:
|
|
158
|
+
data = json.loads(r.read().decode())
|
|
159
|
+
return [Candle._from(c) for c in data.get("candles", [])]
|
|
160
|
+
|
|
161
|
+
def stream(self, venue, symbol, reconnect=True, max_backoff=60):
|
|
162
|
+
"""Live prices, as a generator that yields Tick.
|
|
163
|
+
|
|
164
|
+
One symbol per stream, because one stream is one held connection to that
|
|
165
|
+
book.
|
|
166
|
+
|
|
167
|
+
Reconnection is ON by default and deliberately does NOT retry
|
|
168
|
+
everything. A dropped socket is worth retrying; a revoked key or a plan
|
|
169
|
+
that does not open this book will fail identically forever, and a client
|
|
170
|
+
that hammers a 402 in a loop is a client that gets its account limited.
|
|
171
|
+
So only transport failures and HouseBusy are retried -- and HouseBusy is
|
|
172
|
+
retried after the delay the server asked for, not sooner.
|
|
173
|
+
"""
|
|
174
|
+
backoff = 1.0
|
|
175
|
+
while True:
|
|
176
|
+
try:
|
|
177
|
+
yield from self._stream_once(venue, symbol)
|
|
178
|
+
if not reconnect:
|
|
179
|
+
return
|
|
180
|
+
# A clean end of stream still means the feed stopped; pause
|
|
181
|
+
# briefly rather than spin reopening it.
|
|
182
|
+
time.sleep(min(backoff, max_backoff))
|
|
183
|
+
backoff = min(backoff * 2, max_backoff)
|
|
184
|
+
except HouseBusy as e:
|
|
185
|
+
if not reconnect:
|
|
186
|
+
raise
|
|
187
|
+
time.sleep(e.retry_after)
|
|
188
|
+
except TransportError:
|
|
189
|
+
if not reconnect:
|
|
190
|
+
raise
|
|
191
|
+
time.sleep(min(backoff, max_backoff))
|
|
192
|
+
backoff = min(backoff * 2, max_backoff)
|
|
193
|
+
|
|
194
|
+
def _stream_once(self, venue, symbol):
|
|
195
|
+
r = self._request("/v1/stream", {"venue": venue, "symbol": symbol},
|
|
196
|
+
stream=True)
|
|
197
|
+
try:
|
|
198
|
+
for raw in r:
|
|
199
|
+
line = raw.decode("utf-8", "replace").strip()
|
|
200
|
+
# Keepalive comments hold the connection open through proxies
|
|
201
|
+
# that kill idle streams; they carry no data.
|
|
202
|
+
if not line or line.startswith(":"):
|
|
203
|
+
continue
|
|
204
|
+
if not line.startswith("data:"):
|
|
205
|
+
continue
|
|
206
|
+
payload = line[5:].strip()
|
|
207
|
+
if not payload:
|
|
208
|
+
continue
|
|
209
|
+
try:
|
|
210
|
+
d = json.loads(payload)
|
|
211
|
+
except ValueError:
|
|
212
|
+
continue
|
|
213
|
+
price = d.get("price", d.get("close"))
|
|
214
|
+
if price is None:
|
|
215
|
+
continue
|
|
216
|
+
yield Tick(int(d.get("time", 0)), float(price),
|
|
217
|
+
str(d.get("symbol", symbol)))
|
|
218
|
+
finally:
|
|
219
|
+
r.close()
|
|
220
|
+
|
|
221
|
+
# ── convenience ────────────────────────────────────────────────────────
|
|
222
|
+
def dataframe(self, venue, symbol, tf=60, limit=300):
|
|
223
|
+
"""The same bars as a pandas DataFrame, indexed by UTC timestamp.
|
|
224
|
+
|
|
225
|
+
pandas is an optional extra rather than a dependency: most callers want
|
|
226
|
+
JSON, and forcing a 60MB install on them to read five prices is rude.
|
|
227
|
+
"""
|
|
228
|
+
try:
|
|
229
|
+
import pandas as pd
|
|
230
|
+
except ImportError:
|
|
231
|
+
raise OTChartsError(
|
|
232
|
+
"dataframe() needs pandas: pip install 'otcharts[pandas]'") from None
|
|
233
|
+
rows = self.candles(venue, symbol, tf=tf, limit=limit)
|
|
234
|
+
df = pd.DataFrame([vars(c) for c in rows])
|
|
235
|
+
if not df.empty:
|
|
236
|
+
df["time"] = pd.to_datetime(df["time"], unit="s", utc=True)
|
|
237
|
+
df = df.set_index("time")
|
|
238
|
+
return df
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""One exception per refusal the API can return.
|
|
2
|
+
|
|
3
|
+
The API distinguishes its refusals carefully -- a 402 is not a 401, and a 503
|
|
4
|
+
from the house being full is not a 429 from your own limit -- and a client that
|
|
5
|
+
collapses them all into one HTTPError throws that away. The caller who needs to
|
|
6
|
+
know whether to buy a bigger plan, wait thirty seconds, or fix their key cannot
|
|
7
|
+
tell from a status code they never see.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"OTChartsError", "AuthError", "PlanError", "NotFound",
|
|
12
|
+
"QuotaExceeded", "TooManyStreams", "HouseBusy", "TransportError",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OTChartsError(Exception):
|
|
17
|
+
"""Base for everything this package raises."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, message, status=None, body=None):
|
|
20
|
+
super().__init__(message)
|
|
21
|
+
self.status = status
|
|
22
|
+
self.body = body
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AuthError(OTChartsError):
|
|
26
|
+
"""401 -- the key is missing, malformed, revoked, or not a key at all.
|
|
27
|
+
|
|
28
|
+
Worth knowing: a password reset revokes every key on the account, so a key
|
|
29
|
+
that worked yesterday and 401s today may simply have been revoked by its
|
|
30
|
+
owner resetting their password.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PlanError(OTChartsError):
|
|
35
|
+
"""402 -- the key is good; the plan does not open what you asked for.
|
|
36
|
+
|
|
37
|
+
Either the account holds no data plan, or it holds one that does not open
|
|
38
|
+
this book. Said apart from AuthError on purpose: hunting for a bad key when
|
|
39
|
+
the key is fine wastes an afternoon.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NotFound(OTChartsError):
|
|
44
|
+
"""404 -- no such venue, or no such symbol on that venue.
|
|
45
|
+
|
|
46
|
+
Symbol ids are not portable between books. The same pair is EURUSD_otc on
|
|
47
|
+
Quotex and Pocket Option, EURUSD-OTC on IQ, and EUR/USD-OTC on BinoDex.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class QuotaExceeded(OTChartsError):
|
|
52
|
+
"""429 on a request -- the plan's daily request quota is spent."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TooManyStreams(OTChartsError):
|
|
56
|
+
"""429 on a stream -- this ACCOUNT already holds its maximum open streams.
|
|
57
|
+
|
|
58
|
+
Your own limit, so closing one of your streams fixes it. Distinct from
|
|
59
|
+
HouseBusy, which is not about you at all.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class HouseBusy(OTChartsError):
|
|
64
|
+
"""503 on a stream -- the service as a whole is at its stream ceiling.
|
|
65
|
+
|
|
66
|
+
Not your fault and not fixed by upgrading: every customer's streams share
|
|
67
|
+
the same venue sessions, and the total is capped to protect them. Carries
|
|
68
|
+
`retry_after` in seconds.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, message, status=None, body=None, retry_after=30):
|
|
72
|
+
super().__init__(message, status, body)
|
|
73
|
+
self.retry_after = retry_after
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TransportError(OTChartsError):
|
|
77
|
+
"""The request never got an answer -- DNS, TCP, TLS, or a dropped socket."""
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Tests against a real HTTP server on loopback, not a mocked urlopen.
|
|
2
|
+
|
|
3
|
+
Mocking the transport would test that the code calls the function it calls.
|
|
4
|
+
These start a stdlib server that answers the way the real API answers, so the
|
|
5
|
+
header, the status handling and the SSE parsing are all genuinely exercised --
|
|
6
|
+
and no test touches the network.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import threading
|
|
10
|
+
import unittest
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
12
|
+
|
|
13
|
+
import otcharts
|
|
14
|
+
from otcharts import (
|
|
15
|
+
AuthError, Client, HouseBusy, NotFound, PlanError,
|
|
16
|
+
QuotaExceeded, TooManyStreams,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
ROUTES = {} # path -> (status, headers, body)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Handler(BaseHTTPRequestHandler):
|
|
23
|
+
def do_GET(self):
|
|
24
|
+
path = self.path.split("?")[0]
|
|
25
|
+
if self.headers.get("Authorization") != "Bearer test-key":
|
|
26
|
+
self._send(401, {}, json.dumps({"error": "key refused"}))
|
|
27
|
+
return
|
|
28
|
+
status, headers, body = ROUTES.get(path, (404, {}, '{"error":"nope"}'))
|
|
29
|
+
self._send(status, headers, body)
|
|
30
|
+
|
|
31
|
+
def _send(self, status, headers, body):
|
|
32
|
+
raw = body.encode()
|
|
33
|
+
self.send_response(status)
|
|
34
|
+
for k, v in headers.items():
|
|
35
|
+
self.send_header(k, v)
|
|
36
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
37
|
+
self.end_headers()
|
|
38
|
+
self.wfile.write(raw)
|
|
39
|
+
|
|
40
|
+
def log_message(self, *a):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Base(unittest.TestCase):
|
|
45
|
+
@classmethod
|
|
46
|
+
def setUpClass(cls):
|
|
47
|
+
cls.srv = HTTPServer(("127.0.0.1", 0), Handler)
|
|
48
|
+
cls.port = cls.srv.server_address[1]
|
|
49
|
+
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def tearDownClass(cls):
|
|
53
|
+
cls.srv.shutdown()
|
|
54
|
+
|
|
55
|
+
def client(self, key="test-key"):
|
|
56
|
+
return Client(api_key=key, base_url=f"http://127.0.0.1:{self.port}",
|
|
57
|
+
timeout=5)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class TestReading(Base):
|
|
61
|
+
def test_candles_parse_in_order(self):
|
|
62
|
+
ROUTES["/v1/candles"] = (200, {}, json.dumps({"candles": [
|
|
63
|
+
{"time": 100, "open": 1.1, "high": 1.2, "low": 1.0, "close": 1.15},
|
|
64
|
+
{"time": 160, "open": 1.15, "high": 1.3, "low": 1.1, "close": 1.25},
|
|
65
|
+
]}))
|
|
66
|
+
bars = self.client().candles("quotex", "EURUSD_otc")
|
|
67
|
+
self.assertEqual(len(bars), 2)
|
|
68
|
+
self.assertEqual(bars[0].time, 100)
|
|
69
|
+
self.assertEqual(bars[1].close, 1.25)
|
|
70
|
+
self.assertLess(bars[0].time, bars[1].time, "oldest first")
|
|
71
|
+
|
|
72
|
+
def test_venues_lists_every_book(self):
|
|
73
|
+
ROUTES["/v1/venues"] = (200, {}, json.dumps({"venues": [
|
|
74
|
+
{"id": "otc", "open": False}, {"id": "quotex", "open": True},
|
|
75
|
+
]}))
|
|
76
|
+
vs = self.client().venues()
|
|
77
|
+
self.assertEqual([v.id for v in vs], ["otc", "quotex"])
|
|
78
|
+
self.assertFalse(vs[0].open)
|
|
79
|
+
self.assertTrue(vs[1].open)
|
|
80
|
+
|
|
81
|
+
def test_limit_is_checked_before_the_request(self):
|
|
82
|
+
for bad in (0, 5001, -1):
|
|
83
|
+
with self.assertRaises(ValueError):
|
|
84
|
+
self.client().candles("quotex", "EURUSD_otc", limit=bad)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TestRefusals(Base):
|
|
88
|
+
"""Each refusal must arrive as the exception that says what to DO."""
|
|
89
|
+
|
|
90
|
+
def test_bad_key_is_auth_error(self):
|
|
91
|
+
with self.assertRaises(AuthError):
|
|
92
|
+
self.client(key="wrong").venues()
|
|
93
|
+
|
|
94
|
+
def test_no_plan_is_plan_error_not_auth_error(self):
|
|
95
|
+
ROUTES["/v1/candles"] = (402, {}, json.dumps(
|
|
96
|
+
{"error": "this account has no data plan"}))
|
|
97
|
+
with self.assertRaises(PlanError):
|
|
98
|
+
self.client().candles("iq", "EURUSD-OTC")
|
|
99
|
+
|
|
100
|
+
def test_unknown_symbol_is_not_found(self):
|
|
101
|
+
ROUTES["/v1/candles"] = (404, {}, json.dumps({"error": "no such symbol"}))
|
|
102
|
+
with self.assertRaises(NotFound):
|
|
103
|
+
self.client().candles("iq", "NOPE")
|
|
104
|
+
|
|
105
|
+
def test_429_on_a_request_is_quota(self):
|
|
106
|
+
ROUTES["/v1/candles"] = (429, {}, json.dumps({"error": "daily quota spent"}))
|
|
107
|
+
with self.assertRaises(QuotaExceeded):
|
|
108
|
+
self.client().candles("quotex", "EURUSD_otc")
|
|
109
|
+
|
|
110
|
+
def test_429_on_a_stream_is_the_accounts_own_stream_limit(self):
|
|
111
|
+
"""Same status as the quota case, entirely different fix.
|
|
112
|
+
|
|
113
|
+
Collapsing these two into one exception would tell someone holding ten
|
|
114
|
+
streams that they had run out of daily requests.
|
|
115
|
+
"""
|
|
116
|
+
ROUTES["/v1/stream"] = (429, {}, json.dumps({"error": "too many streams"}))
|
|
117
|
+
gen = self.client().stream("quotex", "EURUSD_otc", reconnect=False)
|
|
118
|
+
with self.assertRaises(TooManyStreams):
|
|
119
|
+
next(gen)
|
|
120
|
+
|
|
121
|
+
def test_503_is_house_busy_and_carries_retry_after(self):
|
|
122
|
+
ROUTES["/v1/stream"] = (503, {"Retry-After": "45"},
|
|
123
|
+
json.dumps({"error": "house is full"}))
|
|
124
|
+
gen = self.client().stream("quotex", "EURUSD_otc", reconnect=False)
|
|
125
|
+
with self.assertRaises(HouseBusy) as cm:
|
|
126
|
+
next(gen)
|
|
127
|
+
self.assertEqual(cm.exception.retry_after, 45,
|
|
128
|
+
"must obey the server's delay, not a guess")
|
|
129
|
+
|
|
130
|
+
def test_a_missing_key_fails_before_any_request(self):
|
|
131
|
+
with self.assertRaises(AuthError):
|
|
132
|
+
Client(api_key="", base_url="http://127.0.0.1:1")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class TestStream(Base):
|
|
136
|
+
def test_sse_parsing_skips_keepalives_and_junk(self):
|
|
137
|
+
body = (
|
|
138
|
+
": keepalive\n" # comment, holds the connection
|
|
139
|
+
"\n" # blank separator
|
|
140
|
+
'data: {"time":100,"price":1.234}\n'
|
|
141
|
+
"event: ping\n" # a field we do not consume
|
|
142
|
+
'data: {"time":160,"price":1.235}\n'
|
|
143
|
+
"data: not json at all\n" # must not crash the generator
|
|
144
|
+
'data: {"time":220}\n' # no price, must be skipped
|
|
145
|
+
'data: {"time":280,"price":1.236}\n'
|
|
146
|
+
)
|
|
147
|
+
ROUTES["/v1/stream"] = (200, {"Content-Type": "text/event-stream"}, body)
|
|
148
|
+
ticks = list(self.client().stream("quotex", "EURUSD_otc", reconnect=False))
|
|
149
|
+
self.assertEqual([t.price for t in ticks], [1.234, 1.235, 1.236])
|
|
150
|
+
self.assertEqual(ticks[0].time, 100)
|
|
151
|
+
|
|
152
|
+
def test_reconnect_off_does_not_retry_a_plan_error(self):
|
|
153
|
+
"""A 402 will fail identically forever; retrying it is a loop."""
|
|
154
|
+
ROUTES["/v1/stream"] = (402, {}, json.dumps({"error": "no plan"}))
|
|
155
|
+
gen = self.client().stream("quotex", "EURUSD_otc", reconnect=True)
|
|
156
|
+
with self.assertRaises(PlanError):
|
|
157
|
+
next(gen) # raises even with reconnect ON, rather than spinning
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class TestPackage(unittest.TestCase):
|
|
161
|
+
def test_version_and_exports(self):
|
|
162
|
+
self.assertRegex(otcharts.__version__, r"^\d+\.\d+\.\d+$")
|
|
163
|
+
for name in ("Client", "Candle", "Tick", "AuthError", "HouseBusy"):
|
|
164
|
+
self.assertTrue(hasattr(otcharts, name), name)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
if __name__ == "__main__":
|
|
168
|
+
unittest.main(verbosity=2)
|