finclient 0.12.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.
- finclient-0.12.0/.gitignore +36 -0
- finclient-0.12.0/LICENSE +21 -0
- finclient-0.12.0/PKG-INFO +206 -0
- finclient-0.12.0/README.md +170 -0
- finclient-0.12.0/examples/fincopy_accounts.py +20 -0
- finclient-0.12.0/examples/fingraph_tickers.py +21 -0
- finclient-0.12.0/examples/finnews_feed.py +17 -0
- finclient-0.12.0/examples/finsocial_pulse.py +17 -0
- finclient-0.12.0/finclient/__init__.py +47 -0
- finclient-0.12.0/finclient/_encode.py +72 -0
- finclient-0.12.0/finclient/_errors.py +125 -0
- finclient-0.12.0/finclient/_generated/__init__.py +1 -0
- finclient-0.12.0/finclient/_generated/copy_types.py +1983 -0
- finclient-0.12.0/finclient/_generated/graph_ops.py +2393 -0
- finclient-0.12.0/finclient/_generated/graph_types.py +881 -0
- finclient-0.12.0/finclient/_generated/news_ops.py +816 -0
- finclient-0.12.0/finclient/_generated/news_types.py +323 -0
- finclient-0.12.0/finclient/_generated/social_ops.py +1239 -0
- finclient-0.12.0/finclient/_generated/social_types.py +416 -0
- finclient-0.12.0/finclient/_paging.py +104 -0
- finclient-0.12.0/finclient/_runtime.py +8 -0
- finclient-0.12.0/finclient/_service.py +269 -0
- finclient-0.12.0/finclient/_transport.py +135 -0
- finclient-0.12.0/finclient/_version.py +3 -0
- finclient-0.12.0/finclient/client.py +112 -0
- finclient-0.12.0/finclient/copy/__init__.py +39 -0
- finclient-0.12.0/finclient/copy/_common.py +87 -0
- finclient-0.12.0/finclient/copy/accounts.py +254 -0
- finclient-0.12.0/finclient/copy/changes.py +63 -0
- finclient-0.12.0/finclient/copy/fx.py +235 -0
- finclient-0.12.0/finclient/copy/orders.py +55 -0
- finclient-0.12.0/finclient/copy/sse.py +48 -0
- finclient-0.12.0/finclient/copy/webhooks.py +70 -0
- finclient-0.12.0/finclient/py.typed +0 -0
- finclient-0.12.0/pyproject.toml +77 -0
- finclient-0.12.0/tests/__init__.py +0 -0
- finclient-0.12.0/tests/conftest.py +97 -0
- finclient-0.12.0/tests/test_copy.py +206 -0
- finclient-0.12.0/tests/test_errors_retries.py +142 -0
- finclient-0.12.0/tests/test_paging.py +49 -0
- finclient-0.12.0/tests/test_routing.py +116 -0
- finclient-0.12.0/tests/test_transport_and_package.py +92 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# .NET
|
|
2
|
+
**/bin/
|
|
3
|
+
**/obj/
|
|
4
|
+
**/TestResults/
|
|
5
|
+
*.user
|
|
6
|
+
*.suo
|
|
7
|
+
.vs/
|
|
8
|
+
|
|
9
|
+
# Node
|
|
10
|
+
**/node_modules/
|
|
11
|
+
**/dist/
|
|
12
|
+
**/coverage/
|
|
13
|
+
artifacts/
|
|
14
|
+
|
|
15
|
+
# Local environment and secrets
|
|
16
|
+
.env
|
|
17
|
+
.env.*
|
|
18
|
+
!.env.example
|
|
19
|
+
*.local.json
|
|
20
|
+
|
|
21
|
+
# Copied from the root LICENSE when the npm package is packed
|
|
22
|
+
typescript/LICENSE
|
|
23
|
+
|
|
24
|
+
# Python
|
|
25
|
+
python/.venv/
|
|
26
|
+
python/dist/
|
|
27
|
+
python/build/
|
|
28
|
+
python/*.egg-info/
|
|
29
|
+
**/__pycache__/
|
|
30
|
+
**/*.pyc
|
|
31
|
+
.pytest_cache/
|
|
32
|
+
.mypy_cache/
|
|
33
|
+
.ruff_cache/
|
|
34
|
+
|
|
35
|
+
# Copied from the root LICENSE when the Python package is built
|
|
36
|
+
python/LICENSE
|
finclient-0.12.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BizJaya TechLab S/B
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: finclient
|
|
3
|
+
Version: 0.12.0
|
|
4
|
+
Summary: Official Python client for the FinCopy, FinGraph, FinNews and FinSocial APIs
|
|
5
|
+
Project-URL: Homepage, https://github.com/bizjaya/FinClient
|
|
6
|
+
Project-URL: Documentation, https://github.com/bizjaya/FinClient/tree/main/python#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/bizjaya/FinClient
|
|
8
|
+
Project-URL: Issues, https://github.com/bizjaya/FinClient/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/bizjaya/FinClient/blob/main/CHANGELOG.md
|
|
10
|
+
Author: BizJaya TechLab S/B
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: api-client,finclient,fincopy,fingraph,finnews,finsocial,market-data,trading
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build<2,>=1.2; extra == 'dev'
|
|
31
|
+
Requires-Dist: mypy<3,>=1.11; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest<10,>=8; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff<1,>=0.6; extra == 'dev'
|
|
34
|
+
Requires-Dist: twine<7,>=5; extra == 'dev'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# FinClient for Python
|
|
38
|
+
|
|
39
|
+
One typed Python client for four APIs: **FinCopy** (trading accounts and orders), **FinGraph** (markets, screens, tickers and
|
|
40
|
+
signals), **FinNews** (news, sentiment and videos) and **FinSocial** (social attention and prediction markets).
|
|
41
|
+
|
|
42
|
+
- Python 3.10 or newer. No runtime dependencies: HTTP uses the standard library.
|
|
43
|
+
- Fully typed (`py.typed`). Request and response shapes are `TypedDict`s generated from each service's OpenAPI document.
|
|
44
|
+
- Retries with backoff, `Retry-After`, one exception hierarchy, and iterators over pages.
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
pip install finclient
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Keys
|
|
51
|
+
|
|
52
|
+
Each service has its own key. Build the client with the keys you have; a part used without its key raises
|
|
53
|
+
`MissingApiKeyError` the first time you call it, before any request is sent.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import os
|
|
57
|
+
from finclient import FinClient, ServiceOptions
|
|
58
|
+
|
|
59
|
+
fin = FinClient(
|
|
60
|
+
api_key=os.environ["FINCOPY_API_KEY"], # FinCopy, sent as X-Api-Key
|
|
61
|
+
graph=ServiceOptions(api_key=os.environ["FINGRAPH_API_KEY"]), # FinGraph, sent as FinUsrKey
|
|
62
|
+
news=ServiceOptions(api_key=os.environ["FINNEWS_API_KEY"]), # FinNews, sent as FinUsrKey
|
|
63
|
+
social=ServiceOptions(api_key=os.environ["FINSOCIAL_API_KEY"]), # FinSocial, sent as FinUsrKey
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Keep keys in trusted server-side code and in the environment or a secret manager, never in source control.
|
|
68
|
+
|
|
69
|
+
| Part | Reached as | Default address | Key header |
|
|
70
|
+
|---|---|---|---|
|
|
71
|
+
| FinCopy | `fin.copy` | `https://api.fincopy.io` | `X-Api-Key` |
|
|
72
|
+
| FinGraph | `fin.graph` | `https://x.fingraph.io` | `FinUsrKey` |
|
|
73
|
+
| FinNews | `fin.news` | `https://x.finnews.io` | `FinUsrKey` |
|
|
74
|
+
| FinSocial | `fin.social` | `https://x.finsocial.io` | `FinUsrKey` |
|
|
75
|
+
|
|
76
|
+
`ServiceOptions` also takes `base_url`, `timeout` and `max_retries` for one part; `FinClient(timeout=30, max_retries=3)`
|
|
77
|
+
sets them for all. The top-level `api_key` and `base_url` are FinCopy's.
|
|
78
|
+
|
|
79
|
+
## FinCopy
|
|
80
|
+
|
|
81
|
+
The surface mirrors the TypeScript and .NET clients, in snake_case: `fin.copy.accounts`, `.orders`, `.fx`, `.changes` and
|
|
82
|
+
`.webhooks`. Fields keep the API's own names (`ACNO`, `SYM`, `LOT`, ...).
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
for account in fin.copy.accounts.list_items({"PageSize": 20}):
|
|
86
|
+
print(account["Fleet"]["Account"]["ACNO"])
|
|
87
|
+
|
|
88
|
+
# A trade call returns once the work is queued for the terminal; follow the stream, the change feed or a webhook.
|
|
89
|
+
fin.copy.orders.make(52014125, {"SYM": "EURUSD", "ACT": "NEW", "OTY": "OP_BUY", "LOT": 0.01})
|
|
90
|
+
|
|
91
|
+
for change in fin.copy.changes.read_all(): # follows the cursor
|
|
92
|
+
print(change)
|
|
93
|
+
for event in fin.copy.fx.stream(): # live events; reconnect in a loop when it ends
|
|
94
|
+
print(event.event, event.data)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Writes carry an `Idempotency-Key` (a fresh one, or pass `idempotency_key=`), so a retried write cannot apply twice.
|
|
98
|
+
|
|
99
|
+
### Webhooks
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from finclient import verify_signature
|
|
103
|
+
|
|
104
|
+
# `raw_body` is the exact request body; `headers` the request headers.
|
|
105
|
+
ok = verify_signature(secret, headers["X-FinCopy-Timestamp"], raw_body, headers["X-FinCopy-Signature"])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The signature is an HMAC-SHA256 over `<timestamp>.<body>`. A timestamp more than five minutes from now, in either
|
|
109
|
+
direction, is refused.
|
|
110
|
+
|
|
111
|
+
## FinGraph, FinNews and FinSocial: two surfaces
|
|
112
|
+
|
|
113
|
+
Every operation of these three services is reachable, in two kept-apart surfaces:
|
|
114
|
+
|
|
115
|
+
| Surface | Reached as | Billing |
|
|
116
|
+
|---|---|---|
|
|
117
|
+
| `/api/...` | `fin.graph.<group>.<operation>()` | Credits per call, on any plan. |
|
|
118
|
+
| `/v1/...` | `fin.graph.v1.<group>.<operation>()` | Included in paid plans and gated by package tier. A few are billed per call like `/api`; some currently need no key. |
|
|
119
|
+
|
|
120
|
+
`<group>` is the operation's tag in snake_case (`tickers`, `news`, `markets`) and `<operation>` the action in snake_case
|
|
121
|
+
(`List` is `list`, `EqtUsa` is `eqt_usa`). Each method's docstring says its route, its billing, and its
|
|
122
|
+
parameters, taken from the API description, so `help(fin.graph.v1.markets.eqt_usa)` is the reference.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
fin.graph.tickers.view("BTCUSDT") # GET /api/tickers/BTCUSDT (credits per call)
|
|
126
|
+
fin.graph.v1.tickers.list(exchange="BINANCE", size=50) # GET /v1/tickers?exchange=BINANCE&size=50
|
|
127
|
+
fin.graph.markets.eqt_usa(syms="NVDA,MSFT") # GET /api/markets/eqtusa?syms=NVDA%2CMSFT
|
|
128
|
+
fin.social.v1.pulse.pulse(syms="BTC,ETH", window="24h")
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Path parameters are positional and query parameters are keyword arguments in snake_case (`in_exchange=True` sends
|
|
132
|
+
`inExchange=true`). Every `/v1` operation needs a key.
|
|
133
|
+
|
|
134
|
+
### Filters and symbol lookups
|
|
135
|
+
|
|
136
|
+
Lists take plain query values: `page` (from 1), `size` (1 to 50), `sort` (a field name; a minus sign in front sorts high to
|
|
137
|
+
low) and the filters each endpoint lists. A symbol lookup takes `syms`, up to 50 names, comma-separated and in any case. A
|
|
138
|
+
list returns a `Page`: `items` are the rows, `paging` is the API's paging block and `not_found` holds the names no row carries.
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
page = fin.news.v1.news.list(syms="AAPL,MSFT", sort="-published", page=1, size=20)
|
|
142
|
+
page.items # the rows (iterating the page yields them too)
|
|
143
|
+
page.paging # {"pageNo": 1, "pageSize": 20, "pageCount": 7, "resCount": 131}
|
|
144
|
+
page.not_found # () when every name was found
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Paging
|
|
148
|
+
|
|
149
|
+
Every operation that pages has two iterators beside it: `<operation>_pages` and `<operation>_items`.
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
for page in fin.news.v1.news.list_pages(size=50, syms="AAPL"): # one Page per request
|
|
153
|
+
print(page.paging["pageNo"], len(page))
|
|
154
|
+
|
|
155
|
+
for article in fin.news.v1.news.list_items(size=50): # every row, page after page
|
|
156
|
+
print(article["Title"])
|
|
157
|
+
|
|
158
|
+
for stock in fin.graph.v1.markets.eqt_usa_items(sort="-vol24"):
|
|
159
|
+
print(stock["Sym"])
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The iterators advance `page` until the last page the paging block names (or an empty one). FinCopy lists have the same helpers:
|
|
163
|
+
`accounts.list_items()`, `fx.orders_pages()`, and so on. Every page is one billed call.
|
|
164
|
+
|
|
165
|
+
## Errors and retries
|
|
166
|
+
|
|
167
|
+
Every failure is a `FinApiError`:
|
|
168
|
+
|
|
169
|
+
| Exception | When |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `AuthenticationError` | 401, or `MissingApiKeyError` when no key was given |
|
|
172
|
+
| `InsufficientCreditsError` | 402 |
|
|
173
|
+
| `PermissionDeniedError` | 403 |
|
|
174
|
+
| `NotFoundError` | 404 |
|
|
175
|
+
| `RateLimitError` | 429 |
|
|
176
|
+
| `ServerError` | 5xx |
|
|
177
|
+
| `ApiConnectionError` | timeout or network failure (`error_code` is `timeout` or `network`) |
|
|
178
|
+
| `ApiResponseError` | an answer that is not a usable reply |
|
|
179
|
+
|
|
180
|
+
An error carries `status_code`, `code` (the API's own code such as `insufficient_credits`), `message`, `errors`, and, on limit
|
|
181
|
+
refusals, `lane`, `limit`, `catag` and `tier`. A `RateLimitError` has `retry_after` in seconds when the API said.
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from finclient import InsufficientCreditsError, RateLimitError
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
fin.graph.tickers.list()
|
|
188
|
+
except InsufficientCreditsError as error:
|
|
189
|
+
print(error.code, error.limit, error.tier)
|
|
190
|
+
except RateLimitError as error:
|
|
191
|
+
print("try again in", error.retry_after)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
A `429` is retried (waiting for `Retry-After` when it is 60 seconds or less), and so are `502`, `503` and `504`, up to
|
|
195
|
+
`max_retries` (default 3) with exponential backoff. A request that is not safe to repeat (a `POST` without an
|
|
196
|
+
idempotency key) is retried only on `429`, which the service refused before processing. Redirects are never followed, so
|
|
197
|
+
a key cannot be forwarded to another host.
|
|
198
|
+
|
|
199
|
+
## Your own transport
|
|
200
|
+
|
|
201
|
+
`FinClient(transport=...)` takes any object with `send(HttpRequest) -> HttpResponse` and
|
|
202
|
+
`stream(HttpRequest) -> StreamResponse`, for a proxy, extra headers, or tests.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT. Copyright BizJaya TechLab S/B.
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# FinClient for Python
|
|
2
|
+
|
|
3
|
+
One typed Python client for four APIs: **FinCopy** (trading accounts and orders), **FinGraph** (markets, screens, tickers and
|
|
4
|
+
signals), **FinNews** (news, sentiment and videos) and **FinSocial** (social attention and prediction markets).
|
|
5
|
+
|
|
6
|
+
- Python 3.10 or newer. No runtime dependencies: HTTP uses the standard library.
|
|
7
|
+
- Fully typed (`py.typed`). Request and response shapes are `TypedDict`s generated from each service's OpenAPI document.
|
|
8
|
+
- Retries with backoff, `Retry-After`, one exception hierarchy, and iterators over pages.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install finclient
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Keys
|
|
15
|
+
|
|
16
|
+
Each service has its own key. Build the client with the keys you have; a part used without its key raises
|
|
17
|
+
`MissingApiKeyError` the first time you call it, before any request is sent.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import os
|
|
21
|
+
from finclient import FinClient, ServiceOptions
|
|
22
|
+
|
|
23
|
+
fin = FinClient(
|
|
24
|
+
api_key=os.environ["FINCOPY_API_KEY"], # FinCopy, sent as X-Api-Key
|
|
25
|
+
graph=ServiceOptions(api_key=os.environ["FINGRAPH_API_KEY"]), # FinGraph, sent as FinUsrKey
|
|
26
|
+
news=ServiceOptions(api_key=os.environ["FINNEWS_API_KEY"]), # FinNews, sent as FinUsrKey
|
|
27
|
+
social=ServiceOptions(api_key=os.environ["FINSOCIAL_API_KEY"]), # FinSocial, sent as FinUsrKey
|
|
28
|
+
)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Keep keys in trusted server-side code and in the environment or a secret manager, never in source control.
|
|
32
|
+
|
|
33
|
+
| Part | Reached as | Default address | Key header |
|
|
34
|
+
|---|---|---|---|
|
|
35
|
+
| FinCopy | `fin.copy` | `https://api.fincopy.io` | `X-Api-Key` |
|
|
36
|
+
| FinGraph | `fin.graph` | `https://x.fingraph.io` | `FinUsrKey` |
|
|
37
|
+
| FinNews | `fin.news` | `https://x.finnews.io` | `FinUsrKey` |
|
|
38
|
+
| FinSocial | `fin.social` | `https://x.finsocial.io` | `FinUsrKey` |
|
|
39
|
+
|
|
40
|
+
`ServiceOptions` also takes `base_url`, `timeout` and `max_retries` for one part; `FinClient(timeout=30, max_retries=3)`
|
|
41
|
+
sets them for all. The top-level `api_key` and `base_url` are FinCopy's.
|
|
42
|
+
|
|
43
|
+
## FinCopy
|
|
44
|
+
|
|
45
|
+
The surface mirrors the TypeScript and .NET clients, in snake_case: `fin.copy.accounts`, `.orders`, `.fx`, `.changes` and
|
|
46
|
+
`.webhooks`. Fields keep the API's own names (`ACNO`, `SYM`, `LOT`, ...).
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
for account in fin.copy.accounts.list_items({"PageSize": 20}):
|
|
50
|
+
print(account["Fleet"]["Account"]["ACNO"])
|
|
51
|
+
|
|
52
|
+
# A trade call returns once the work is queued for the terminal; follow the stream, the change feed or a webhook.
|
|
53
|
+
fin.copy.orders.make(52014125, {"SYM": "EURUSD", "ACT": "NEW", "OTY": "OP_BUY", "LOT": 0.01})
|
|
54
|
+
|
|
55
|
+
for change in fin.copy.changes.read_all(): # follows the cursor
|
|
56
|
+
print(change)
|
|
57
|
+
for event in fin.copy.fx.stream(): # live events; reconnect in a loop when it ends
|
|
58
|
+
print(event.event, event.data)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Writes carry an `Idempotency-Key` (a fresh one, or pass `idempotency_key=`), so a retried write cannot apply twice.
|
|
62
|
+
|
|
63
|
+
### Webhooks
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from finclient import verify_signature
|
|
67
|
+
|
|
68
|
+
# `raw_body` is the exact request body; `headers` the request headers.
|
|
69
|
+
ok = verify_signature(secret, headers["X-FinCopy-Timestamp"], raw_body, headers["X-FinCopy-Signature"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The signature is an HMAC-SHA256 over `<timestamp>.<body>`. A timestamp more than five minutes from now, in either
|
|
73
|
+
direction, is refused.
|
|
74
|
+
|
|
75
|
+
## FinGraph, FinNews and FinSocial: two surfaces
|
|
76
|
+
|
|
77
|
+
Every operation of these three services is reachable, in two kept-apart surfaces:
|
|
78
|
+
|
|
79
|
+
| Surface | Reached as | Billing |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `/api/...` | `fin.graph.<group>.<operation>()` | Credits per call, on any plan. |
|
|
82
|
+
| `/v1/...` | `fin.graph.v1.<group>.<operation>()` | Included in paid plans and gated by package tier. A few are billed per call like `/api`; some currently need no key. |
|
|
83
|
+
|
|
84
|
+
`<group>` is the operation's tag in snake_case (`tickers`, `news`, `markets`) and `<operation>` the action in snake_case
|
|
85
|
+
(`List` is `list`, `EqtUsa` is `eqt_usa`). Each method's docstring says its route, its billing, and its
|
|
86
|
+
parameters, taken from the API description, so `help(fin.graph.v1.markets.eqt_usa)` is the reference.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
fin.graph.tickers.view("BTCUSDT") # GET /api/tickers/BTCUSDT (credits per call)
|
|
90
|
+
fin.graph.v1.tickers.list(exchange="BINANCE", size=50) # GET /v1/tickers?exchange=BINANCE&size=50
|
|
91
|
+
fin.graph.markets.eqt_usa(syms="NVDA,MSFT") # GET /api/markets/eqtusa?syms=NVDA%2CMSFT
|
|
92
|
+
fin.social.v1.pulse.pulse(syms="BTC,ETH", window="24h")
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Path parameters are positional and query parameters are keyword arguments in snake_case (`in_exchange=True` sends
|
|
96
|
+
`inExchange=true`). Every `/v1` operation needs a key.
|
|
97
|
+
|
|
98
|
+
### Filters and symbol lookups
|
|
99
|
+
|
|
100
|
+
Lists take plain query values: `page` (from 1), `size` (1 to 50), `sort` (a field name; a minus sign in front sorts high to
|
|
101
|
+
low) and the filters each endpoint lists. A symbol lookup takes `syms`, up to 50 names, comma-separated and in any case. A
|
|
102
|
+
list returns a `Page`: `items` are the rows, `paging` is the API's paging block and `not_found` holds the names no row carries.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
page = fin.news.v1.news.list(syms="AAPL,MSFT", sort="-published", page=1, size=20)
|
|
106
|
+
page.items # the rows (iterating the page yields them too)
|
|
107
|
+
page.paging # {"pageNo": 1, "pageSize": 20, "pageCount": 7, "resCount": 131}
|
|
108
|
+
page.not_found # () when every name was found
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Paging
|
|
112
|
+
|
|
113
|
+
Every operation that pages has two iterators beside it: `<operation>_pages` and `<operation>_items`.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
for page in fin.news.v1.news.list_pages(size=50, syms="AAPL"): # one Page per request
|
|
117
|
+
print(page.paging["pageNo"], len(page))
|
|
118
|
+
|
|
119
|
+
for article in fin.news.v1.news.list_items(size=50): # every row, page after page
|
|
120
|
+
print(article["Title"])
|
|
121
|
+
|
|
122
|
+
for stock in fin.graph.v1.markets.eqt_usa_items(sort="-vol24"):
|
|
123
|
+
print(stock["Sym"])
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The iterators advance `page` until the last page the paging block names (or an empty one). FinCopy lists have the same helpers:
|
|
127
|
+
`accounts.list_items()`, `fx.orders_pages()`, and so on. Every page is one billed call.
|
|
128
|
+
|
|
129
|
+
## Errors and retries
|
|
130
|
+
|
|
131
|
+
Every failure is a `FinApiError`:
|
|
132
|
+
|
|
133
|
+
| Exception | When |
|
|
134
|
+
|---|---|
|
|
135
|
+
| `AuthenticationError` | 401, or `MissingApiKeyError` when no key was given |
|
|
136
|
+
| `InsufficientCreditsError` | 402 |
|
|
137
|
+
| `PermissionDeniedError` | 403 |
|
|
138
|
+
| `NotFoundError` | 404 |
|
|
139
|
+
| `RateLimitError` | 429 |
|
|
140
|
+
| `ServerError` | 5xx |
|
|
141
|
+
| `ApiConnectionError` | timeout or network failure (`error_code` is `timeout` or `network`) |
|
|
142
|
+
| `ApiResponseError` | an answer that is not a usable reply |
|
|
143
|
+
|
|
144
|
+
An error carries `status_code`, `code` (the API's own code such as `insufficient_credits`), `message`, `errors`, and, on limit
|
|
145
|
+
refusals, `lane`, `limit`, `catag` and `tier`. A `RateLimitError` has `retry_after` in seconds when the API said.
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
from finclient import InsufficientCreditsError, RateLimitError
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
fin.graph.tickers.list()
|
|
152
|
+
except InsufficientCreditsError as error:
|
|
153
|
+
print(error.code, error.limit, error.tier)
|
|
154
|
+
except RateLimitError as error:
|
|
155
|
+
print("try again in", error.retry_after)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
A `429` is retried (waiting for `Retry-After` when it is 60 seconds or less), and so are `502`, `503` and `504`, up to
|
|
159
|
+
`max_retries` (default 3) with exponential backoff. A request that is not safe to repeat (a `POST` without an
|
|
160
|
+
idempotency key) is retried only on `429`, which the service refused before processing. Redirects are never followed, so
|
|
161
|
+
a key cannot be forwarded to another host.
|
|
162
|
+
|
|
163
|
+
## Your own transport
|
|
164
|
+
|
|
165
|
+
`FinClient(transport=...)` takes any object with `send(HttpRequest) -> HttpResponse` and
|
|
166
|
+
`stream(HttpRequest) -> StreamResponse`, for a proxy, extra headers, or tests.
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
MIT. Copyright BizJaya TechLab S/B.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""List your FinCopy accounts and their open orders. Needs FINCOPY_API_KEY in the environment."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from finclient import FinClient, InsufficientCreditsError, RateLimitError
|
|
5
|
+
|
|
6
|
+
fin = FinClient(api_key=os.environ["FINCOPY_API_KEY"])
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
for account in fin.copy.accounts.list_items({"PageSize": 20}):
|
|
10
|
+
fleet = (account.get("Fleet") or {}).get("Account") or {}
|
|
11
|
+
print(fleet.get("ACNO"), fleet.get("Login"))
|
|
12
|
+
for order in fin.copy.fx.orders_items({"PageSize": 50}):
|
|
13
|
+
print("open order", order.get("OID"), order.get("SYM"))
|
|
14
|
+
except RateLimitError as error:
|
|
15
|
+
print(f"Rate limited; retry in {error.retry_after} seconds.")
|
|
16
|
+
except InsufficientCreditsError as error:
|
|
17
|
+
print(f"Out of credits: {error.message}")
|
|
18
|
+
|
|
19
|
+
# Queue a trade. A successful call means the work is queued for the terminal, not that it has filled.
|
|
20
|
+
# fin.copy.orders.make(52014125, {"SYM": "EURUSD", "ACT": "NEW", "OTY": "OP_BUY", "LOT": 0.01})
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Read FinGraph markets and tickers. Needs FINGRAPH_API_KEY in the environment."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from finclient import FinClient, ServiceOptions
|
|
5
|
+
|
|
6
|
+
fin = FinClient(graph=ServiceOptions(api_key=os.environ["FINGRAPH_API_KEY"]))
|
|
7
|
+
|
|
8
|
+
# /v1: included in paid plans. US stocks by name, up to 50 symbols; a minus sign sorts high to low.
|
|
9
|
+
stocks = fin.graph.v1.markets.eqt_usa(syms="NVDA,MSFT,BCDA", sort="-chg1d")
|
|
10
|
+
for stock in stocks:
|
|
11
|
+
print(stock["Sym"], stock["Price"], stock["Signal"])
|
|
12
|
+
print("Not found:", stocks.not_found) # names that no row carries
|
|
13
|
+
|
|
14
|
+
# Lists page with page and size; tickers_items follows the pages for you.
|
|
15
|
+
for index, ticker in enumerate(fin.graph.v1.tickers.list_items(exchange="BINANCE", quote="USDT", size=50)):
|
|
16
|
+
print(ticker)
|
|
17
|
+
if index >= 4:
|
|
18
|
+
break
|
|
19
|
+
|
|
20
|
+
# /api: billed in credits per call, on any plan. Path parameters are positional.
|
|
21
|
+
print(fin.graph.tickers.view("BTCUSDT"))
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Read the FinNews feed with filters, then page through it. Needs FINNEWS_API_KEY in the environment."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from finclient import FinClient, ServiceOptions
|
|
5
|
+
|
|
6
|
+
fin = FinClient(news=ServiceOptions(api_key=os.environ["FINNEWS_API_KEY"]))
|
|
7
|
+
|
|
8
|
+
# Plain keyword arguments: symbols, a sort (a minus sign sorts high to low), and the page to read.
|
|
9
|
+
page = fin.news.v1.news.list(syms="AAPL,MSFT", sort="-published", page=1, size=10)
|
|
10
|
+
print(page.paging)
|
|
11
|
+
for article in page:
|
|
12
|
+
print(article.get("Title"))
|
|
13
|
+
|
|
14
|
+
# Every article that matches, page after page.
|
|
15
|
+
for article in fin.news.v1.news.list_items(syms="AAPL", size=50):
|
|
16
|
+
print(article.get("Title"))
|
|
17
|
+
break
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Read what is being said about a few symbols, then the prediction markets. Needs FINSOCIAL_API_KEY."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from finclient import FinClient, ServiceOptions
|
|
5
|
+
|
|
6
|
+
fin = FinClient(social=ServiceOptions(api_key=os.environ["FINSOCIAL_API_KEY"]))
|
|
7
|
+
|
|
8
|
+
# The pulse: mentions, engagement and the bullish and bearish split, for up to 50 symbols by name.
|
|
9
|
+
pulse = fin.social.pulse.pulse(syms="BTC,ETH")
|
|
10
|
+
for row in pulse:
|
|
11
|
+
print(row["Sym"], row["Mentions"], row["Bullish"], row["Bearish"])
|
|
12
|
+
print("Not found:", pulse.not_found) # names that no row carries
|
|
13
|
+
|
|
14
|
+
# /v1: included in paid plans. Every prediction market, a page at a time; markets_items follows the pages for you.
|
|
15
|
+
for market in fin.social.v1.markets.markets_items(size=25):
|
|
16
|
+
print(market)
|
|
17
|
+
break
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""FinClient: one client for the FinCopy, FinGraph, FinNews and FinSocial APIs."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ._errors import (
|
|
5
|
+
ApiConnectionError,
|
|
6
|
+
ApiResponseError,
|
|
7
|
+
AuthenticationError,
|
|
8
|
+
FinApiError,
|
|
9
|
+
InsufficientCreditsError,
|
|
10
|
+
MissingApiKeyError,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
PermissionDeniedError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
ServerError,
|
|
15
|
+
)
|
|
16
|
+
from ._paging import Page, PageInfo
|
|
17
|
+
from ._transport import HttpRequest, HttpResponse, StreamResponse, Transport, TransportError, UrllibTransport
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
from .client import FinClient, ServiceOptions
|
|
20
|
+
from .copy import FinWebhook, StreamEvent, verify_signature
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"ApiConnectionError",
|
|
24
|
+
"ApiResponseError",
|
|
25
|
+
"AuthenticationError",
|
|
26
|
+
"FinApiError",
|
|
27
|
+
"FinClient",
|
|
28
|
+
"FinWebhook",
|
|
29
|
+
"HttpRequest",
|
|
30
|
+
"HttpResponse",
|
|
31
|
+
"InsufficientCreditsError",
|
|
32
|
+
"MissingApiKeyError",
|
|
33
|
+
"NotFoundError",
|
|
34
|
+
"Page",
|
|
35
|
+
"PageInfo",
|
|
36
|
+
"PermissionDeniedError",
|
|
37
|
+
"RateLimitError",
|
|
38
|
+
"ServerError",
|
|
39
|
+
"ServiceOptions",
|
|
40
|
+
"StreamEvent",
|
|
41
|
+
"StreamResponse",
|
|
42
|
+
"Transport",
|
|
43
|
+
"TransportError",
|
|
44
|
+
"UrllibTransport",
|
|
45
|
+
"__version__",
|
|
46
|
+
"verify_signature",
|
|
47
|
+
]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Encoding of paths, query strings and request bodies."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from datetime import date, datetime
|
|
7
|
+
from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
__all__ = ["drop_none", "encode_query", "seg", "snake"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def snake(name: str) -> str:
|
|
14
|
+
"""``pageNo`` -> ``page_no``, ``MaxPerKey`` -> ``max_per_key``."""
|
|
15
|
+
text = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)
|
|
16
|
+
text = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", text)
|
|
17
|
+
return text.lower()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def seg(value: Any) -> str:
|
|
21
|
+
"""One URL path segment, percent-encoded."""
|
|
22
|
+
text = str(value)
|
|
23
|
+
if not text.strip():
|
|
24
|
+
raise ValueError("A path parameter must not be empty.")
|
|
25
|
+
return quote(text, safe="")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _scalar(value: Any) -> Any:
|
|
29
|
+
if isinstance(value, (datetime, date)):
|
|
30
|
+
return value.isoformat()
|
|
31
|
+
return value
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def drop_none(value: Any) -> Any:
|
|
35
|
+
"""The value with every ``None`` removed, nested ones too, as FinCopy reads a missing field and a null one alike."""
|
|
36
|
+
if isinstance(value, Mapping):
|
|
37
|
+
return {key: drop_none(item) for key, item in value.items() if item is not None}
|
|
38
|
+
if isinstance(value, (list, tuple)):
|
|
39
|
+
return [drop_none(item) for item in value]
|
|
40
|
+
return _scalar(value)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _query_value(value: Any) -> str:
|
|
44
|
+
if isinstance(value, bool):
|
|
45
|
+
return "true" if value else "false"
|
|
46
|
+
return str(_scalar(value))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def encode_query(
|
|
50
|
+
query: Optional[Iterable[Tuple[str, Any]]] = None,
|
|
51
|
+
extra: Optional[Iterable[Tuple[str, Any]]] = None,
|
|
52
|
+
) -> str:
|
|
53
|
+
"""The query string (without ``?``); values that are None are left out and a list repeats its name."""
|
|
54
|
+
pairs: List[Tuple[str, str]] = []
|
|
55
|
+
for name, value in list(query or []) + list(extra or []):
|
|
56
|
+
if value is None:
|
|
57
|
+
continue
|
|
58
|
+
if isinstance(value, (list, tuple)):
|
|
59
|
+
pairs.extend((name, _query_value(item)) for item in value if item is not None)
|
|
60
|
+
else:
|
|
61
|
+
pairs.append((name, _query_value(value)))
|
|
62
|
+
return "&".join(f"{quote(name, safe='')}={quote(value, safe='')}" for name, value in pairs)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _json_default(value: Any) -> Any:
|
|
66
|
+
if isinstance(value, (datetime, date)):
|
|
67
|
+
return value.isoformat()
|
|
68
|
+
raise TypeError(f"{type(value).__name__} is not JSON serializable.")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def encode_body(body: Union[Mapping[str, Any], Sequence[Any]]) -> bytes:
|
|
72
|
+
return json.dumps(drop_none(body), separators=(",", ":"), default=_json_default).encode("utf-8")
|