galore-sdk 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.
- galore_sdk-0.1.0/.gitignore +6 -0
- galore_sdk-0.1.0/LICENSE +21 -0
- galore_sdk-0.1.0/PKG-INFO +71 -0
- galore_sdk-0.1.0/README.md +49 -0
- galore_sdk-0.1.0/pyproject.toml +35 -0
- galore_sdk-0.1.0/src/galore_sdk/__init__.py +30 -0
- galore_sdk-0.1.0/src/galore_sdk/cli.py +60 -0
- galore_sdk-0.1.0/src/galore_sdk/client.py +169 -0
- galore_sdk-0.1.0/src/galore_sdk/py.typed +0 -0
- galore_sdk-0.1.0/tests/test_sdk.py +53 -0
galore_sdk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Galore
|
|
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,71 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: galore-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for Galore (trygalore.com): check every AI trade against a person's rules before it reaches the brokerage. Hosted practice API, no key.
|
|
5
|
+
Project-URL: Homepage, https://trygalore.com
|
|
6
|
+
Project-URL: Documentation, https://trygalore.com/developers/sandbox
|
|
7
|
+
Project-URL: Source, https://github.com/mehek-builds/galore-sdk
|
|
8
|
+
Project-URL: API reference, https://trygalore.com/api/sandbox/openapi.json
|
|
9
|
+
Author-email: Galore <mehekbuilds@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai trading,brokerage,galore,guardrails,mcp,pre-trade check,risk rules,trading agent,trygalore
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# galore-sdk
|
|
24
|
+
|
|
25
|
+
Galore checks every trade an AI sends against rules a person approved once, before the trade reaches their brokerage (Alpaca, Robinhood, Interactive Brokers, Kalshi, Polymarket). It never picks trades, holds money or gives advice.
|
|
26
|
+
|
|
27
|
+
> This is **Galore from [trygalore.com](https://trygalore.com)**, the AI trade-check service. It is not the GaLore PyTorch optimizer (`galore-torch`) or the `galore` spectroscopy package.
|
|
28
|
+
|
|
29
|
+
The SDK talks to Galore's **hosted practice API**: no key, no account, nothing saved. `rules` and `order` follow the live connector's `set_rules` and `send_trade` schemas, so the same objects work there; the extra `agent` argument names the AI (live, its sign-in does).
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install galore-sdk
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from galore_sdk import Galore, make_order, make_rules
|
|
37
|
+
|
|
38
|
+
galore = Galore() # hosted practice API, no key
|
|
39
|
+
|
|
40
|
+
rules = make_rules(
|
|
41
|
+
agents=["my-trading-agent"],
|
|
42
|
+
instruments=["AAPL", "MSFT"],
|
|
43
|
+
max_order_usd=2000,
|
|
44
|
+
max_daily_usd=5000,
|
|
45
|
+
max_quantity=10,
|
|
46
|
+
)
|
|
47
|
+
order = make_order(instrument="AAPL", side="buy", quantity=2, limit_price=190)
|
|
48
|
+
# make_order gives a fresh eventId; reuse an order's eventId only to retry that same trade.
|
|
49
|
+
|
|
50
|
+
result = galore.check("my-trading-agent", rules, order)
|
|
51
|
+
print(result["decision"]) # allowed | stopped | held | needs_person
|
|
52
|
+
for check in result["checks"]:
|
|
53
|
+
print(check["rule"], check["passed"], check["detail"])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Command line: `galore check --symbol AAPL --qty 2 --price 190`.
|
|
57
|
+
|
|
58
|
+
Errors raise `galore_sdk.GaloreError` with `.status`, `.code` and `.field` (the bad input). Python 3.9+, no dependencies.
|
|
59
|
+
|
|
60
|
+
## What comes back
|
|
61
|
+
|
|
62
|
+
- `decision`: `allowed` (every rule passed), `stopped` (a rule failed; the trade never reaches the brokerage), `held` (this `eventId` was already sent; read its status, never resend), `needs_person` (above `confirmAboveUsd`; the person confirms in their own browser).
|
|
63
|
+
- `summary`: one plain line. `checks`: every rule with `passed` and `detail`. `practice`: always `true` here.
|
|
64
|
+
|
|
65
|
+
Rule fields (live `set_rules` shape): `connectionId`, `agents`, `instruments`, `sides`, `timeInForce`, `maxQuantity`, `maxOrderUsd`, `maxDailySubmittedUsd`, `maxOrdersPerDay`, `maxSnapshotAgeMs`, `expiresAt` (ms), `disclosure`; optional `confirmAboveUsd`, `maxPositionUsd`. Live-only fields that need brokerage data are accepted and listed in `notChecked`. Optional `context`: `ordersToday`, `submittedTodayUsd`, `positionUsd`, `availableQuantity`, `recentEventIds`.
|
|
66
|
+
|
|
67
|
+
## Real trades
|
|
68
|
+
|
|
69
|
+
Add `https://connect.trygalore.com/mcp` to your AI as an MCP connector and sign in with a Galore account ($19 a month, Night Stop included). The person approves the rules in their own browser; the same rules and order objects work there (`brokerage` for the real `connectionId`, `set_rules`, `ask_to_approve`, then `send_trade`).
|
|
70
|
+
|
|
71
|
+
Docs: https://trygalore.com/developers/sandbox · Source: https://github.com/mehek-builds/galore-sdk · License: MIT
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# galore-sdk
|
|
2
|
+
|
|
3
|
+
Galore checks every trade an AI sends against rules a person approved once, before the trade reaches their brokerage (Alpaca, Robinhood, Interactive Brokers, Kalshi, Polymarket). It never picks trades, holds money or gives advice.
|
|
4
|
+
|
|
5
|
+
> This is **Galore from [trygalore.com](https://trygalore.com)**, the AI trade-check service. It is not the GaLore PyTorch optimizer (`galore-torch`) or the `galore` spectroscopy package.
|
|
6
|
+
|
|
7
|
+
The SDK talks to Galore's **hosted practice API**: no key, no account, nothing saved. `rules` and `order` follow the live connector's `set_rules` and `send_trade` schemas, so the same objects work there; the extra `agent` argument names the AI (live, its sign-in does).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install galore-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from galore_sdk import Galore, make_order, make_rules
|
|
15
|
+
|
|
16
|
+
galore = Galore() # hosted practice API, no key
|
|
17
|
+
|
|
18
|
+
rules = make_rules(
|
|
19
|
+
agents=["my-trading-agent"],
|
|
20
|
+
instruments=["AAPL", "MSFT"],
|
|
21
|
+
max_order_usd=2000,
|
|
22
|
+
max_daily_usd=5000,
|
|
23
|
+
max_quantity=10,
|
|
24
|
+
)
|
|
25
|
+
order = make_order(instrument="AAPL", side="buy", quantity=2, limit_price=190)
|
|
26
|
+
# make_order gives a fresh eventId; reuse an order's eventId only to retry that same trade.
|
|
27
|
+
|
|
28
|
+
result = galore.check("my-trading-agent", rules, order)
|
|
29
|
+
print(result["decision"]) # allowed | stopped | held | needs_person
|
|
30
|
+
for check in result["checks"]:
|
|
31
|
+
print(check["rule"], check["passed"], check["detail"])
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Command line: `galore check --symbol AAPL --qty 2 --price 190`.
|
|
35
|
+
|
|
36
|
+
Errors raise `galore_sdk.GaloreError` with `.status`, `.code` and `.field` (the bad input). Python 3.9+, no dependencies.
|
|
37
|
+
|
|
38
|
+
## What comes back
|
|
39
|
+
|
|
40
|
+
- `decision`: `allowed` (every rule passed), `stopped` (a rule failed; the trade never reaches the brokerage), `held` (this `eventId` was already sent; read its status, never resend), `needs_person` (above `confirmAboveUsd`; the person confirms in their own browser).
|
|
41
|
+
- `summary`: one plain line. `checks`: every rule with `passed` and `detail`. `practice`: always `true` here.
|
|
42
|
+
|
|
43
|
+
Rule fields (live `set_rules` shape): `connectionId`, `agents`, `instruments`, `sides`, `timeInForce`, `maxQuantity`, `maxOrderUsd`, `maxDailySubmittedUsd`, `maxOrdersPerDay`, `maxSnapshotAgeMs`, `expiresAt` (ms), `disclosure`; optional `confirmAboveUsd`, `maxPositionUsd`. Live-only fields that need brokerage data are accepted and listed in `notChecked`. Optional `context`: `ordersToday`, `submittedTodayUsd`, `positionUsd`, `availableQuantity`, `recentEventIds`.
|
|
44
|
+
|
|
45
|
+
## Real trades
|
|
46
|
+
|
|
47
|
+
Add `https://connect.trygalore.com/mcp` to your AI as an MCP connector and sign in with a Galore account ($19 a month, Night Stop included). The person approves the rules in their own browser; the same rules and order objects work there (`brokerage` for the real `connectionId`, `set_rules`, `ask_to_approve`, then `send_trade`).
|
|
48
|
+
|
|
49
|
+
Docs: https://trygalore.com/developers/sandbox · Source: https://github.com/mehek-builds/galore-sdk · License: MIT
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "galore-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK for Galore (trygalore.com): check every AI trade against a person's rules before it reaches the brokerage. Hosted practice API, no key."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Galore", email = "mehekbuilds@gmail.com" }]
|
|
13
|
+
keywords = ["galore", "trygalore", "ai trading", "trading agent", "pre-trade check", "risk rules", "mcp", "brokerage", "guardrails"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = []
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://trygalore.com"
|
|
27
|
+
Documentation = "https://trygalore.com/developers/sandbox"
|
|
28
|
+
Source = "https://github.com/mehek-builds/galore-sdk"
|
|
29
|
+
"API reference" = "https://trygalore.com/api/sandbox/openapi.json"
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
galore = "galore_sdk.cli:main"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/galore_sdk"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Galore SDK: check every AI trade against a person's rules before it reaches the brokerage.
|
|
2
|
+
|
|
3
|
+
Galore is trygalore.com. This package talks to its hosted practice API, which needs no key or account:
|
|
4
|
+
|
|
5
|
+
from galore_sdk import Galore
|
|
6
|
+
|
|
7
|
+
galore = Galore()
|
|
8
|
+
start = galore.example_rules()
|
|
9
|
+
result = galore.check(start["agent"], start["rules"], start["order"])
|
|
10
|
+
print(result["decision"], result["summary"])
|
|
11
|
+
|
|
12
|
+
Real trades go through the live MCP connector at https://connect.trygalore.com/mcp. The same rules and order objects
|
|
13
|
+
work there; the person signs in and approves the rules in their own browser.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .client import (
|
|
17
|
+
DEFAULT_BASE_URL,
|
|
18
|
+
DISCLOSURE,
|
|
19
|
+
LIVE_MCP_URL,
|
|
20
|
+
SITE_MCP_URL,
|
|
21
|
+
Galore,
|
|
22
|
+
GaloreError,
|
|
23
|
+
check,
|
|
24
|
+
example_rules,
|
|
25
|
+
make_order,
|
|
26
|
+
make_rules,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = ["Galore", "GaloreError", "check", "example_rules", "make_order", "make_rules", "DEFAULT_BASE_URL", "LIVE_MCP_URL", "SITE_MCP_URL"]
|
|
30
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""``galore`` command: check a trade against rules from the shell, using the hosted practice API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import math
|
|
9
|
+
|
|
10
|
+
from .client import Galore, GaloreError, make_order
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def main(argv=None) -> int:
|
|
14
|
+
parser = argparse.ArgumentParser(prog="galore", description="Galore (trygalore.com): check an AI trade against a person's rules. Practice API, no key.")
|
|
15
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
16
|
+
sub.add_parser("example", help="print example rules and an order as JSON")
|
|
17
|
+
check = sub.add_parser("check", help="check one trade")
|
|
18
|
+
check.add_argument("--symbol", required=True)
|
|
19
|
+
check.add_argument("--side", choices=["buy", "sell"], default="buy")
|
|
20
|
+
check.add_argument("--qty", type=float, required=True)
|
|
21
|
+
check.add_argument("--price", type=float, required=True, help="limit price in USD")
|
|
22
|
+
check.add_argument("--agent", default="my-trading-agent")
|
|
23
|
+
check.add_argument("--rules", help="path to a rules JSON file (default: the example rules)")
|
|
24
|
+
check.add_argument("--json", action="store_true", help="print the full JSON answer")
|
|
25
|
+
args = parser.parse_args(argv)
|
|
26
|
+
galore = Galore()
|
|
27
|
+
if args.command == "check" and not (math.isfinite(args.qty) and math.isfinite(args.price) and args.qty > 0 and args.price > 0):
|
|
28
|
+
print("galore: --qty and --price must be numbers above 0", file=sys.stderr)
|
|
29
|
+
return 2
|
|
30
|
+
try:
|
|
31
|
+
if args.command == "example":
|
|
32
|
+
print(json.dumps(galore.example_rules(), indent=2))
|
|
33
|
+
return 0
|
|
34
|
+
if args.rules:
|
|
35
|
+
with open(args.rules, encoding="utf-8") as handle:
|
|
36
|
+
rules = json.load(handle)
|
|
37
|
+
else:
|
|
38
|
+
rules = galore.example_rules()["rules"]
|
|
39
|
+
if args.agent not in rules["agents"]:
|
|
40
|
+
rules["agents"].append(args.agent)
|
|
41
|
+
order = make_order(instrument=args.symbol, side=args.side, quantity=args.qty, limit_price=args.price,
|
|
42
|
+
connection_id=rules.get("connectionId", "practice-account"))
|
|
43
|
+
result = galore.check(args.agent, rules, order)
|
|
44
|
+
except (OSError, ValueError) as error:
|
|
45
|
+
print(f"galore: could not read --rules: {error}", file=sys.stderr)
|
|
46
|
+
return 2
|
|
47
|
+
except GaloreError as error:
|
|
48
|
+
print(f"galore: {error}" + (f" ({error.field})" if error.field else ""), file=sys.stderr)
|
|
49
|
+
return 2
|
|
50
|
+
if args.json:
|
|
51
|
+
print(json.dumps(result, indent=2))
|
|
52
|
+
else:
|
|
53
|
+
print(f"{result['decision'].upper()}: {result['summary']}")
|
|
54
|
+
for item in result["checks"]:
|
|
55
|
+
print(f" {'ok ' if item['passed'] else 'NO '} {item['rule']}: {item['detail']}")
|
|
56
|
+
return 0 if result["decision"] == "allowed" else 1
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
sys.exit(main())
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""HTTP client for the Galore practice API. Standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Dict, Iterable, Mapping, Optional
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://trygalore.com/api/sandbox"
|
|
13
|
+
LIVE_MCP_URL = "https://connect.trygalore.com/mcp"
|
|
14
|
+
SITE_MCP_URL = "https://trygalore.com/mcp"
|
|
15
|
+
USER_AGENT = "galore-sdk-python/0.1.0"
|
|
16
|
+
DISCLOSURE = "Existing connection. Limit orders only. Broker approvals remain in force. No guaranteed fill or autonomous stop protection."
|
|
17
|
+
|
|
18
|
+
Json = Dict[str, Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class GaloreError(Exception):
|
|
22
|
+
"""Raised when the API refuses a request. ``field`` names the bad input, when there is one."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, status: Optional[int] = None, code: Optional[str] = None, field: Optional[str] = None, body: Any = None):
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.status = status
|
|
27
|
+
self.code = code
|
|
28
|
+
self.field = field
|
|
29
|
+
self.body = body
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Galore:
|
|
33
|
+
"""Client for Galore's hosted practice API.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
base_url: Defaults to ``GALORE_BASE_URL`` or https://trygalore.com/api/sandbox.
|
|
37
|
+
timeout: Seconds per request.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, base_url: Optional[str] = None, timeout: float = 15.0):
|
|
41
|
+
self.base_url = (base_url or os.environ.get("GALORE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
42
|
+
self.timeout = timeout
|
|
43
|
+
|
|
44
|
+
def _request(self, method: str, path: str, body: Optional[Mapping[str, Any]] = None) -> Json:
|
|
45
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
46
|
+
request = urllib.request.Request(
|
|
47
|
+
self.base_url + path,
|
|
48
|
+
data=data,
|
|
49
|
+
method=method,
|
|
50
|
+
headers={"Accept": "application/json", "Content-Type": "application/json", "User-Agent": USER_AGENT},
|
|
51
|
+
)
|
|
52
|
+
try:
|
|
53
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
54
|
+
raw = response.read().decode("utf-8")
|
|
55
|
+
try:
|
|
56
|
+
return json.loads(raw)
|
|
57
|
+
except ValueError:
|
|
58
|
+
raise GaloreError(f"Expected JSON from {self.base_url}, got: {raw[:200]}") from None
|
|
59
|
+
except urllib.error.HTTPError as error:
|
|
60
|
+
raw = error.read().decode("utf-8", "replace")
|
|
61
|
+
try:
|
|
62
|
+
payload = json.loads(raw)
|
|
63
|
+
except ValueError:
|
|
64
|
+
payload = {"error": {"message": raw or error.reason}}
|
|
65
|
+
detail = payload.get("error", {}) if isinstance(payload, dict) else {}
|
|
66
|
+
raise GaloreError(detail.get("message") or f"HTTP {error.code}", status=error.code, code=detail.get("code"), field=detail.get("field"), body=payload) from None
|
|
67
|
+
except urllib.error.URLError as error:
|
|
68
|
+
raise GaloreError(f"Could not reach {self.base_url}: {error.reason}") from None
|
|
69
|
+
except (TimeoutError, OSError) as error:
|
|
70
|
+
raise GaloreError(f"Could not reach {self.base_url}: {error}") from None
|
|
71
|
+
|
|
72
|
+
def overview(self) -> Json:
|
|
73
|
+
"""What the practice API is, with a working example."""
|
|
74
|
+
return self._request("GET", "")
|
|
75
|
+
|
|
76
|
+
def example_rules(self) -> Json:
|
|
77
|
+
"""A valid request body: ``{"agent": ..., "rules": ..., "order": ...}``. The order is good for one minute."""
|
|
78
|
+
return self._request("GET", "/example-rules")
|
|
79
|
+
|
|
80
|
+
def check(self, agent: str, rules: Mapping[str, Any], order: Mapping[str, Any], context: Optional[Mapping[str, Any]] = None) -> Json:
|
|
81
|
+
"""Check one trade by ``agent`` (the AI sending it) against rules.
|
|
82
|
+
|
|
83
|
+
``rules`` and ``order`` follow the live connector's set_rules and send_trade schemas; see make_rules and make_order.
|
|
84
|
+
|
|
85
|
+
Returns a dict with ``decision`` (``allowed``, ``stopped``, ``held`` or ``needs_person``), ``summary``,
|
|
86
|
+
``orderValueUsd`` and ``checks`` (every rule with ``passed`` and ``detail``). Raises GaloreError on bad input.
|
|
87
|
+
"""
|
|
88
|
+
body: Dict[str, Any] = {"agent": agent, "rules": dict(rules), "order": dict(order)}
|
|
89
|
+
if context:
|
|
90
|
+
body["context"] = dict(context)
|
|
91
|
+
return self._request("POST", "/check", body)
|
|
92
|
+
|
|
93
|
+
def openapi(self) -> Json:
|
|
94
|
+
"""The OpenAPI 3.1 document for this API."""
|
|
95
|
+
return self._request("GET", "/openapi.json")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def make_rules(
|
|
99
|
+
*,
|
|
100
|
+
agents: Iterable[str],
|
|
101
|
+
connection_id: str = "practice-account",
|
|
102
|
+
instruments: Iterable[str],
|
|
103
|
+
max_order_usd: float,
|
|
104
|
+
max_daily_usd: float,
|
|
105
|
+
max_quantity: float,
|
|
106
|
+
max_orders_per_day: int = 10,
|
|
107
|
+
sides: Iterable[str] = ("buy", "sell"),
|
|
108
|
+
time_in_force: Iterable[str] = ("day",),
|
|
109
|
+
days: float = 30,
|
|
110
|
+
confirm_above_usd: Optional[float] = None,
|
|
111
|
+
max_position_usd: Optional[float] = None,
|
|
112
|
+
) -> Json:
|
|
113
|
+
"""Build a rules dict in the live connector's set_rules shape. Live, connection_id comes from the brokerage tool."""
|
|
114
|
+
rules: Json = {
|
|
115
|
+
"connectionId": connection_id,
|
|
116
|
+
"agents": list(agents),
|
|
117
|
+
"instruments": [symbol.upper() for symbol in instruments],
|
|
118
|
+
"sides": list(sides),
|
|
119
|
+
"timeInForce": list(time_in_force),
|
|
120
|
+
"maxQuantity": max_quantity,
|
|
121
|
+
"maxOrderUsd": max_order_usd,
|
|
122
|
+
"maxDailySubmittedUsd": max_daily_usd,
|
|
123
|
+
"maxOrdersPerDay": max_orders_per_day,
|
|
124
|
+
"maxSnapshotAgeMs": 5000,
|
|
125
|
+
"expiresAt": int((time.time() + days * 86400) * 1000),
|
|
126
|
+
"disclosure": DISCLOSURE,
|
|
127
|
+
}
|
|
128
|
+
if confirm_above_usd is not None:
|
|
129
|
+
rules["confirmAboveUsd"] = confirm_above_usd
|
|
130
|
+
if max_position_usd is not None:
|
|
131
|
+
rules["maxPositionUsd"] = max_position_usd
|
|
132
|
+
return rules
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def make_order(
|
|
136
|
+
*,
|
|
137
|
+
instrument: str,
|
|
138
|
+
side: str,
|
|
139
|
+
quantity: float,
|
|
140
|
+
limit_price: float,
|
|
141
|
+
event_id: Optional[str] = None,
|
|
142
|
+
connection_id: str = "practice-account",
|
|
143
|
+
time_in_force: str = "day",
|
|
144
|
+
valid_for_seconds: float = 60,
|
|
145
|
+
) -> Json:
|
|
146
|
+
"""Build an order in the live send_trade shape. Keep event_id stable for retries of the same trade."""
|
|
147
|
+
import uuid
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
"eventId": event_id or f"trade-{uuid.uuid4().hex[:12]}",
|
|
151
|
+
"connectionId": connection_id,
|
|
152
|
+
"instrument": instrument.upper(),
|
|
153
|
+
"side": side,
|
|
154
|
+
"quantity": quantity,
|
|
155
|
+
"limitPrice": limit_price,
|
|
156
|
+
"orderType": "limit",
|
|
157
|
+
"timeInForce": time_in_force,
|
|
158
|
+
"validUntil": int((time.time() + valid_for_seconds) * 1000),
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def check(agent: str, rules: Mapping[str, Any], order: Mapping[str, Any], context: Optional[Mapping[str, Any]] = None) -> Json:
|
|
163
|
+
"""Shortcut for ``Galore().check(...)``."""
|
|
164
|
+
return Galore().check(agent, rules, order, context)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def example_rules() -> Json:
|
|
168
|
+
"""Shortcut for ``Galore().example_rules()``."""
|
|
169
|
+
return Galore().example_rules()
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Run with GALORE_BASE_URL pointing at a local copy of the practice API, or unset for production."""
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
from galore_sdk import Galore, GaloreError, make_order, make_rules
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SdkTest(unittest.TestCase):
|
|
10
|
+
def setUp(self):
|
|
11
|
+
self.galore = Galore()
|
|
12
|
+
|
|
13
|
+
def test_example_is_allowed(self):
|
|
14
|
+
start = self.galore.example_rules()
|
|
15
|
+
result = self.galore.check(start["agent"], start["rules"], start["order"])
|
|
16
|
+
self.assertTrue(result["practice"])
|
|
17
|
+
self.assertEqual(result["decision"], "allowed")
|
|
18
|
+
|
|
19
|
+
def test_wrong_symbol_is_stopped(self):
|
|
20
|
+
rules = make_rules(agents=["bot"], instruments=["msft"], max_order_usd=2000, max_daily_usd=5000, max_quantity=10)
|
|
21
|
+
order = make_order(instrument="AAPL", side="buy", quantity=1, limit_price=190)
|
|
22
|
+
result = self.galore.check("bot", rules, order)
|
|
23
|
+
self.assertEqual(result["decision"], "stopped")
|
|
24
|
+
self.assertEqual([c["rule"] for c in result["checks"] if not c["passed"]], ["instrument_allowed"])
|
|
25
|
+
|
|
26
|
+
def test_bad_input_names_field(self):
|
|
27
|
+
start = self.galore.example_rules()
|
|
28
|
+
order = dict(start["order"], side="short")
|
|
29
|
+
with self.assertRaises(GaloreError) as caught:
|
|
30
|
+
self.galore.check(start["agent"], start["rules"], order)
|
|
31
|
+
self.assertEqual(caught.exception.status, 400)
|
|
32
|
+
self.assertEqual(caught.exception.field, "order.side")
|
|
33
|
+
|
|
34
|
+
def test_cli(self):
|
|
35
|
+
done = subprocess.run([sys.executable, "-m", "galore_sdk.cli", "check", "--symbol", "AAPL", "--qty", "2", "--price", "190"], capture_output=True, text=True)
|
|
36
|
+
self.assertEqual(done.returncode, 0, done.stderr)
|
|
37
|
+
self.assertTrue(done.stdout.startswith("ALLOWED"))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_cli_bad_input_exits_2(self):
|
|
41
|
+
done = subprocess.run([sys.executable, "-m", "galore_sdk.cli", "check", "--symbol", "AAPL", "--qty", "nan", "--price", "190"], capture_output=True, text=True)
|
|
42
|
+
self.assertEqual(done.returncode, 2)
|
|
43
|
+
done = subprocess.run([sys.executable, "-m", "galore_sdk.cli", "check", "--symbol", "AAPL", "--qty", "1", "--price", "190", "--rules", "missing.json"], capture_output=True, text=True)
|
|
44
|
+
self.assertEqual(done.returncode, 2)
|
|
45
|
+
self.assertNotIn("Traceback", done.stderr)
|
|
46
|
+
|
|
47
|
+
def test_unreachable_is_galore_error(self):
|
|
48
|
+
with self.assertRaises(GaloreError):
|
|
49
|
+
Galore(base_url="http://127.0.0.1:9/api", timeout=2).overview()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
unittest.main()
|