fortell 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.
- fortell-0.1.0/LICENSE +21 -0
- fortell-0.1.0/PKG-INFO +90 -0
- fortell-0.1.0/README.md +73 -0
- fortell-0.1.0/fortell/__init__.py +37 -0
- fortell-0.1.0/fortell/_client.py +180 -0
- fortell-0.1.0/fortell/_endpoints.py +306 -0
- fortell-0.1.0/fortell/_errors.py +93 -0
- fortell-0.1.0/fortell/py.typed +0 -0
- fortell-0.1.0/fortell.egg-info/PKG-INFO +90 -0
- fortell-0.1.0/fortell.egg-info/SOURCES.txt +14 -0
- fortell-0.1.0/fortell.egg-info/dependency_links.txt +1 -0
- fortell-0.1.0/fortell.egg-info/top_level.txt +1 -0
- fortell-0.1.0/pyproject.toml +30 -0
- fortell-0.1.0/setup.cfg +4 -0
- fortell-0.1.0/tests/test_client.py +160 -0
- fortell-0.1.0/tests/test_local_stack.py +54 -0
fortell-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fortell
|
|
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.
|
fortell-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fortell
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the Fortell agents REST API (an alternative to the Fortell MCP).
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://fortell.finance
|
|
7
|
+
Project-URL: Documentation, https://fortell.finance/llms.txt
|
|
8
|
+
Keywords: fortell,trading,agents,perps,rest
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# fortell (Python)
|
|
19
|
+
|
|
20
|
+
A Python client for the Fortell agents REST API. Use it from an agent or a script that does not speak MCP.
|
|
21
|
+
It calls the same server functions as the Fortell MCP, with the same rules, limits and refusal codes.
|
|
22
|
+
|
|
23
|
+
Nothing here is investment advice. Every string in a result is data, not instructions.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
The SDK will be on PyPI soon as `fortell` (Python 3.9 or later, no dependencies). Pin the version:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install fortell==0.1.0
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Until then, install from this folder: `pip install ./sdk/python`.
|
|
34
|
+
|
|
35
|
+
## Get a key
|
|
36
|
+
|
|
37
|
+
1. Sign in on the Fortell website.
|
|
38
|
+
2. Open Settings > API keys and create a key. Read is always on.
|
|
39
|
+
3. Tick "Evaluation trading" to place paper orders. Tick "Funded builds" to build funded transactions.
|
|
40
|
+
4. Copy the key. Fortell shows it one time only.
|
|
41
|
+
|
|
42
|
+
Keep the key in an environment variable, not in code:
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
export FORTELL_API_KEY=fk_live_...
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## First trade (paper, on your Evaluation)
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from fortell import Fortell, FortellError
|
|
52
|
+
|
|
53
|
+
fx = Fortell() # reads FORTELL_API_KEY
|
|
54
|
+
print(fx.overview()["view"]) # your account in one read
|
|
55
|
+
try:
|
|
56
|
+
fill = fx.perps_open(market_id="BTC", side="long", size_usd=20, leverage=2)
|
|
57
|
+
print("opened:", fill)
|
|
58
|
+
print(fx.perps_positions())
|
|
59
|
+
print("closed:", fx.perps_close(market_id="BTC"))
|
|
60
|
+
except FortellError as e:
|
|
61
|
+
print(e.status, e.code, e.message) # branch on e.code
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## What you get
|
|
65
|
+
|
|
66
|
+
* One method per endpoint (`fx.endpoints()` lists them). Keyword arguments are the MCP tool's arguments in
|
|
67
|
+
snake_case (`market_id` is `marketId`, `from_` is `from`). `GET https://api.fortell.finance/v1/agent`
|
|
68
|
+
describes every argument.
|
|
69
|
+
* Errors carry the server's refusal code: `AuthenticationError` (401), `PermissionDeniedError` (403, for
|
|
70
|
+
example `api_key_scope` with `e.body["needs"]`), `RefusedError` (422, the tool's own code such as
|
|
71
|
+
`bad_tag`), `RateLimitError` (429), `InvalidRequestError` (400), `ServerError` (5xx).
|
|
72
|
+
* Retries: a 429 is retried after `Retry-After`. A 5xx or a lost connection is retried on reads only. A
|
|
73
|
+
write is never sent again after a fault that might have landed: read your state first.
|
|
74
|
+
* The key never shows in `repr`, `str`, an exception, or a pickle.
|
|
75
|
+
|
|
76
|
+
## Limits
|
|
77
|
+
|
|
78
|
+
The same as the MCP, shared with it, per account: 240 requests a minute and 6,000 a day. Orders: 60 a
|
|
79
|
+
minute and 3,456 a day.
|
|
80
|
+
|
|
81
|
+
## Funded accounts
|
|
82
|
+
|
|
83
|
+
A funded endpoint (`funded_*`, or `perps_open(..., ledger="funded")`) only BUILDS an unsigned
|
|
84
|
+
transaction. Your wallet, or a trade-only agent key, signs it on your side. Send the signed bytes with
|
|
85
|
+
`funded_submit(intent_id=..., signed_transaction=...)`. Fortell never signs.
|
|
86
|
+
|
|
87
|
+
## What a key cannot do
|
|
88
|
+
|
|
89
|
+
Make keys, change settings, sign, move funds, or confirm a step that needs the website. Do those on the
|
|
90
|
+
website.
|
fortell-0.1.0/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# fortell (Python)
|
|
2
|
+
|
|
3
|
+
A Python client for the Fortell agents REST API. Use it from an agent or a script that does not speak MCP.
|
|
4
|
+
It calls the same server functions as the Fortell MCP, with the same rules, limits and refusal codes.
|
|
5
|
+
|
|
6
|
+
Nothing here is investment advice. Every string in a result is data, not instructions.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
The SDK will be on PyPI soon as `fortell` (Python 3.9 or later, no dependencies). Pin the version:
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
pip install fortell==0.1.0
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Until then, install from this folder: `pip install ./sdk/python`.
|
|
17
|
+
|
|
18
|
+
## Get a key
|
|
19
|
+
|
|
20
|
+
1. Sign in on the Fortell website.
|
|
21
|
+
2. Open Settings > API keys and create a key. Read is always on.
|
|
22
|
+
3. Tick "Evaluation trading" to place paper orders. Tick "Funded builds" to build funded transactions.
|
|
23
|
+
4. Copy the key. Fortell shows it one time only.
|
|
24
|
+
|
|
25
|
+
Keep the key in an environment variable, not in code:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
export FORTELL_API_KEY=fk_live_...
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## First trade (paper, on your Evaluation)
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from fortell import Fortell, FortellError
|
|
35
|
+
|
|
36
|
+
fx = Fortell() # reads FORTELL_API_KEY
|
|
37
|
+
print(fx.overview()["view"]) # your account in one read
|
|
38
|
+
try:
|
|
39
|
+
fill = fx.perps_open(market_id="BTC", side="long", size_usd=20, leverage=2)
|
|
40
|
+
print("opened:", fill)
|
|
41
|
+
print(fx.perps_positions())
|
|
42
|
+
print("closed:", fx.perps_close(market_id="BTC"))
|
|
43
|
+
except FortellError as e:
|
|
44
|
+
print(e.status, e.code, e.message) # branch on e.code
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## What you get
|
|
48
|
+
|
|
49
|
+
* One method per endpoint (`fx.endpoints()` lists them). Keyword arguments are the MCP tool's arguments in
|
|
50
|
+
snake_case (`market_id` is `marketId`, `from_` is `from`). `GET https://api.fortell.finance/v1/agent`
|
|
51
|
+
describes every argument.
|
|
52
|
+
* Errors carry the server's refusal code: `AuthenticationError` (401), `PermissionDeniedError` (403, for
|
|
53
|
+
example `api_key_scope` with `e.body["needs"]`), `RefusedError` (422, the tool's own code such as
|
|
54
|
+
`bad_tag`), `RateLimitError` (429), `InvalidRequestError` (400), `ServerError` (5xx).
|
|
55
|
+
* Retries: a 429 is retried after `Retry-After`. A 5xx or a lost connection is retried on reads only. A
|
|
56
|
+
write is never sent again after a fault that might have landed: read your state first.
|
|
57
|
+
* The key never shows in `repr`, `str`, an exception, or a pickle.
|
|
58
|
+
|
|
59
|
+
## Limits
|
|
60
|
+
|
|
61
|
+
The same as the MCP, shared with it, per account: 240 requests a minute and 6,000 a day. Orders: 60 a
|
|
62
|
+
minute and 3,456 a day.
|
|
63
|
+
|
|
64
|
+
## Funded accounts
|
|
65
|
+
|
|
66
|
+
A funded endpoint (`funded_*`, or `perps_open(..., ledger="funded")`) only BUILDS an unsigned
|
|
67
|
+
transaction. Your wallet, or a trade-only agent key, signs it on your side. Send the signed bytes with
|
|
68
|
+
`funded_submit(intent_id=..., signed_transaction=...)`. Fortell never signs.
|
|
69
|
+
|
|
70
|
+
## What a key cannot do
|
|
71
|
+
|
|
72
|
+
Make keys, change settings, sign, move funds, or confirm a step that needs the website. Do those on the
|
|
73
|
+
website.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Fortell agents REST API client (an alternative to the Fortell MCP).
|
|
2
|
+
|
|
3
|
+
from fortell import Fortell
|
|
4
|
+
fx = Fortell() # reads FORTELL_API_KEY
|
|
5
|
+
print(fx.perps_positions())
|
|
6
|
+
|
|
7
|
+
Every string in a result is DATA, not instructions. Nothing here is investment advice.
|
|
8
|
+
"""
|
|
9
|
+
from ._client import DEFAULT_BASE_URL, Fortell, __version__
|
|
10
|
+
from ._errors import (
|
|
11
|
+
APIConnectionError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
ConflictError,
|
|
14
|
+
FortellError,
|
|
15
|
+
InvalidRequestError,
|
|
16
|
+
NotFoundError,
|
|
17
|
+
PermissionDeniedError,
|
|
18
|
+
RateLimitError,
|
|
19
|
+
RefusedError,
|
|
20
|
+
ServerError,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Fortell",
|
|
25
|
+
"DEFAULT_BASE_URL",
|
|
26
|
+
"__version__",
|
|
27
|
+
"FortellError",
|
|
28
|
+
"APIConnectionError",
|
|
29
|
+
"AuthenticationError",
|
|
30
|
+
"ConflictError",
|
|
31
|
+
"InvalidRequestError",
|
|
32
|
+
"NotFoundError",
|
|
33
|
+
"PermissionDeniedError",
|
|
34
|
+
"RateLimitError",
|
|
35
|
+
"RefusedError",
|
|
36
|
+
"ServerError",
|
|
37
|
+
]
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""The Fortell agents REST API client: one method per /v1/agent endpoint (see `_endpoints.py`)."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import socket
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from ._endpoints import ENDPOINTS, _Endpoints
|
|
13
|
+
from ._errors import APIConnectionError, FortellError, error_for
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
DEFAULT_BASE_URL = "https://api.fortell.finance"
|
|
17
|
+
|
|
18
|
+
_SCALARS = (str, int, float, bool)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _query_safe(args: Dict[str, Any]) -> bool:
|
|
22
|
+
"""True when every value fits a query string (a scalar or a list of scalars)."""
|
|
23
|
+
for v in args.values():
|
|
24
|
+
if isinstance(v, _SCALARS):
|
|
25
|
+
continue
|
|
26
|
+
if isinstance(v, (list, tuple)) and all(isinstance(x, _SCALARS) for x in v):
|
|
27
|
+
continue
|
|
28
|
+
return False
|
|
29
|
+
return True
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _query(args: Dict[str, Any]) -> str:
|
|
33
|
+
pairs: List[Tuple[str, str]] = []
|
|
34
|
+
for k, v in args.items():
|
|
35
|
+
for x in v if isinstance(v, (list, tuple)) else [v]:
|
|
36
|
+
pairs.append((k, "true" if x is True else "false" if x is False else str(x)))
|
|
37
|
+
return urllib.parse.urlencode(pairs)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Secret:
|
|
41
|
+
"""Holds the key. Its repr is masked, so `vars(client)` or a debugger shows no secret."""
|
|
42
|
+
|
|
43
|
+
__slots__ = ("_v",)
|
|
44
|
+
|
|
45
|
+
def __init__(self, v: str) -> None:
|
|
46
|
+
self._v = v
|
|
47
|
+
|
|
48
|
+
def reveal(self) -> str:
|
|
49
|
+
return self._v
|
|
50
|
+
|
|
51
|
+
def __repr__(self) -> str:
|
|
52
|
+
return "<API key hidden>"
|
|
53
|
+
|
|
54
|
+
__str__ = __repr__
|
|
55
|
+
|
|
56
|
+
def __reduce__(self) -> Any:
|
|
57
|
+
raise TypeError("An API key cannot be pickled.")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _label(key: str) -> str:
|
|
61
|
+
"""The public label of a key (`fk_live_<id>_…`). Never the secret."""
|
|
62
|
+
parts = key.split("_")
|
|
63
|
+
return f"{parts[0]}_{parts[1]}_{parts[2]}_…" if len(parts) >= 4 else "fk_…"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Fortell(_Endpoints):
|
|
67
|
+
"""A client for the Fortell agents REST API.
|
|
68
|
+
|
|
69
|
+
`api_key` (or the FORTELL_API_KEY environment variable) is a key from Settings > API keys on the
|
|
70
|
+
Fortell website. The key never appears in `repr`, in `str`, or in an exception.
|
|
71
|
+
|
|
72
|
+
Retries: a 429 is retried after its Retry-After (reads and writes: the server did nothing). A 5xx
|
|
73
|
+
or a lost connection is retried on reads only, with exponential backoff and jitter. A write is
|
|
74
|
+
never sent twice for a fault that might have landed.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: Optional[str] = None,
|
|
80
|
+
*,
|
|
81
|
+
base_url: Optional[str] = None,
|
|
82
|
+
timeout: float = 60.0,
|
|
83
|
+
max_retries: int = 3,
|
|
84
|
+
backoff: float = 0.5,
|
|
85
|
+
max_backoff: float = 20.0,
|
|
86
|
+
) -> None:
|
|
87
|
+
key = api_key if api_key is not None else os.environ.get("FORTELL_API_KEY")
|
|
88
|
+
if not isinstance(key, str) or not key.startswith("fk_"):
|
|
89
|
+
raise ValueError(
|
|
90
|
+
"Pass an API key (fk_live_...) or set FORTELL_API_KEY. "
|
|
91
|
+
"Make one in Settings > API keys on the Fortell website."
|
|
92
|
+
)
|
|
93
|
+
self._key = _Secret(key)
|
|
94
|
+
self.key_label = _label(key)
|
|
95
|
+
self.base_url = (base_url or os.environ.get("FORTELL_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
96
|
+
self.timeout = timeout
|
|
97
|
+
self.max_retries = max(0, int(max_retries))
|
|
98
|
+
self.backoff = max(0.0, float(backoff))
|
|
99
|
+
self.max_backoff = max(0.0, float(max_backoff))
|
|
100
|
+
|
|
101
|
+
def __repr__(self) -> str:
|
|
102
|
+
return f"Fortell(base_url={self.base_url!r}, key={self.key_label!r})"
|
|
103
|
+
|
|
104
|
+
__str__ = __repr__
|
|
105
|
+
|
|
106
|
+
def __getstate__(self) -> Dict[str, Any]:
|
|
107
|
+
raise TypeError("A Fortell client holds an API key and cannot be pickled.")
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def endpoints() -> Tuple[Tuple[str, str, str, str, str], ...]:
|
|
111
|
+
"""(method name, HTTP method, path, MCP tool, scope) for every endpoint."""
|
|
112
|
+
return ENDPOINTS
|
|
113
|
+
|
|
114
|
+
# -- transport --------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def _delay(self, attempt: int, retry_after: Optional[float]) -> float:
|
|
117
|
+
d = min(self.max_backoff, self.backoff * (2 ** attempt)) * (0.5 + random.random() / 2)
|
|
118
|
+
return max(d, retry_after or 0.0)
|
|
119
|
+
|
|
120
|
+
def _send(self, method: str, path: str, args: Dict[str, Any]) -> Tuple[int, Dict[str, str], Any]:
|
|
121
|
+
url = f"{self.base_url}{path}"
|
|
122
|
+
data = None
|
|
123
|
+
headers = {
|
|
124
|
+
"Authorization": f"Bearer {self._key.reveal()}",
|
|
125
|
+
"Accept": "application/json",
|
|
126
|
+
"User-Agent": f"fortell-python/{__version__}",
|
|
127
|
+
}
|
|
128
|
+
if method == "GET":
|
|
129
|
+
q = _query(args)
|
|
130
|
+
if q:
|
|
131
|
+
url = f"{url}?{q}"
|
|
132
|
+
else:
|
|
133
|
+
data = json.dumps(args).encode("utf-8")
|
|
134
|
+
headers["Content-Type"] = "application/json"
|
|
135
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
136
|
+
try:
|
|
137
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
138
|
+
return res.status, {k.lower(): v for k, v in res.headers.items()}, _json(res.read())
|
|
139
|
+
except urllib.error.HTTPError as e:
|
|
140
|
+
raw = e.read() if hasattr(e, "read") else b""
|
|
141
|
+
return e.code, {k.lower(): v for k, v in (e.headers or {}).items()}, _json(raw)
|
|
142
|
+
|
|
143
|
+
def _call(self, method: str, path: str, args: Dict[str, Any], write: bool) -> Dict[str, Any]:
|
|
144
|
+
clean = {k: v for k, v in args.items() if v is not None}
|
|
145
|
+
if method == "GET" and not _query_safe(clean):
|
|
146
|
+
method = "POST"
|
|
147
|
+
attempt = 0
|
|
148
|
+
while True:
|
|
149
|
+
try:
|
|
150
|
+
status, headers, body = self._send(method, path, clean)
|
|
151
|
+
except (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError) as e:
|
|
152
|
+
if write or attempt >= self.max_retries:
|
|
153
|
+
raise APIConnectionError(
|
|
154
|
+
f"No answer from {self.base_url}: {type(e).__name__}."
|
|
155
|
+
+ (" A write is not resent: read your state before you try again." if write else "")
|
|
156
|
+
) from None
|
|
157
|
+
time.sleep(self._delay(attempt, None))
|
|
158
|
+
attempt += 1
|
|
159
|
+
continue
|
|
160
|
+
if status < 400:
|
|
161
|
+
return body if isinstance(body, dict) else {"result": body}
|
|
162
|
+
ra = headers.get("retry-after")
|
|
163
|
+
err = error_for(status, body, float(ra) if ra and ra.replace(".", "", 1).isdigit() else None)
|
|
164
|
+
retryable = status == 429 or (status >= 500 and not write and err.code != "api_keys_off")
|
|
165
|
+
if not retryable or attempt >= self.max_retries:
|
|
166
|
+
raise err
|
|
167
|
+
time.sleep(self._delay(attempt, err.retry_after))
|
|
168
|
+
attempt += 1
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _json(raw: bytes) -> Any:
|
|
172
|
+
if not raw:
|
|
173
|
+
return {}
|
|
174
|
+
try:
|
|
175
|
+
return json.loads(raw.decode("utf-8"))
|
|
176
|
+
except ValueError:
|
|
177
|
+
return {"text": raw.decode("utf-8", "replace")[:400]}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
__all__ = ["Fortell", "FortellError", "DEFAULT_BASE_URL", "__version__"]
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
# GENERATED by apps/mcp/scripts/gen-rest-sdk.ts from the REST door's index. Do not edit by hand.
|
|
2
|
+
# One method per /v1/agent endpoint; the keyword arguments are the tool's own input schema.
|
|
3
|
+
from typing import Any, Dict, List, Literal, Optional, Union # noqa: F401
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class _Endpoints:
|
|
7
|
+
"""The /v1/agent endpoints. Mixed into `fortell.Fortell`; every method returns the tool's JSON object."""
|
|
8
|
+
|
|
9
|
+
def _call(self, method: str, path: str, args: Dict[str, Any], write: bool) -> Dict[str, Any]: # pragma: no cover
|
|
10
|
+
raise NotImplementedError
|
|
11
|
+
|
|
12
|
+
def whoami(self) -> Dict[str, Any]:
|
|
13
|
+
"""
|
|
14
|
+
GET /v1/agent/whoami. Scope: read.
|
|
15
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
16
|
+
"""
|
|
17
|
+
return self._call("GET", "/v1/agent/whoami", {}, write=False)
|
|
18
|
+
|
|
19
|
+
def overview(self, *, view: Optional[Literal["challenge", "positions", "board"]] = None, market_id: Optional[str] = None, since: Optional[int] = None, asset: Optional[str] = None) -> Dict[str, Any]:
|
|
20
|
+
"""
|
|
21
|
+
GET /v1/agent/overview (MCP tool fortell_overview). Scope: read.
|
|
22
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
23
|
+
"""
|
|
24
|
+
return self._call("GET", "/v1/agent/overview", {"view": view, "marketId": market_id, "since": since, "asset": asset}, write=False)
|
|
25
|
+
|
|
26
|
+
def wallet(self, *, detail: Optional[Literal["compact", "full"]] = None) -> Dict[str, Any]:
|
|
27
|
+
"""
|
|
28
|
+
GET /v1/agent/wallet (MCP tool fortell_wallet). Scope: read.
|
|
29
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
30
|
+
"""
|
|
31
|
+
return self._call("GET", "/v1/agent/wallet", {"detail": detail}, write=False)
|
|
32
|
+
|
|
33
|
+
def catalog(self, *, code: Optional[str] = None, tier: Optional[str] = None, section: Optional[Literal["tiers", "accounts", "rules", "notes"]] = None) -> Dict[str, Any]:
|
|
34
|
+
"""
|
|
35
|
+
GET /v1/agent/catalog (MCP tool fortell_challenge_catalog). Scope: read.
|
|
36
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
37
|
+
"""
|
|
38
|
+
return self._call("GET", "/v1/agent/catalog", {"code": code, "tier": tier, "section": section}, write=False)
|
|
39
|
+
|
|
40
|
+
def state(self, *, market_id: Optional[str] = None) -> Dict[str, Any]:
|
|
41
|
+
"""
|
|
42
|
+
GET /v1/agent/state (MCP tool fortell_state). Scope: read.
|
|
43
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
44
|
+
"""
|
|
45
|
+
return self._call("GET", "/v1/agent/state", {"marketId": market_id}, write=False)
|
|
46
|
+
|
|
47
|
+
def progress(self) -> Dict[str, Any]:
|
|
48
|
+
"""
|
|
49
|
+
GET /v1/agent/progress (MCP tool fortell_progress). Scope: read.
|
|
50
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
51
|
+
"""
|
|
52
|
+
return self._call("GET", "/v1/agent/progress", {}, write=False)
|
|
53
|
+
|
|
54
|
+
def brief(self, *, market_id: Optional[str] = None, since: Optional[int] = None, markets: Optional[int] = None) -> Dict[str, Any]:
|
|
55
|
+
"""
|
|
56
|
+
GET /v1/agent/brief (MCP tool fortell_brief). Scope: read.
|
|
57
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
58
|
+
"""
|
|
59
|
+
return self._call("GET", "/v1/agent/brief", {"marketId": market_id, "since": since, "markets": markets}, write=False)
|
|
60
|
+
|
|
61
|
+
def stocks(self, *, all: Optional[bool] = None, symbols: Optional[List[str]] = None, detail: Optional[Literal["compact", "full"]] = None, section: Optional[Literal["board", "notes"]] = None) -> Dict[str, Any]:
|
|
62
|
+
"""
|
|
63
|
+
GET /v1/agent/stocks (MCP tool fortell_stocks). Scope: read.
|
|
64
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
65
|
+
"""
|
|
66
|
+
return self._call("GET", "/v1/agent/stocks", {"all": all, "symbols": symbols, "detail": detail, "section": section}, write=False)
|
|
67
|
+
|
|
68
|
+
def seat(self) -> Dict[str, Any]:
|
|
69
|
+
"""
|
|
70
|
+
GET /v1/agent/seat (MCP tool fortell_seat). Scope: read.
|
|
71
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
72
|
+
"""
|
|
73
|
+
return self._call("GET", "/v1/agent/seat", {}, write=False)
|
|
74
|
+
|
|
75
|
+
def profile(self, *, trader: Optional[str] = None) -> Dict[str, Any]:
|
|
76
|
+
"""
|
|
77
|
+
GET /v1/agent/profile (MCP tool fortell_profile). Scope: read.
|
|
78
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
79
|
+
"""
|
|
80
|
+
return self._call("GET", "/v1/agent/profile", {"trader": trader}, write=False)
|
|
81
|
+
|
|
82
|
+
def leaderboards(self, *, board: Optional[Literal["crews", "traders"]] = None, who: Optional[Literal["humans", "agents"]] = None) -> Dict[str, Any]:
|
|
83
|
+
"""
|
|
84
|
+
GET /v1/agent/leaderboards (MCP tool fortell_leaderboards). Scope: read.
|
|
85
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
86
|
+
"""
|
|
87
|
+
return self._call("GET", "/v1/agent/leaderboards", {"board": board, "who": who}, write=False)
|
|
88
|
+
|
|
89
|
+
def referral(self) -> Dict[str, Any]:
|
|
90
|
+
"""
|
|
91
|
+
GET /v1/agent/referral (MCP tool fortell_referral). Scope: read.
|
|
92
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
93
|
+
"""
|
|
94
|
+
return self._call("GET", "/v1/agent/referral", {}, write=False)
|
|
95
|
+
|
|
96
|
+
def crew(self, *, action: Optional[Literal["create", "join", "invite", "leave"]] = None, mode: Optional[Literal["duo", "trio"]] = None, name: Optional[str] = None, code: Optional[str] = None, friend: Optional[str] = None) -> Dict[str, Any]:
|
|
97
|
+
"""
|
|
98
|
+
GET /v1/agent/crew (MCP tool fortell_crew). Scope: read.
|
|
99
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
100
|
+
"""
|
|
101
|
+
return self._call("GET", "/v1/agent/crew", {"action": action, "mode": mode, "name": name, "code": code, "friend": friend}, write=False)
|
|
102
|
+
|
|
103
|
+
def transparency(self, *, tier: Optional[str] = None, section: Optional[Literal["figures", "notes"]] = None) -> Dict[str, Any]:
|
|
104
|
+
"""
|
|
105
|
+
GET /v1/agent/transparency (MCP tool fortell_transparency). Scope: read.
|
|
106
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
107
|
+
"""
|
|
108
|
+
return self._call("GET", "/v1/agent/transparency", {"tier": tier, "section": section}, write=False)
|
|
109
|
+
|
|
110
|
+
def price_history(self, *, market_id: Optional[str] = None, asset: Optional[str] = None, mins: Optional[int] = None, range: Optional[Literal["1h", "4h", "1d", "1w"]] = None, candles: Optional[Literal["1m", "5m", "15m", "1h", "4h", "1d"]] = None, from_: Optional[int] = None, to: Optional[int] = None, limit: Optional[int] = None, max_points: Optional[int] = None) -> Dict[str, Any]:
|
|
111
|
+
"""
|
|
112
|
+
GET /v1/agent/price-history (MCP tool fortell_price_history). Scope: read.
|
|
113
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
114
|
+
"""
|
|
115
|
+
return self._call("GET", "/v1/agent/price-history", {"marketId": market_id, "asset": asset, "mins": mins, "range": range, "candles": candles, "from": from_, "to": to, "limit": limit, "maxPoints": max_points}, write=False)
|
|
116
|
+
|
|
117
|
+
def backtest(self, *, markets: Optional[List[str]] = None, interval: Optional[Literal["15m", "1h", "4h", "1d"]] = None, from_: Optional[int] = None, to: Optional[int] = None, entry: Optional[Dict[str, Any]] = None, exit: Optional[Dict[str, Any]] = None, filters: Optional[Dict[str, Any]] = None, variants: Optional[List[Dict[str, Any]]] = None, detail: Optional[List[str]] = None, coverage: Optional[bool] = None, tier: Optional[str] = None, costs: Optional[Dict[str, Any]] = None, sizing: Optional[Dict[str, Any]] = None, split: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
118
|
+
"""
|
|
119
|
+
GET /v1/agent/backtest (MCP tool fortell_backtest). Scope: read.
|
|
120
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
121
|
+
"""
|
|
122
|
+
return self._call("GET", "/v1/agent/backtest", {"markets": markets, "interval": interval, "from": from_, "to": to, "entry": entry, "exit": exit, "filters": filters, "variants": variants, "detail": detail, "coverage": coverage, "tier": tier, "costs": costs, "sizing": sizing, "split": split}, write=False)
|
|
123
|
+
|
|
124
|
+
def perps_markets(self, *, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, symbols: Optional[List[str]] = None, limit: Optional[int] = None, detail: Optional[Literal["compact", "full"]] = None) -> Dict[str, Any]:
|
|
125
|
+
"""
|
|
126
|
+
GET /v1/agent/perps/markets (MCP tool fortell_perps_markets). Scope: read.
|
|
127
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
128
|
+
"""
|
|
129
|
+
return self._call("GET", "/v1/agent/perps/markets", {"ledger": ledger, "symbols": symbols, "limit": limit, "detail": detail}, write=False)
|
|
130
|
+
|
|
131
|
+
def perps_quote(self, *, market_id: str, side: Literal["long", "short"], size_usd: Optional[float] = None, base_qty: Optional[float] = None, usd: Optional[float] = None, leverage: Optional[float] = None, slippage_bps: Optional[int] = None, ledger: Optional[Literal["challenge", "practice", "funded"]] = None) -> Dict[str, Any]:
|
|
132
|
+
"""
|
|
133
|
+
GET /v1/agent/perps/quote (MCP tool fortell_perps_quote). Scope: read.
|
|
134
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
135
|
+
"""
|
|
136
|
+
return self._call("GET", "/v1/agent/perps/quote", {"marketId": market_id, "side": side, "sizeUsd": size_usd, "baseQty": base_qty, "usd": usd, "leverage": leverage, "slippageBps": slippage_bps, "ledger": ledger}, write=False)
|
|
137
|
+
|
|
138
|
+
def perps_positions(self, *, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, closed: Optional[Dict[str, Any]] = None, since: Optional[str] = None, limit: Optional[int] = None, wait_secs: Optional[int] = None, watch: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
139
|
+
"""
|
|
140
|
+
GET /v1/agent/perps/positions (MCP tool fortell_perps_positions). Scope: read.
|
|
141
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
142
|
+
"""
|
|
143
|
+
return self._call("GET", "/v1/agent/perps/positions", {"ledger": ledger, "closed": closed, "since": since, "limit": limit, "waitSecs": wait_secs, "watch": watch}, write=False)
|
|
144
|
+
|
|
145
|
+
def perps_rails(self, *, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, what_if_return_pct: Optional[float] = None) -> Dict[str, Any]:
|
|
146
|
+
"""
|
|
147
|
+
GET /v1/agent/perps/rails (MCP tool fortell_perps_rails). Scope: read.
|
|
148
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
149
|
+
"""
|
|
150
|
+
return self._call("GET", "/v1/agent/perps/rails", {"ledger": ledger, "whatIfReturnPct": what_if_return_pct}, write=False)
|
|
151
|
+
|
|
152
|
+
def playbook(self, *, skill: Optional[Literal["position-watch", "rails-watch", "pass-coach", "order-helper", "journal-coach", "fortell-setup"]] = None, template: Optional[Literal["pass-coach-guard", "btc-scalp-desk", "eth-sol-intraday", "swing-keeper", "trend-follow-frame", "range-frame", "breakout-watch", "commodities-event-day", "stocks-session"]] = None) -> Dict[str, Any]:
|
|
153
|
+
"""
|
|
154
|
+
GET /v1/agent/playbook (MCP tool fortell_playbook). Scope: read.
|
|
155
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
156
|
+
"""
|
|
157
|
+
return self._call("GET", "/v1/agent/playbook", {"skill": skill, "template": template}, write=False)
|
|
158
|
+
|
|
159
|
+
def guide(self, *, doc: Optional[Literal["llms.txt", "skill.md"]] = None) -> Dict[str, Any]:
|
|
160
|
+
"""
|
|
161
|
+
GET /v1/agent/guide (MCP tool fortell_guide). Scope: read.
|
|
162
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
163
|
+
"""
|
|
164
|
+
return self._call("GET", "/v1/agent/guide", {"doc": doc}, write=False)
|
|
165
|
+
|
|
166
|
+
def changelog(self) -> Dict[str, Any]:
|
|
167
|
+
"""
|
|
168
|
+
GET /v1/agent/changelog (MCP tool fortell_changelog). Scope: read.
|
|
169
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
170
|
+
"""
|
|
171
|
+
return self._call("GET", "/v1/agent/changelog", {}, write=False)
|
|
172
|
+
|
|
173
|
+
def perps_open(self, *, market_id: str, side: Literal["long", "short"], size_usd: Optional[float] = None, base_qty: Optional[float] = None, usd: Optional[float] = None, leverage: Optional[float] = None, stop_loss: Optional[float] = None, take_profit: Optional[float] = None, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, client_order_id: Optional[str] = None, tag: Optional[str] = None, slippage_bps: Optional[int] = None, agent_key: Optional[str] = None, agent_name: Optional[int] = None, transaction_version: Optional[Literal["v1", "legacy", "v0"]] = None) -> Dict[str, Any]:
|
|
174
|
+
"""
|
|
175
|
+
POST /v1/agent/perps/open (MCP tool fortell_perps_open). Scope: trade-evaluation (ledger funded:
|
|
176
|
+
funded-build).
|
|
177
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
178
|
+
"""
|
|
179
|
+
return self._call("POST", "/v1/agent/perps/open", {"marketId": market_id, "side": side, "sizeUsd": size_usd, "baseQty": base_qty, "usd": usd, "leverage": leverage, "stopLoss": stop_loss, "takeProfit": take_profit, "ledger": ledger, "clientOrderId": client_order_id, "tag": tag, "slippageBps": slippage_bps, "agentKey": agent_key, "agentName": agent_name, "transactionVersion": transaction_version}, write=True)
|
|
180
|
+
|
|
181
|
+
def perps_close(self, *, market_id: str, fraction: Optional[float] = None, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, client_order_id: Optional[str] = None, tag: Optional[str] = None, slippage_bps: Optional[int] = None, agent_key: Optional[str] = None, agent_name: Optional[int] = None) -> Dict[str, Any]:
|
|
182
|
+
"""
|
|
183
|
+
POST /v1/agent/perps/close (MCP tool fortell_perps_close). Scope: trade-evaluation (ledger
|
|
184
|
+
funded: funded-build).
|
|
185
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
186
|
+
"""
|
|
187
|
+
return self._call("POST", "/v1/agent/perps/close", {"marketId": market_id, "fraction": fraction, "ledger": ledger, "clientOrderId": client_order_id, "tag": tag, "slippageBps": slippage_bps, "agentKey": agent_key, "agentName": agent_name}, write=True)
|
|
188
|
+
|
|
189
|
+
def perps_protection(self, *, action: Literal["set", "cancel"], kind: Optional[Literal["stop_loss", "take_profit"]] = None, market_id: Optional[str] = None, trigger_price: Optional[float] = None, order_id: Optional[str] = None, size_pct: Optional[float] = None, size_lots: Optional[Union[str, int]] = None, tag: Optional[str] = None, ledger: Optional[Literal["challenge", "practice", "funded"]] = None, agent_key: Optional[str] = None, agent_name: Optional[int] = None) -> Dict[str, Any]:
|
|
190
|
+
"""
|
|
191
|
+
POST /v1/agent/perps/protection (MCP tool fortell_perps_protection). Scope: trade-evaluation
|
|
192
|
+
(ledger funded: funded-build).
|
|
193
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
194
|
+
"""
|
|
195
|
+
return self._call("POST", "/v1/agent/perps/protection", {"action": action, "kind": kind, "marketId": market_id, "triggerPrice": trigger_price, "orderId": order_id, "sizePct": size_pct, "sizeLots": size_lots, "tag": tag, "ledger": ledger, "agentKey": agent_key, "agentName": agent_name}, write=True)
|
|
196
|
+
|
|
197
|
+
def funded_buy_challenge(self, *, tier: str, code: Optional[str] = None) -> Dict[str, Any]:
|
|
198
|
+
"""
|
|
199
|
+
POST /v1/agent/funded/buy-challenge (MCP tool fortell_build_buy_challenge). Scope: funded-build.
|
|
200
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
201
|
+
"""
|
|
202
|
+
return self._call("POST", "/v1/agent/funded/buy-challenge", {"tier": tier, "code": code}, write=True)
|
|
203
|
+
|
|
204
|
+
def funded_resume_purchase(self) -> Dict[str, Any]:
|
|
205
|
+
"""
|
|
206
|
+
POST /v1/agent/funded/resume-purchase (MCP tool fortell_resume_purchase). Scope: funded-build.
|
|
207
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
208
|
+
"""
|
|
209
|
+
return self._call("POST", "/v1/agent/funded/resume-purchase", {}, write=True)
|
|
210
|
+
|
|
211
|
+
def funded_claim(self, *, vault: Optional[str] = None, amount_usd: Optional[float] = None) -> Dict[str, Any]:
|
|
212
|
+
"""
|
|
213
|
+
POST /v1/agent/funded/claim (MCP tool fortell_build_claim). Scope: funded-build.
|
|
214
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
215
|
+
"""
|
|
216
|
+
return self._call("POST", "/v1/agent/funded/claim", {"vault": vault, "amountUsd": amount_usd}, write=True)
|
|
217
|
+
|
|
218
|
+
def funded_hand_back(self, *, vault: Optional[str] = None) -> Dict[str, Any]:
|
|
219
|
+
"""
|
|
220
|
+
POST /v1/agent/funded/hand-back (MCP tool fortell_hand_back_seat). Scope: funded-build.
|
|
221
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
222
|
+
"""
|
|
223
|
+
return self._call("POST", "/v1/agent/funded/hand-back", {"vault": vault}, write=True)
|
|
224
|
+
|
|
225
|
+
def funded_level_up(self, *, vault: Optional[str] = None) -> Dict[str, Any]:
|
|
226
|
+
"""
|
|
227
|
+
POST /v1/agent/funded/level-up (MCP tool fortell_build_level_up). Scope: funded-build.
|
|
228
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
229
|
+
"""
|
|
230
|
+
return self._call("POST", "/v1/agent/funded/level-up", {"vault": vault}, write=True)
|
|
231
|
+
|
|
232
|
+
def funded_grant_agent(self, *, agent_key: str, cap_usd: float, name: Optional[int] = None, hours: Optional[float] = None, vault: Optional[str] = None) -> Dict[str, Any]:
|
|
233
|
+
"""
|
|
234
|
+
POST /v1/agent/funded/grant-agent (MCP tool fortell_build_grant_agent). Scope: funded-build.
|
|
235
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
236
|
+
"""
|
|
237
|
+
return self._call("POST", "/v1/agent/funded/grant-agent", {"agentKey": agent_key, "name": name, "hours": hours, "capUsd": cap_usd, "vault": vault}, write=True)
|
|
238
|
+
|
|
239
|
+
def funded_seat_trade(self, *, action: Literal["buy", "sell"], round: Optional[str] = None, usd: Optional[float] = None, lots: Optional[int] = None, leverage: Optional[float] = None, side: Optional[Literal["long", "short"]] = None, fraction: Optional[float] = None, outcome: Optional[int] = None, slippage_bps: Optional[int] = None, vault: Optional[str] = None, min_fill_usd: Optional[float] = None, agent_key: Optional[str] = None, agent_name: Optional[int] = None) -> Dict[str, Any]:
|
|
240
|
+
"""
|
|
241
|
+
POST /v1/agent/funded/seat-trade (MCP tool fortell_build_seat_trade). Scope: funded-build.
|
|
242
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
243
|
+
"""
|
|
244
|
+
return self._call("POST", "/v1/agent/funded/seat-trade", {"action": action, "round": round, "usd": usd, "lots": lots, "leverage": leverage, "side": side, "fraction": fraction, "outcome": outcome, "slippageBps": slippage_bps, "vault": vault, "minFillUsd": min_fill_usd, "agentKey": agent_key, "agentName": agent_name}, write=True)
|
|
245
|
+
|
|
246
|
+
def funded_seat_bracket(self, *, action: Literal["set", "clear"], market_id: str, stop_usd: Optional[float] = None, take_usd: Optional[float] = None, vault: Optional[str] = None, agent_key: Optional[str] = None, agent_name: Optional[int] = None) -> Dict[str, Any]:
|
|
247
|
+
"""
|
|
248
|
+
POST /v1/agent/funded/seat-bracket (MCP tool fortell_seat_bracket). Scope: funded-build.
|
|
249
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
250
|
+
"""
|
|
251
|
+
return self._call("POST", "/v1/agent/funded/seat-bracket", {"action": action, "marketId": market_id, "stopUsd": stop_usd, "takeUsd": take_usd, "vault": vault, "agentKey": agent_key, "agentName": agent_name}, write=True)
|
|
252
|
+
|
|
253
|
+
def funded_seat_order(self, *, action: Literal["place", "cancel"], kind: Optional[Literal["limit", "stop_loss", "take_profit"]] = None, market_id: Optional[str] = None, side: Optional[Literal["long", "short"]] = None, usd: Optional[float] = None, leverage: Optional[float] = None, limit_price: Optional[float] = None, trigger_price: Optional[float] = None, position_id: Optional[str] = None, order_id: Optional[str] = None, vault: Optional[str] = None) -> Dict[str, Any]:
|
|
254
|
+
"""
|
|
255
|
+
POST /v1/agent/funded/seat-order (MCP tool fortell_seat_order). Scope: funded-build.
|
|
256
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
257
|
+
"""
|
|
258
|
+
return self._call("POST", "/v1/agent/funded/seat-order", {"action": action, "kind": kind, "marketId": market_id, "side": side, "usd": usd, "leverage": leverage, "limitPrice": limit_price, "triggerPrice": trigger_price, "positionId": position_id, "orderId": order_id, "vault": vault}, write=True)
|
|
259
|
+
|
|
260
|
+
def funded_submit(self, *, intent_id: str, signed_transaction: str) -> Dict[str, Any]:
|
|
261
|
+
"""
|
|
262
|
+
POST /v1/agent/funded/submit (MCP tool fortell_submit_signed_transaction). Scope: funded-build.
|
|
263
|
+
The full description and limits of each argument: GET /v1/agent.
|
|
264
|
+
"""
|
|
265
|
+
return self._call("POST", "/v1/agent/funded/submit", {"intentId": intent_id, "signedTransaction": signed_transaction}, write=True)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
# (method name, HTTP method, path, MCP tool, scope) for every endpoint, in the index order.
|
|
269
|
+
ENDPOINTS = (
|
|
270
|
+
("whoami", "GET", "/v1/agent/whoami", "", "read"),
|
|
271
|
+
("overview", "GET", "/v1/agent/overview", "fortell_overview", "read"),
|
|
272
|
+
("wallet", "GET", "/v1/agent/wallet", "fortell_wallet", "read"),
|
|
273
|
+
("catalog", "GET", "/v1/agent/catalog", "fortell_challenge_catalog", "read"),
|
|
274
|
+
("state", "GET", "/v1/agent/state", "fortell_state", "read"),
|
|
275
|
+
("progress", "GET", "/v1/agent/progress", "fortell_progress", "read"),
|
|
276
|
+
("brief", "GET", "/v1/agent/brief", "fortell_brief", "read"),
|
|
277
|
+
("stocks", "GET", "/v1/agent/stocks", "fortell_stocks", "read"),
|
|
278
|
+
("seat", "GET", "/v1/agent/seat", "fortell_seat", "read"),
|
|
279
|
+
("profile", "GET", "/v1/agent/profile", "fortell_profile", "read"),
|
|
280
|
+
("leaderboards", "GET", "/v1/agent/leaderboards", "fortell_leaderboards", "read"),
|
|
281
|
+
("referral", "GET", "/v1/agent/referral", "fortell_referral", "read"),
|
|
282
|
+
("crew", "GET", "/v1/agent/crew", "fortell_crew", "read"),
|
|
283
|
+
("transparency", "GET", "/v1/agent/transparency", "fortell_transparency", "read"),
|
|
284
|
+
("price_history", "GET", "/v1/agent/price-history", "fortell_price_history", "read"),
|
|
285
|
+
("backtest", "GET", "/v1/agent/backtest", "fortell_backtest", "read"),
|
|
286
|
+
("perps_markets", "GET", "/v1/agent/perps/markets", "fortell_perps_markets", "read"),
|
|
287
|
+
("perps_quote", "GET", "/v1/agent/perps/quote", "fortell_perps_quote", "read"),
|
|
288
|
+
("perps_positions", "GET", "/v1/agent/perps/positions", "fortell_perps_positions", "read"),
|
|
289
|
+
("perps_rails", "GET", "/v1/agent/perps/rails", "fortell_perps_rails", "read"),
|
|
290
|
+
("playbook", "GET", "/v1/agent/playbook", "fortell_playbook", "read"),
|
|
291
|
+
("guide", "GET", "/v1/agent/guide", "fortell_guide", "read"),
|
|
292
|
+
("changelog", "GET", "/v1/agent/changelog", "fortell_changelog", "read"),
|
|
293
|
+
("perps_open", "POST", "/v1/agent/perps/open", "fortell_perps_open", "trade-evaluation (ledger funded: funded-build)"),
|
|
294
|
+
("perps_close", "POST", "/v1/agent/perps/close", "fortell_perps_close", "trade-evaluation (ledger funded: funded-build)"),
|
|
295
|
+
("perps_protection", "POST", "/v1/agent/perps/protection", "fortell_perps_protection", "trade-evaluation (ledger funded: funded-build)"),
|
|
296
|
+
("funded_buy_challenge", "POST", "/v1/agent/funded/buy-challenge", "fortell_build_buy_challenge", "funded-build"),
|
|
297
|
+
("funded_resume_purchase", "POST", "/v1/agent/funded/resume-purchase", "fortell_resume_purchase", "funded-build"),
|
|
298
|
+
("funded_claim", "POST", "/v1/agent/funded/claim", "fortell_build_claim", "funded-build"),
|
|
299
|
+
("funded_hand_back", "POST", "/v1/agent/funded/hand-back", "fortell_hand_back_seat", "funded-build"),
|
|
300
|
+
("funded_level_up", "POST", "/v1/agent/funded/level-up", "fortell_build_level_up", "funded-build"),
|
|
301
|
+
("funded_grant_agent", "POST", "/v1/agent/funded/grant-agent", "fortell_build_grant_agent", "funded-build"),
|
|
302
|
+
("funded_seat_trade", "POST", "/v1/agent/funded/seat-trade", "fortell_build_seat_trade", "funded-build"),
|
|
303
|
+
("funded_seat_bracket", "POST", "/v1/agent/funded/seat-bracket", "fortell_seat_bracket", "funded-build"),
|
|
304
|
+
("funded_seat_order", "POST", "/v1/agent/funded/seat-order", "fortell_seat_order", "funded-build"),
|
|
305
|
+
("funded_submit", "POST", "/v1/agent/funded/submit", "fortell_submit_signed_transaction", "funded-build"),
|
|
306
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Errors of the Fortell agents REST API. Each carries the server's refusal `code`, never the API key."""
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class FortellError(Exception):
|
|
6
|
+
"""A refused or failed call. `code` is the stable machine name; branch on it, not on the message."""
|
|
7
|
+
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
message: str,
|
|
11
|
+
*,
|
|
12
|
+
status: Optional[int] = None,
|
|
13
|
+
code: Optional[str] = None,
|
|
14
|
+
body: Optional[Dict[str, Any]] = None,
|
|
15
|
+
retry_after: Optional[float] = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.message = message
|
|
19
|
+
self.status = status
|
|
20
|
+
self.code = code
|
|
21
|
+
self.body: Dict[str, Any] = body if isinstance(body, dict) else {}
|
|
22
|
+
self.retry_after = retry_after
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
return f"[{self.status} {self.code}] {self.message}"
|
|
26
|
+
|
|
27
|
+
def __repr__(self) -> str:
|
|
28
|
+
return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class InvalidRequestError(FortellError):
|
|
32
|
+
"""400 or 405: the arguments or the method (invalid_arguments, invalid_json, method_not_allowed)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthenticationError(FortellError):
|
|
36
|
+
"""401: api_key_missing, api_key_invalid, api_key_revoked, api_key_expired, api_key_wallet_unlinked,
|
|
37
|
+
api_key_signed_out, api_key_account_inactive."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PermissionDeniedError(FortellError):
|
|
41
|
+
"""403: api_key_scope (see `.body["needs"]`), confirm_needs_website, wallet_not_yours."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class NotFoundError(FortellError):
|
|
45
|
+
"""404: no such endpoint."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ConflictError(FortellError):
|
|
49
|
+
"""409: an identical call is still running (in_flight). Wait for it; do not resend."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class RefusedError(FortellError):
|
|
53
|
+
"""422: the tool refused the call. `.code` and `.body` are the tool's own (the same as on the MCP)."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RateLimitError(FortellError):
|
|
57
|
+
"""429: too many requests. `.retry_after` is in seconds."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ServerError(FortellError):
|
|
61
|
+
"""5xx: a fault on the server side."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class APIConnectionError(FortellError):
|
|
65
|
+
"""The request did not get an answer (network, timeout)."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def error_for(status: int, body: Any, retry_after: Optional[float]) -> FortellError:
|
|
69
|
+
"""The error class for an HTTP status and the server's JSON body."""
|
|
70
|
+
b = body if isinstance(body, dict) else {}
|
|
71
|
+
message = str(b.get("error") or b.get("text") or f"HTTP {status}")
|
|
72
|
+
code = b.get("code") if isinstance(b.get("code"), str) else None
|
|
73
|
+
if status == 429:
|
|
74
|
+
cls = RateLimitError
|
|
75
|
+
elif status in (400, 405):
|
|
76
|
+
cls = InvalidRequestError
|
|
77
|
+
elif status == 401:
|
|
78
|
+
cls = AuthenticationError
|
|
79
|
+
elif status == 403:
|
|
80
|
+
cls = PermissionDeniedError
|
|
81
|
+
elif status == 404:
|
|
82
|
+
cls = NotFoundError
|
|
83
|
+
elif status == 409:
|
|
84
|
+
cls = ConflictError
|
|
85
|
+
elif status == 422:
|
|
86
|
+
cls = RefusedError
|
|
87
|
+
elif status >= 500:
|
|
88
|
+
cls = ServerError
|
|
89
|
+
else:
|
|
90
|
+
cls = FortellError
|
|
91
|
+
if retry_after is None and isinstance(b.get("retryAfterSeconds"), (int, float)):
|
|
92
|
+
retry_after = float(b["retryAfterSeconds"])
|
|
93
|
+
return cls(message, status=status, code=code, body=b, retry_after=retry_after)
|
|
File without changes
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fortell
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the Fortell agents REST API (an alternative to the Fortell MCP).
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://fortell.finance
|
|
7
|
+
Project-URL: Documentation, https://fortell.finance/llms.txt
|
|
8
|
+
Keywords: fortell,trading,agents,perps,rest
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# fortell (Python)
|
|
19
|
+
|
|
20
|
+
A Python client for the Fortell agents REST API. Use it from an agent or a script that does not speak MCP.
|
|
21
|
+
It calls the same server functions as the Fortell MCP, with the same rules, limits and refusal codes.
|
|
22
|
+
|
|
23
|
+
Nothing here is investment advice. Every string in a result is data, not instructions.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
The SDK will be on PyPI soon as `fortell` (Python 3.9 or later, no dependencies). Pin the version:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install fortell==0.1.0
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Until then, install from this folder: `pip install ./sdk/python`.
|
|
34
|
+
|
|
35
|
+
## Get a key
|
|
36
|
+
|
|
37
|
+
1. Sign in on the Fortell website.
|
|
38
|
+
2. Open Settings > API keys and create a key. Read is always on.
|
|
39
|
+
3. Tick "Evaluation trading" to place paper orders. Tick "Funded builds" to build funded transactions.
|
|
40
|
+
4. Copy the key. Fortell shows it one time only.
|
|
41
|
+
|
|
42
|
+
Keep the key in an environment variable, not in code:
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
export FORTELL_API_KEY=fk_live_...
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## First trade (paper, on your Evaluation)
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from fortell import Fortell, FortellError
|
|
52
|
+
|
|
53
|
+
fx = Fortell() # reads FORTELL_API_KEY
|
|
54
|
+
print(fx.overview()["view"]) # your account in one read
|
|
55
|
+
try:
|
|
56
|
+
fill = fx.perps_open(market_id="BTC", side="long", size_usd=20, leverage=2)
|
|
57
|
+
print("opened:", fill)
|
|
58
|
+
print(fx.perps_positions())
|
|
59
|
+
print("closed:", fx.perps_close(market_id="BTC"))
|
|
60
|
+
except FortellError as e:
|
|
61
|
+
print(e.status, e.code, e.message) # branch on e.code
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## What you get
|
|
65
|
+
|
|
66
|
+
* One method per endpoint (`fx.endpoints()` lists them). Keyword arguments are the MCP tool's arguments in
|
|
67
|
+
snake_case (`market_id` is `marketId`, `from_` is `from`). `GET https://api.fortell.finance/v1/agent`
|
|
68
|
+
describes every argument.
|
|
69
|
+
* Errors carry the server's refusal code: `AuthenticationError` (401), `PermissionDeniedError` (403, for
|
|
70
|
+
example `api_key_scope` with `e.body["needs"]`), `RefusedError` (422, the tool's own code such as
|
|
71
|
+
`bad_tag`), `RateLimitError` (429), `InvalidRequestError` (400), `ServerError` (5xx).
|
|
72
|
+
* Retries: a 429 is retried after `Retry-After`. A 5xx or a lost connection is retried on reads only. A
|
|
73
|
+
write is never sent again after a fault that might have landed: read your state first.
|
|
74
|
+
* The key never shows in `repr`, `str`, an exception, or a pickle.
|
|
75
|
+
|
|
76
|
+
## Limits
|
|
77
|
+
|
|
78
|
+
The same as the MCP, shared with it, per account: 240 requests a minute and 6,000 a day. Orders: 60 a
|
|
79
|
+
minute and 3,456 a day.
|
|
80
|
+
|
|
81
|
+
## Funded accounts
|
|
82
|
+
|
|
83
|
+
A funded endpoint (`funded_*`, or `perps_open(..., ledger="funded")`) only BUILDS an unsigned
|
|
84
|
+
transaction. Your wallet, or a trade-only agent key, signs it on your side. Send the signed bytes with
|
|
85
|
+
`funded_submit(intent_id=..., signed_transaction=...)`. Fortell never signs.
|
|
86
|
+
|
|
87
|
+
## What a key cannot do
|
|
88
|
+
|
|
89
|
+
Make keys, change settings, sign, move funds, or confirm a step that needs the website. Do those on the
|
|
90
|
+
website.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
fortell/__init__.py
|
|
5
|
+
fortell/_client.py
|
|
6
|
+
fortell/_endpoints.py
|
|
7
|
+
fortell/_errors.py
|
|
8
|
+
fortell/py.typed
|
|
9
|
+
fortell.egg-info/PKG-INFO
|
|
10
|
+
fortell.egg-info/SOURCES.txt
|
|
11
|
+
fortell.egg-info/dependency_links.txt
|
|
12
|
+
fortell.egg-info/top_level.txt
|
|
13
|
+
tests/test_client.py
|
|
14
|
+
tests/test_local_stack.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fortell
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fortell"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python client for the Fortell agents REST API (an alternative to the Fortell MCP)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = []
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
keywords = ["fortell", "trading", "agents", "perps", "rest"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://fortell.finance"
|
|
24
|
+
Documentation = "https://fortell.finance/llms.txt"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
include = ["fortell*"]
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.package-data]
|
|
30
|
+
fortell = ["py.typed"]
|
fortell-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Unit tests of the client against a local stub server (no network, no Fortell)."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import pickle
|
|
5
|
+
import sys
|
|
6
|
+
import threading
|
|
7
|
+
import unittest
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
9
|
+
from urllib.parse import parse_qs, urlparse
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
12
|
+
|
|
13
|
+
import fortell # noqa: E402
|
|
14
|
+
from fortell import Fortell # noqa: E402
|
|
15
|
+
|
|
16
|
+
KEY = "fk_test_abcdefghijkl_" + "Z" * 43
|
|
17
|
+
SECRET = "Z" * 43
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Stub(BaseHTTPRequestHandler):
|
|
21
|
+
script = [] # list of (status, headers, body) answered in order; the last one repeats
|
|
22
|
+
seen = []
|
|
23
|
+
|
|
24
|
+
def log_message(self, *a): # quiet
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
def _answer(self):
|
|
28
|
+
n = int(self.headers.get("content-length") or 0)
|
|
29
|
+
raw = self.rfile.read(n) if n else b""
|
|
30
|
+
Stub.seen.append({
|
|
31
|
+
"method": self.command, "path": urlparse(self.path).path, "query": parse_qs(urlparse(self.path).query),
|
|
32
|
+
"auth": self.headers.get("authorization"), "body": json.loads(raw) if raw else None,
|
|
33
|
+
})
|
|
34
|
+
status, headers, body = Stub.script[min(len(Stub.seen) - 1, len(Stub.script) - 1)]
|
|
35
|
+
data = json.dumps(body).encode()
|
|
36
|
+
self.send_response(status)
|
|
37
|
+
self.send_header("content-type", "application/json")
|
|
38
|
+
for k, v in headers.items():
|
|
39
|
+
self.send_header(k, v)
|
|
40
|
+
self.send_header("content-length", str(len(data)))
|
|
41
|
+
self.end_headers()
|
|
42
|
+
self.wfile.write(data)
|
|
43
|
+
|
|
44
|
+
do_GET = _answer
|
|
45
|
+
do_POST = _answer
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ClientTest(unittest.TestCase):
|
|
49
|
+
@classmethod
|
|
50
|
+
def setUpClass(cls):
|
|
51
|
+
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), Stub)
|
|
52
|
+
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
53
|
+
cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}"
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def tearDownClass(cls):
|
|
57
|
+
cls.srv.shutdown()
|
|
58
|
+
|
|
59
|
+
def setUp(self):
|
|
60
|
+
Stub.seen = []
|
|
61
|
+
Stub.script = [(200, {}, {"ok": True})]
|
|
62
|
+
self.fx = Fortell(KEY, base_url=self.url, backoff=0.001, max_backoff=0.002)
|
|
63
|
+
|
|
64
|
+
def test_no_secret_in_repr_vars_or_pickle(self):
|
|
65
|
+
for text in (repr(self.fx), str(self.fx), repr(vars(self.fx))):
|
|
66
|
+
self.assertNotIn(SECRET, text)
|
|
67
|
+
self.assertIn("fk_test_abcdefghijkl_", repr(self.fx))
|
|
68
|
+
with self.assertRaises(TypeError):
|
|
69
|
+
pickle.dumps(self.fx)
|
|
70
|
+
|
|
71
|
+
def test_key_required(self):
|
|
72
|
+
old = os.environ.pop("FORTELL_API_KEY", None)
|
|
73
|
+
try:
|
|
74
|
+
with self.assertRaises(ValueError):
|
|
75
|
+
Fortell(base_url=self.url)
|
|
76
|
+
with self.assertRaises(ValueError):
|
|
77
|
+
Fortell("not-a-key", base_url=self.url)
|
|
78
|
+
finally:
|
|
79
|
+
if old is not None:
|
|
80
|
+
os.environ["FORTELL_API_KEY"] = old
|
|
81
|
+
|
|
82
|
+
def test_read_is_get_with_query_and_bearer(self):
|
|
83
|
+
out = self.fx.price_history(market_id="BTC", from_=1764633600, limit=5)
|
|
84
|
+
self.assertEqual(out, {"ok": True})
|
|
85
|
+
s = Stub.seen[0]
|
|
86
|
+
self.assertEqual((s["method"], s["path"]), ("GET", "/v1/agent/price-history"))
|
|
87
|
+
self.assertEqual(s["auth"], f"Bearer {KEY}")
|
|
88
|
+
self.assertEqual(s["query"], {"marketId": ["BTC"], "from": ["1764633600"], "limit": ["5"]})
|
|
89
|
+
|
|
90
|
+
def test_read_with_an_object_is_post(self):
|
|
91
|
+
self.fx.backtest(markets=["BTC"], entry={"rule": "x"})
|
|
92
|
+
s = Stub.seen[0]
|
|
93
|
+
self.assertEqual(s["method"], "POST")
|
|
94
|
+
self.assertEqual(s["body"], {"markets": ["BTC"], "entry": {"rule": "x"}})
|
|
95
|
+
|
|
96
|
+
def test_write_is_post_json(self):
|
|
97
|
+
self.fx.perps_open(market_id="BTC", side="long", size_usd=10, leverage=2)
|
|
98
|
+
s = Stub.seen[0]
|
|
99
|
+
self.assertEqual((s["method"], s["path"]), ("POST", "/v1/agent/perps/open"))
|
|
100
|
+
self.assertEqual(s["body"], {"marketId": "BTC", "side": "long", "sizeUsd": 10, "leverage": 2})
|
|
101
|
+
|
|
102
|
+
def test_429_is_retried_on_a_write_after_retry_after(self):
|
|
103
|
+
Stub.script = [(429, {"retry-after": "0"}, {"error": "slow down", "code": "rate_limited"}), (200, {}, {"done": 1})]
|
|
104
|
+
self.assertEqual(self.fx.perps_close(market_id="BTC"), {"done": 1})
|
|
105
|
+
self.assertEqual(len(Stub.seen), 2)
|
|
106
|
+
|
|
107
|
+
def test_5xx_is_retried_on_a_read_only(self):
|
|
108
|
+
Stub.script = [(502, {}, {"error": "bad gateway"}), (200, {}, {"ok": 2})]
|
|
109
|
+
self.assertEqual(self.fx.state(), {"ok": 2})
|
|
110
|
+
Stub.seen = []
|
|
111
|
+
Stub.script = [(503, {}, {"error": "down", "code": "no_store"})]
|
|
112
|
+
with self.assertRaises(fortell.ServerError) as cm:
|
|
113
|
+
self.fx.perps_open(market_id="BTC", side="long", size_usd=10)
|
|
114
|
+
self.assertEqual(len(Stub.seen), 1, "a write is never resent after a 5xx")
|
|
115
|
+
self.assertEqual(cm.exception.code, "no_store")
|
|
116
|
+
|
|
117
|
+
def test_retries_stop(self):
|
|
118
|
+
Stub.script = [(429, {"retry-after": "0"}, {"error": "slow", "code": "rate_limited"})]
|
|
119
|
+
fx = Fortell(KEY, base_url=self.url, max_retries=2, backoff=0.001)
|
|
120
|
+
with self.assertRaises(fortell.RateLimitError) as cm:
|
|
121
|
+
fx.state()
|
|
122
|
+
self.assertEqual(len(Stub.seen), 3)
|
|
123
|
+
self.assertEqual(cm.exception.retry_after, 0.0)
|
|
124
|
+
|
|
125
|
+
def test_errors_carry_the_refusal_code_and_no_secret(self):
|
|
126
|
+
cases = [
|
|
127
|
+
(401, "api_key_revoked", fortell.AuthenticationError),
|
|
128
|
+
(403, "api_key_scope", fortell.PermissionDeniedError),
|
|
129
|
+
(422, "bad_tag", fortell.RefusedError),
|
|
130
|
+
(400, "invalid_arguments", fortell.InvalidRequestError),
|
|
131
|
+
(409, "in_flight", fortell.ConflictError),
|
|
132
|
+
(404, "not_found", fortell.NotFoundError),
|
|
133
|
+
]
|
|
134
|
+
for status, code, cls in cases:
|
|
135
|
+
Stub.seen = []
|
|
136
|
+
Stub.script = [(status, {}, {"error": f"refused {code}", "code": code, "needs": "trade-evaluation"})]
|
|
137
|
+
with self.assertRaises(cls) as cm:
|
|
138
|
+
self.fx.perps_open(market_id="BTC", side="long", size_usd=10)
|
|
139
|
+
e = cm.exception
|
|
140
|
+
self.assertEqual((e.status, e.code), (status, code))
|
|
141
|
+
self.assertEqual(e.body.get("needs"), "trade-evaluation")
|
|
142
|
+
for text in (str(e), repr(e)):
|
|
143
|
+
self.assertNotIn(SECRET, text)
|
|
144
|
+
|
|
145
|
+
def test_connection_error_on_a_write_is_not_resent(self):
|
|
146
|
+
fx = Fortell(KEY, base_url="http://127.0.0.1:9", max_retries=3, backoff=0.001, timeout=2)
|
|
147
|
+
with self.assertRaises(fortell.APIConnectionError) as cm:
|
|
148
|
+
fx.perps_close(market_id="BTC")
|
|
149
|
+
self.assertNotIn(SECRET, str(cm.exception))
|
|
150
|
+
|
|
151
|
+
def test_one_method_per_endpoint(self):
|
|
152
|
+
names = [e[0] for e in Fortell.endpoints()]
|
|
153
|
+
self.assertEqual(len(names), len(set(names)))
|
|
154
|
+
for n in names:
|
|
155
|
+
self.assertTrue(callable(getattr(self.fx, n)), n)
|
|
156
|
+
self.assertNotIn("wallet", Fortell.perps_open.__code__.co_varnames[: Fortell.perps_open.__code__.co_kwonlyargcount + 1])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == "__main__":
|
|
160
|
+
unittest.main()
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""The SDK against the local REST door (apps/mcp/test/rest-sdk.ts starts it and sets the environment).
|
|
2
|
+
|
|
3
|
+
Skipped when FORTELL_SDK_STACK_URL is unset, EXCEPT when FORTELL_SDK_REQUIRE_STACK=1: then a skip is a failure,
|
|
4
|
+
so the gate that runs it can never pass by skipping.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import unittest
|
|
9
|
+
|
|
10
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
11
|
+
|
|
12
|
+
import fortell # noqa: E402
|
|
13
|
+
from fortell import Fortell # noqa: E402
|
|
14
|
+
|
|
15
|
+
URL = os.environ.get("FORTELL_SDK_STACK_URL")
|
|
16
|
+
READ = os.environ.get("FORTELL_SDK_STACK_READ_KEY")
|
|
17
|
+
TRADE = os.environ.get("FORTELL_SDK_STACK_TRADE_KEY")
|
|
18
|
+
REQUIRED = os.environ.get("FORTELL_SDK_REQUIRE_STACK") == "1"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LocalStackTest(unittest.TestCase):
|
|
22
|
+
def setUp(self):
|
|
23
|
+
if not URL:
|
|
24
|
+
if REQUIRED:
|
|
25
|
+
self.fail("FORTELL_SDK_REQUIRE_STACK=1 but no stack URL was given")
|
|
26
|
+
self.skipTest("no local stack")
|
|
27
|
+
|
|
28
|
+
def test_whoami_and_reads(self):
|
|
29
|
+
fx = Fortell(READ, base_url=URL)
|
|
30
|
+
me = fx.whoami()
|
|
31
|
+
self.assertEqual(me["scopes"], ["read"])
|
|
32
|
+
guide = fx.guide()
|
|
33
|
+
self.assertTrue(guide.get("text") or guide)
|
|
34
|
+
changes = fx.changelog()
|
|
35
|
+
self.assertIsInstance(changes, dict)
|
|
36
|
+
|
|
37
|
+
def test_refusals_carry_codes(self):
|
|
38
|
+
with self.assertRaises(fortell.PermissionDeniedError) as cm:
|
|
39
|
+
Fortell(READ, base_url=URL).perps_open(market_id="BTC", side="long", size_usd=10)
|
|
40
|
+
self.assertEqual(cm.exception.code, "api_key_scope")
|
|
41
|
+
self.assertEqual(cm.exception.body.get("needs"), "trade-evaluation")
|
|
42
|
+
with self.assertRaises(fortell.RefusedError) as cm:
|
|
43
|
+
Fortell(TRADE, base_url=URL).perps_open(market_id="BTC", side="long", size_usd=10, ledger="challenge", tag="not a tag!")
|
|
44
|
+
self.assertEqual(cm.exception.code, "bad_tag")
|
|
45
|
+
with self.assertRaises(fortell.InvalidRequestError) as cm:
|
|
46
|
+
Fortell(READ, base_url=URL).perps_quote(market_id="BTC", side="sideways", size_usd=10) # type: ignore[arg-type]
|
|
47
|
+
self.assertEqual(cm.exception.code, "invalid_arguments")
|
|
48
|
+
with self.assertRaises(fortell.AuthenticationError) as cm:
|
|
49
|
+
Fortell("fk_test_" + "u" * 12 + "_" + "u" * 43, base_url=URL).state()
|
|
50
|
+
self.assertEqual(cm.exception.code, "api_key_invalid")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
if __name__ == "__main__":
|
|
54
|
+
unittest.main()
|