brue-language 0.0.1__py3-none-any.whl
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.
- brue/__init__.py +76 -0
- brue/__main__.py +5 -0
- brue/api.py +168 -0
- brue/ast.py +321 -0
- brue/auth.py +136 -0
- brue/builtins.py +2283 -0
- brue/cli.py +282 -0
- brue/data.py +627 -0
- brue/errors.py +71 -0
- brue/indicators.py +2433 -0
- brue/jsmath.py +551 -0
- brue/jsnum.py +123 -0
- brue/live.py +287 -0
- brue/output.py +521 -0
- brue/parser.py +1136 -0
- brue/runtime.py +3242 -0
- brue/session.py +233 -0
- brue/strategy.py +760 -0
- brue/tokenizer.py +394 -0
- brue/value.py +283 -0
- brue_language-0.0.1.dist-info/METADATA +110 -0
- brue_language-0.0.1.dist-info/RECORD +52 -0
- brue_language-0.0.1.dist-info/WHEEL +4 -0
- brue_language-0.0.1.dist-info/entry_points.txt +2 -0
- brue_language-0.0.1.dist-info/licenses/LICENSE +21 -0
- brueconnect/__init__.py +15 -0
- brueconnect/__main__.py +383 -0
- brueconnect/adapter.py +329 -0
- brueconnect/adapters/__init__.py +0 -0
- brueconnect/adapters/atlas/atlas_adapter.py +2297 -0
- brueconnect/adapters/helix/helix_adapter.py +2120 -0
- brueconnect/adapters/lse_sim/__init__.py +0 -0
- brueconnect/adapters/lse_sim/lse_sim_adapter.py +895 -0
- brueconnect/adapters/meridian/meridian_adapter.py +2029 -0
- brueconnect/adapters/northgate/northgate_adapter.py +1926 -0
- brueconnect/adapters/novafx/__init__.py +0 -0
- brueconnect/adapters/novafx/novafx_adapter.py +164 -0
- brueconnect/adapters/paper/__init__.py +0 -0
- brueconnect/adapters/paper/paper_adapter.py +659 -0
- brueconnect/adapters/pemberton/pemberton_adapter.py +1860 -0
- brueconnect/adapters/quantex/quantex_adapter.py +1884 -0
- brueconnect/adapters/sablepoint/sablepoint_adapter.py +2507 -0
- brueconnect/adapters/vertex/vertex_adapter.py +2003 -0
- brueconnect/client.py +694 -0
- brueconnect/conformance/__init__.py +0 -0
- brueconnect/conformance/auth_drivers/__init__.py +0 -0
- brueconnect/conformance/auth_drivers/meridian_login.py +62 -0
- brueconnect/conformance/run.py +873 -0
- brueconnect/protocol.py +234 -0
- brueconnect/registry.py +280 -0
- brueconnect/runner/__init__.py +0 -0
- brueconnect/runner/live_driver.py +341 -0
brue/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""brue: the Brue trading EXECUTION language.
|
|
2
|
+
|
|
3
|
+
One import, one key: brue.login() verifies the LSE identity, then
|
|
4
|
+
buy()/sell()/close() place real orders through a Brue Connect broker
|
|
5
|
+
adapter. Scripts (.brue) run through run_script_full; a live driver
|
|
6
|
+
re-derives each closed bar's order intents from the script's own
|
|
7
|
+
deterministic window state (capture_intents) and hands them to the
|
|
8
|
+
connector. brue executes; research happens in plain Python on the results.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
__version__ = "0.0.1"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run_script(source, bars):
|
|
16
|
+
from .runtime import ExternalData
|
|
17
|
+
return run_script_with_data(source, bars, ExternalData())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run_script_with_data(source, bars, external):
|
|
21
|
+
from .runtime import RunOptions
|
|
22
|
+
return run_script_full(source, bars, external, {}, RunOptions())
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_script_full(source, bars, external, input_overrides, options):
|
|
26
|
+
"""tokenize + parse + execute; errors come back inside the ExecOutput,
|
|
27
|
+
never raised."""
|
|
28
|
+
from . import parser, tokenizer
|
|
29
|
+
from .errors import BrueError
|
|
30
|
+
|
|
31
|
+
# Windows editors and Python text-mode writes produce CRLF; the
|
|
32
|
+
# tokenizer speaks LF. Normalize at every entry point.
|
|
33
|
+
source = source.replace("\r\n", "\n").replace("\r", "\n")
|
|
34
|
+
try:
|
|
35
|
+
tokens = tokenizer.tokenize(source)
|
|
36
|
+
except BrueError as e:
|
|
37
|
+
return _error_output(e)
|
|
38
|
+
try:
|
|
39
|
+
program = parser.parse(tokens)
|
|
40
|
+
except BrueError as e:
|
|
41
|
+
return _error_output(e)
|
|
42
|
+
from .runtime import execute_with_options
|
|
43
|
+
return execute_with_options(program, bars, input_overrides, external, options)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# parse_time_arg and parse_bars_csv live in data.py with strict parsing
|
|
47
|
+
# (float()/int() alone are looser: underscores, unicode digits); re-exported
|
|
48
|
+
# here as public API.
|
|
49
|
+
from .data import parse_bars_csv, parse_time_arg # noqa: E402,F401
|
|
50
|
+
from .api import BrueScriptError, Indicator # noqa: E402,F401
|
|
51
|
+
from .auth import (Account, BrueAuthError, account, current_key, # noqa: E402,F401
|
|
52
|
+
login, logout)
|
|
53
|
+
# The trading surface: login -> trade. Module import is stdlib-only; the
|
|
54
|
+
# broker connection (Brue Connect subprocess) spins up on the first call.
|
|
55
|
+
from .live import (BrueLiveError, balance, buy, close, disconnect, # noqa: E402,F401
|
|
56
|
+
flatten, history, instruments, positions, sell)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _error_output(e):
|
|
60
|
+
from .output import ErrorInfo, ExecOutput
|
|
61
|
+
from .value import Value
|
|
62
|
+
return ExecOutput(
|
|
63
|
+
success=False,
|
|
64
|
+
commands=[],
|
|
65
|
+
errors=[ErrorInfo(message=e.message, line=e.loc.line, col=e.loc.col,
|
|
66
|
+
phase=e.phase, suggestion=e.suggestion)],
|
|
67
|
+
inputs=[],
|
|
68
|
+
live_orders=[],
|
|
69
|
+
live_closes=[],
|
|
70
|
+
decl_title=Value.Null,
|
|
71
|
+
decl_overlay=Value.Bool(True),
|
|
72
|
+
decl_symbol=None,
|
|
73
|
+
decl_timeframe=None,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
brue/__main__.py
ADDED
brue/api.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Host-facing helpers over the script engine.
|
|
2
|
+
|
|
3
|
+
The engine internals speak BarData lists and ExecOutput (conformance-locked,
|
|
4
|
+
do not touch). This module is the indicator bridge: indicator_series() and
|
|
5
|
+
Indicator turn a Brue script's plot() calls into named per-bar series so a
|
|
6
|
+
chart host (such as the LSE Terminal) can draw them. brue executes orders;
|
|
7
|
+
it does not report simulated P&L.
|
|
8
|
+
|
|
9
|
+
Accepted data shapes: a pandas DataFrame (any case-insensitive subset of
|
|
10
|
+
time/open/high/low/close/volume columns, time in epoch s, epoch ms, or
|
|
11
|
+
datetimes), a list of dicts with those keys, a list of [t,o,h,l,c,v] rows,
|
|
12
|
+
or a path to a csv. pandas is NOT a dependency: it is duck-typed, so the
|
|
13
|
+
package installs clean without it.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BrueScriptError(Exception):
|
|
21
|
+
"""The script failed to tokenize/parse/run; message is user-facing."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, errors):
|
|
24
|
+
self.errors = errors
|
|
25
|
+
first = errors[0] if errors else {}
|
|
26
|
+
super().__init__(first.get("message", "script error"))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _to_ms(t) -> float:
|
|
30
|
+
"""Epoch seconds, epoch ms, or datetime-like -> epoch ms."""
|
|
31
|
+
if hasattr(t, "timestamp"):
|
|
32
|
+
return float(t.timestamp() * 1000.0)
|
|
33
|
+
x = float(t)
|
|
34
|
+
# Heuristic: values below 1e11 are seconds (that is the year 5138);
|
|
35
|
+
# anything bigger is already ms.
|
|
36
|
+
return x * 1000.0 if x < 1e11 else x
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _bars_from_any(data):
|
|
40
|
+
from .runtime import BarData
|
|
41
|
+
|
|
42
|
+
if isinstance(data, str):
|
|
43
|
+
from . import parse_bars_csv
|
|
44
|
+
with open(data, encoding="utf-8") as f:
|
|
45
|
+
return parse_bars_csv(f.read())
|
|
46
|
+
|
|
47
|
+
# pandas DataFrame, duck-typed so pandas stays optional.
|
|
48
|
+
if hasattr(data, "columns") and hasattr(data, "itertuples"):
|
|
49
|
+
cols = {str(c).strip().lower(): c for c in data.columns}
|
|
50
|
+
tcol = next((cols[k] for k in ("time", "ts", "timestamp", "date",
|
|
51
|
+
"datetime") if k in cols), None)
|
|
52
|
+
need = [k for k in ("open", "high", "low", "close") if k not in cols]
|
|
53
|
+
if tcol is None or need:
|
|
54
|
+
missing = (["time"] if tcol is None else []) + need
|
|
55
|
+
raise ValueError(f"data is missing columns: {', '.join(missing)}")
|
|
56
|
+
# The index is never used as the time column: explicit only, since
|
|
57
|
+
# a wrong guess silently shifts every fill.
|
|
58
|
+
out = []
|
|
59
|
+
vol = cols.get("volume")
|
|
60
|
+
for row in data.itertuples(index=False):
|
|
61
|
+
d = dict(zip(data.columns, row))
|
|
62
|
+
out.append(BarData(
|
|
63
|
+
time=_to_ms(d[tcol]),
|
|
64
|
+
open=float(d[cols["open"]]), high=float(d[cols["high"]]),
|
|
65
|
+
low=float(d[cols["low"]]), close=float(d[cols["close"]]),
|
|
66
|
+
volume=float(d[vol]) if vol is not None else 0.0))
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
if isinstance(data, (list, tuple)) and data:
|
|
70
|
+
first = data[0]
|
|
71
|
+
if isinstance(first, dict):
|
|
72
|
+
return [BarData(time=_to_ms(r.get("time", r.get("ts", r.get("timestamp")))),
|
|
73
|
+
open=float(r["open"]), high=float(r["high"]),
|
|
74
|
+
low=float(r["low"]), close=float(r["close"]),
|
|
75
|
+
volume=float(r.get("volume", 0.0)))
|
|
76
|
+
for r in data]
|
|
77
|
+
if isinstance(first, (list, tuple)) and len(first) >= 5:
|
|
78
|
+
return [BarData(time=_to_ms(r[0]), open=float(r[1]), high=float(r[2]),
|
|
79
|
+
low=float(r[3]), close=float(r[4]),
|
|
80
|
+
volume=float(r[5]) if len(r) > 5 else 0.0)
|
|
81
|
+
for r in data]
|
|
82
|
+
raise ValueError("unsupported data shape: pass a DataFrame, list of "
|
|
83
|
+
"dicts, list of [t,o,h,l,c,v] rows, or a csv path")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def indicator_series(script: str, data, inputs: dict | None = None) -> dict:
|
|
87
|
+
"""
|
|
88
|
+
Run a Brue script as a chart INDICATOR: every plot() call becomes a
|
|
89
|
+
named series aligned to the bars. This is how chart hosts (such as the
|
|
90
|
+
LSE Terminal, or a notebook) draw Brue-written indicators on live charts.
|
|
91
|
+
|
|
92
|
+
Returns {"plots": {name: [float per bar]}, "meta": {name: kwargs},
|
|
93
|
+
"overlay": bool, "inputs": [declared input() specs],
|
|
94
|
+
"times": [epoch ms per bar]}.
|
|
95
|
+
Raises BrueScriptError on script errors.
|
|
96
|
+
"""
|
|
97
|
+
from . import run_script_full
|
|
98
|
+
from .runtime import ExternalData, RunOptions
|
|
99
|
+
from .value import Value
|
|
100
|
+
|
|
101
|
+
bars = _bars_from_any(data)
|
|
102
|
+
options = RunOptions()
|
|
103
|
+
options.collect_plots = True
|
|
104
|
+
overrides = {}
|
|
105
|
+
for k, v in (inputs or {}).items():
|
|
106
|
+
overrides[str(k)] = (Value.Bool(v) if isinstance(v, bool)
|
|
107
|
+
else Value.Num(v) if isinstance(v, (int, float))
|
|
108
|
+
else Value.Str(str(v)))
|
|
109
|
+
out = run_script_full(script, bars, ExternalData(), overrides, options)
|
|
110
|
+
raw = json.loads(out.to_json())
|
|
111
|
+
if not raw.get("success"):
|
|
112
|
+
raise BrueScriptError(raw.get("errors", []))
|
|
113
|
+
n = len(bars)
|
|
114
|
+
plots = {}
|
|
115
|
+
for name, points in getattr(out, "plots", {}).items():
|
|
116
|
+
col = [float("nan")] * n
|
|
117
|
+
for bar_i, v in points:
|
|
118
|
+
if 0 <= bar_i < n:
|
|
119
|
+
col[bar_i] = v
|
|
120
|
+
plots[name] = col
|
|
121
|
+
return {"plots": plots,
|
|
122
|
+
"meta": getattr(out, "plot_meta", {}),
|
|
123
|
+
"overlay": bool((raw.get("declaration") or {}).get("overlay", True)),
|
|
124
|
+
"inputs": raw.get("inputs", []),
|
|
125
|
+
"times": [b.time for b in bars]}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Indicator:
|
|
129
|
+
"""A Brue indicator as a first-class object: its plot() calls become
|
|
130
|
+
named series.
|
|
131
|
+
|
|
132
|
+
indicator = brue.Indicator(source)
|
|
133
|
+
indicator.compute(df) # pandas DataFrame, one column per plot
|
|
134
|
+
indicator.series(df) # plain dict of lists (no pandas needed)
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(self, source: str):
|
|
138
|
+
self.source = source
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def from_file(cls, path) -> "Indicator":
|
|
142
|
+
with open(path, encoding="utf-8") as f:
|
|
143
|
+
return cls(f.read())
|
|
144
|
+
|
|
145
|
+
def series(self, data, **inputs) -> dict:
|
|
146
|
+
r = indicator_series(self.source, data, inputs=inputs or None)
|
|
147
|
+
return r["plots"]
|
|
148
|
+
|
|
149
|
+
def compute(self, data, **inputs):
|
|
150
|
+
import pandas as pd
|
|
151
|
+
r = indicator_series(self.source, data, inputs=inputs or None)
|
|
152
|
+
df = pd.DataFrame(r["plots"])
|
|
153
|
+
df.insert(0, "time", pd.to_datetime(r["times"], unit="ms"))
|
|
154
|
+
return df
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def overlay(self) -> bool:
|
|
158
|
+
return bool(indicator_series(self.source, _PROBE_ROWS)["overlay"])
|
|
159
|
+
|
|
160
|
+
def __repr__(self):
|
|
161
|
+
import re
|
|
162
|
+
m = re.search(r'strategy\(\s*"([^"]*)"', self.source)
|
|
163
|
+
return f'Indicator("{m.group(1) if m else "untitled"}")'
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# Tiny deterministic bars for cheap structural probes (overlay flag etc).
|
|
167
|
+
_PROBE_ROWS = [[1700000000000 + i * 3600000, 100.0, 100.6, 99.5, 100.2, 1000.0]
|
|
168
|
+
for i in range(60)]
|
brue/ast.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
# AST node types. The kind_str names are observable: the runtime's
|
|
2
|
+
# expression fingerprint falls back to "{kind}_{line}_{col}" and those keys
|
|
3
|
+
# decide series-cache identity, so they are locked by the conformance goldens.
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Loc:
|
|
10
|
+
line: int
|
|
11
|
+
col: int
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Expr:
|
|
15
|
+
"""Base class for all expression nodes."""
|
|
16
|
+
|
|
17
|
+
# The kind string (used by the fingerprint fallback). Each subclass
|
|
18
|
+
# sets _KIND.
|
|
19
|
+
_KIND = ""
|
|
20
|
+
|
|
21
|
+
def kind_str(self) -> str:
|
|
22
|
+
return self._KIND
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class KeywordArg:
|
|
27
|
+
name: str
|
|
28
|
+
value: Expr
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class NumberLiteral(Expr):
|
|
33
|
+
value: float
|
|
34
|
+
loc: Loc
|
|
35
|
+
_KIND = "NumberLiteral"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class StringLiteral(Expr):
|
|
40
|
+
value: str
|
|
41
|
+
loc: Loc
|
|
42
|
+
_KIND = "StringLiteral"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class BoolLiteral(Expr):
|
|
47
|
+
value: bool
|
|
48
|
+
loc: Loc
|
|
49
|
+
_KIND = "BoolLiteral"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class NaLiteral(Expr):
|
|
54
|
+
loc: Loc
|
|
55
|
+
_KIND = "NaLiteral"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class ColorLiteral(Expr):
|
|
60
|
+
r: float
|
|
61
|
+
g: float
|
|
62
|
+
b: float
|
|
63
|
+
a: float
|
|
64
|
+
loc: Loc
|
|
65
|
+
_KIND = "ColorLiteral"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class Identifier(Expr):
|
|
70
|
+
name: str
|
|
71
|
+
loc: Loc
|
|
72
|
+
_KIND = "Identifier"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class Binary(Expr):
|
|
77
|
+
op: str
|
|
78
|
+
left: Expr
|
|
79
|
+
right: Expr
|
|
80
|
+
loc: Loc
|
|
81
|
+
_KIND = "BinaryExpr"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class Unary(Expr):
|
|
86
|
+
op: str
|
|
87
|
+
operand: Expr
|
|
88
|
+
loc: Loc
|
|
89
|
+
_KIND = "UnaryExpr"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Call(Expr):
|
|
94
|
+
callee: str
|
|
95
|
+
args: List[Expr]
|
|
96
|
+
kwargs: List[KeywordArg]
|
|
97
|
+
loc: Loc
|
|
98
|
+
_KIND = "CallExpr"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class History(Expr):
|
|
103
|
+
source: Expr
|
|
104
|
+
offset: Expr
|
|
105
|
+
loc: Loc
|
|
106
|
+
_KIND = "HistoryExpr"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class Ternary(Expr):
|
|
111
|
+
condition: Expr
|
|
112
|
+
if_true: Expr
|
|
113
|
+
if_false: Expr
|
|
114
|
+
loc: Loc
|
|
115
|
+
_KIND = "TernaryExpr"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class ArrayLiteral(Expr):
|
|
120
|
+
elements: List[Expr]
|
|
121
|
+
loc: Loc
|
|
122
|
+
_KIND = "ArrayLiteral"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class MapLiteral(Expr):
|
|
127
|
+
entries: List[Tuple[Expr, Expr]]
|
|
128
|
+
loc: Loc
|
|
129
|
+
_KIND = "MapLiteral"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class Member(Expr):
|
|
134
|
+
object: Expr
|
|
135
|
+
member: str
|
|
136
|
+
loc: Loc
|
|
137
|
+
_KIND = "MemberExpr"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class MethodCall(Expr):
|
|
142
|
+
object: Expr
|
|
143
|
+
method: str
|
|
144
|
+
args: List[Expr]
|
|
145
|
+
loc: Loc
|
|
146
|
+
_KIND = "MethodCallExpr"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class FmtPart:
|
|
150
|
+
"""F-string parts; variants are the nested classes FmtPart.Text /
|
|
151
|
+
FmtPart.Expr."""
|
|
152
|
+
|
|
153
|
+
@dataclass
|
|
154
|
+
class Text:
|
|
155
|
+
value: str
|
|
156
|
+
|
|
157
|
+
@dataclass
|
|
158
|
+
class Expr:
|
|
159
|
+
expr: "Expr"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class FormatString(Expr):
|
|
164
|
+
parts: List[object] # FmtPart.Text | FmtPart.Expr
|
|
165
|
+
specs: List[Optional[str]]
|
|
166
|
+
loc: Loc
|
|
167
|
+
_KIND = "FormatStringExpr"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass
|
|
171
|
+
class FunctionParam:
|
|
172
|
+
name: str
|
|
173
|
+
default_value: Optional[Expr]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass
|
|
177
|
+
class TypeField:
|
|
178
|
+
name: str
|
|
179
|
+
field_type: str
|
|
180
|
+
default_value: Optional[Expr]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass
|
|
184
|
+
class DeclarationStmt:
|
|
185
|
+
args: List[Expr]
|
|
186
|
+
kwargs: List[KeywordArg]
|
|
187
|
+
symbol: Optional[str]
|
|
188
|
+
timeframe: Optional[str]
|
|
189
|
+
execution_mode: str
|
|
190
|
+
broker: Optional[str]
|
|
191
|
+
account: Optional[str]
|
|
192
|
+
password: Optional[str]
|
|
193
|
+
loc: Loc
|
|
194
|
+
# Scripts have no header; the parser always builds this headerless
|
|
195
|
+
# placeholder (pure logic: qualified series, symbol-carrying orders).
|
|
196
|
+
headerless: bool = False
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass
|
|
200
|
+
class UseStmt:
|
|
201
|
+
canonical: str
|
|
202
|
+
timeframe: Optional[str]
|
|
203
|
+
alias: str
|
|
204
|
+
alias_explicit: bool
|
|
205
|
+
is_dataset: bool
|
|
206
|
+
loc: Loc
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class Stmt:
|
|
210
|
+
"""Base class for all statement nodes."""
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass
|
|
214
|
+
class Assign(Stmt):
|
|
215
|
+
target: str
|
|
216
|
+
op: str
|
|
217
|
+
value: Expr
|
|
218
|
+
loc: Loc
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass
|
|
222
|
+
class Persist(Stmt):
|
|
223
|
+
target: str
|
|
224
|
+
value: Expr
|
|
225
|
+
loc: Loc
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@dataclass
|
|
229
|
+
class Const(Stmt):
|
|
230
|
+
target: str
|
|
231
|
+
value: Expr
|
|
232
|
+
loc: Loc
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@dataclass
|
|
236
|
+
class If(Stmt):
|
|
237
|
+
condition: Expr
|
|
238
|
+
body: List[Stmt]
|
|
239
|
+
elifs: List[Tuple[Expr, List[Stmt]]]
|
|
240
|
+
else_body: List[Stmt]
|
|
241
|
+
loc: Loc
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class For(Stmt):
|
|
246
|
+
variable: str
|
|
247
|
+
iterable: Expr
|
|
248
|
+
body: List[Stmt]
|
|
249
|
+
loc: Loc
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@dataclass
|
|
253
|
+
class While(Stmt):
|
|
254
|
+
condition: Expr
|
|
255
|
+
body: List[Stmt]
|
|
256
|
+
loc: Loc
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@dataclass
|
|
260
|
+
class Break(Stmt):
|
|
261
|
+
loc: Loc
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@dataclass
|
|
265
|
+
class Continue(Stmt):
|
|
266
|
+
loc: Loc
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@dataclass
|
|
270
|
+
class FunctionDef(Stmt):
|
|
271
|
+
name: str
|
|
272
|
+
params: List[FunctionParam]
|
|
273
|
+
body: List[Stmt]
|
|
274
|
+
loc: Loc
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@dataclass
|
|
278
|
+
class Return(Stmt):
|
|
279
|
+
value: Optional[Expr]
|
|
280
|
+
loc: Loc
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass
|
|
284
|
+
class ExprStmt(Stmt):
|
|
285
|
+
expr: Expr
|
|
286
|
+
loc: Loc
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
@dataclass
|
|
290
|
+
class MemberAssign(Stmt):
|
|
291
|
+
target: Expr
|
|
292
|
+
value: Expr
|
|
293
|
+
loc: Loc
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@dataclass
|
|
297
|
+
class MultiAssign(Stmt):
|
|
298
|
+
targets: List[str]
|
|
299
|
+
value: Expr
|
|
300
|
+
loc: Loc
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@dataclass
|
|
304
|
+
class TypeDef(Stmt):
|
|
305
|
+
name: str
|
|
306
|
+
fields: List[TypeField]
|
|
307
|
+
loc: Loc
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@dataclass
|
|
311
|
+
class EnumDef(Stmt):
|
|
312
|
+
name: str
|
|
313
|
+
members: List[Tuple[str, Optional[str]]]
|
|
314
|
+
loc: Loc
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@dataclass
|
|
318
|
+
class Program:
|
|
319
|
+
declaration: DeclarationStmt
|
|
320
|
+
uses: List[UseStmt]
|
|
321
|
+
body: List[Stmt]
|
brue/auth.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Account identity for the brue ecosystem: brue.login(api_key=...) verifies
|
|
2
|
+
# the user's LSE API key (the same key they log into the data platform with)
|
|
3
|
+
# against the platform and caches the verified account for the session.
|
|
4
|
+
#
|
|
5
|
+
# Scope, deliberately narrow: login is REQUIRED for anything account-bound
|
|
6
|
+
# (LSE data, arming live trading in Brue Connect) and NOT required for the
|
|
7
|
+
# local math: indicators and script runs over local data never need a key
|
|
8
|
+
# or a network connection.
|
|
9
|
+
#
|
|
10
|
+
# stdlib-only (urllib): the brue package keeps zero hard dependencies.
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
|
|
20
|
+
VALIDATE_URL = os.environ.get(
|
|
21
|
+
"BRUE_AUTH_URL", "https://api.londonstrategicedge.com/keys/validate")
|
|
22
|
+
_CONFIG_PATH = os.path.join(
|
|
23
|
+
os.path.expanduser("~"), ".config", "brue", "config.json")
|
|
24
|
+
|
|
25
|
+
_KEY: str | None = None
|
|
26
|
+
_ACCOUNT: "Account | None" = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BrueAuthError(Exception):
|
|
30
|
+
"""Raised when a key is missing, unknown, revoked, expired, or blocked."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Account:
|
|
35
|
+
"""The verified identity behind an API key. The raw key is never stored
|
|
36
|
+
here; components that need it call current_key()."""
|
|
37
|
+
key_id: str
|
|
38
|
+
user_id: str
|
|
39
|
+
plan_id: str
|
|
40
|
+
environment: str
|
|
41
|
+
permissions: list = field(default_factory=list)
|
|
42
|
+
rate_limit_per_minute: int | None = None
|
|
43
|
+
rate_limit_per_day: int | None = None
|
|
44
|
+
features: dict | None = None
|
|
45
|
+
|
|
46
|
+
def __repr__(self):
|
|
47
|
+
return (f"Account(plan={self.plan_id!r}, environment={self.environment!r}, "
|
|
48
|
+
f"key_id={self.key_id[:8]}...)")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _resolve_key(api_key: str | None) -> str | None:
|
|
52
|
+
if api_key:
|
|
53
|
+
return api_key.strip()
|
|
54
|
+
for env in ("BRUE_API_KEY", "LSE_API_KEY"):
|
|
55
|
+
v = os.environ.get(env, "").strip()
|
|
56
|
+
if v:
|
|
57
|
+
return v
|
|
58
|
+
try:
|
|
59
|
+
with open(_CONFIG_PATH, encoding="utf-8") as f:
|
|
60
|
+
v = (json.load(f).get("api_key") or "").strip()
|
|
61
|
+
if v:
|
|
62
|
+
return v
|
|
63
|
+
except (OSError, ValueError):
|
|
64
|
+
pass
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def login(api_key: str | None = None, *, timeout: float = 15.0) -> Account:
|
|
69
|
+
"""Verify the LSE API key and cache the account for this process.
|
|
70
|
+
|
|
71
|
+
import brue
|
|
72
|
+
brue.login(api_key="lse_...") # or BRUE_API_KEY / LSE_API_KEY env,
|
|
73
|
+
brue.account() # or ~/.config/brue/config.json
|
|
74
|
+
|
|
75
|
+
Raises BrueAuthError with the service's reason on any invalid key.
|
|
76
|
+
"""
|
|
77
|
+
global _KEY, _ACCOUNT
|
|
78
|
+
key = _resolve_key(api_key)
|
|
79
|
+
if not key:
|
|
80
|
+
raise BrueAuthError(
|
|
81
|
+
"no API key: pass brue.login(api_key=...), set BRUE_API_KEY or "
|
|
82
|
+
"LSE_API_KEY, or put {\"api_key\": ...} in ~/.config/brue/config.json. "
|
|
83
|
+
"Get a key at https://londonstrategicedge.com/data")
|
|
84
|
+
req = urllib.request.Request(
|
|
85
|
+
VALIDATE_URL,
|
|
86
|
+
data=json.dumps({"key": key, "surface": "brue.login"}).encode(),
|
|
87
|
+
headers={"Content-Type": "application/json",
|
|
88
|
+
"User-Agent": "brue (+https://londonstrategicedge.com)"},
|
|
89
|
+
method="POST")
|
|
90
|
+
try:
|
|
91
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
92
|
+
payload = json.loads(resp.read().decode())
|
|
93
|
+
except urllib.error.HTTPError as e:
|
|
94
|
+
try:
|
|
95
|
+
reason = json.loads(e.read().decode()).get("reason", "")
|
|
96
|
+
except ValueError:
|
|
97
|
+
reason = ""
|
|
98
|
+
raise BrueAuthError(
|
|
99
|
+
f"key rejected ({e.code}): {reason or 'invalid key'}") from None
|
|
100
|
+
except (urllib.error.URLError, TimeoutError) as e:
|
|
101
|
+
raise BrueAuthError(
|
|
102
|
+
f"could not reach the key service ({e}); check your connection") from None
|
|
103
|
+
if not payload.get("valid"):
|
|
104
|
+
raise BrueAuthError(f"key rejected: {payload.get('reason', 'invalid key')}")
|
|
105
|
+
_KEY = key
|
|
106
|
+
_ACCOUNT = Account(
|
|
107
|
+
key_id=str(payload.get("key_id", "")),
|
|
108
|
+
user_id=str(payload.get("user_id", "")),
|
|
109
|
+
plan_id=str(payload.get("plan_id", "")),
|
|
110
|
+
environment=str(payload.get("environment", "")),
|
|
111
|
+
permissions=payload.get("permissions") or [],
|
|
112
|
+
rate_limit_per_minute=payload.get("rate_limit_per_minute"),
|
|
113
|
+
rate_limit_per_day=payload.get("rate_limit_per_day"),
|
|
114
|
+
features=payload.get("features"),
|
|
115
|
+
)
|
|
116
|
+
return _ACCOUNT
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def account() -> Account:
|
|
120
|
+
"""The Account from the last successful login (raises if not logged in)."""
|
|
121
|
+
if _ACCOUNT is None:
|
|
122
|
+
raise BrueAuthError("not logged in: call brue.login(api_key=...) first")
|
|
123
|
+
return _ACCOUNT
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def current_key() -> str:
|
|
127
|
+
"""The verified raw key, for components that must send it (data, live)."""
|
|
128
|
+
if _KEY is None:
|
|
129
|
+
raise BrueAuthError("not logged in: call brue.login(api_key=...) first")
|
|
130
|
+
return _KEY
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def logout() -> None:
|
|
134
|
+
global _KEY, _ACCOUNT
|
|
135
|
+
_KEY = None
|
|
136
|
+
_ACCOUNT = None
|