@reyaxyz/strategy-format 0.0.0-stage → 0.2.0

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.
package/LICENSE.md ADDED
@@ -0,0 +1 @@
1
+ MIT License
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @reyaxyz/strategy-format
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The v3 strategy format (`reya.workflow/3`) for TypeScript, shared by the chat (reya-mcp) and the app.
4
+ The workflow service stays the only judge of whether a strategy is valid; this package lets a client
5
+ show and hash a document it receives.
6
+
7
+ - `readStrategy(text)`: the document and its `versionHash`, or a refusal with a code and a dotted path.
8
+ Checks, in order: at most 12,288 UTF-8 bytes, nesting at most 32, JSON, canonical text, no default written out
9
+ (`explicit_default`), well-formed Unicode, reya-chain's generated JSON Schema (read by zod, with `rounds`
10
+ capped at u32 as the parser reads it), four rules the schema cannot express (`id_duplicate`,
11
+ `one_of_violated`, `rounds_then_mismatch`, `label_control_character`), and the expression caps
12
+ (`expr_too_large`: each tree at most 8 deep, at most 256 nodes in the document). A convenience, never a
13
+ validator: later-phase faults are the service's. It accepts every document that only a later phase
14
+ refuses (the structure-phase ranges reya-chain writes into the schema are dropped when it loads). It
15
+ lets a few parse-phase faults through, which the service refuses: string lengths are counted in UTF-16
16
+ units, not bytes, and decimal precision is not checked. Neither makes a card differ from the hashed
17
+ bytes, since the hash is over the exact text and the text must be canonical.
18
+ - `canonical(doc)` and `versionHash(doc)`: `keccak256(UTF-8(canonical(doc)))`, what Start signs.
19
+ - `sentences(doc, t?, locale?, mode?)`: one line per block, keyed by block id, plus the three settings. Every field
20
+ the format leaves out is worded by its meaning (a crossing with no band fires again only after going
21
+ back past its level, a stop level with no size closes all of it). `t` is a translation of
22
+ `src/en.json`; English by default. `mode` is `live` (the default, also for a draft) or `paper`: a
23
+ Paper run has no liquidation, and its max loss, position and account value are its own, so those
24
+ lines have a `.paper` form. A test changes every signed value of every example (and of
25
+ `tests/kitchen-sink.json`, which holds every kind and field the examples lack) one at a time, and
26
+ fails if no line changes. A pin's source ids
27
+ (`market`, `outcome`) are not shown: the card shows the label the trader saw, which the service
28
+ checks against them.
29
+ - `workflowV3Schema`, `acceptedKinds`, `schemaSource`: the copies of reya-chain's files and the commit
30
+ they came from.
31
+
32
+ Dependencies: `zod` and `@noble/hashes` only. No v2 code.
33
+
34
+ ## The copies of reya-chain's files
35
+
36
+ `src/schema/` (the schema and the accepted-kinds list) and `tests/fixtures/reya-chain/` (the examples,
37
+ their manifest and the e1 signing vectors) are copies, pinned to one reya-chain commit in each
38
+ `source.json` with every file's SHA-256 (the examples are checked against the manifest's). Re-copy
39
+ with `scripts/copy-from-reya-chain.sh <reya-chain clone> [commit]`, never by hand; the tests then run
40
+ every example through the reader and the hash, and fail on a kind or field `sentences` does not word.
package/dist/en.json ADDED
@@ -0,0 +1,212 @@
1
+ {
2
+ "state.ref": "state {n}",
3
+ "state.named": "\"{name}\" (state {n})",
4
+ "state.start": "Start: ",
5
+ "state.start.member": "Start for each member: ",
6
+ "state.in_list": " (for each member of list {list})",
7
+ "state.checks": " Checks {rules}, in that order.",
8
+ "state.normal": "{start}{ref}{in_list}.{checks}",
9
+ "state.loop_head": "{start}{ref}{in_list}: a loop of at most {rounds} rounds, then {then}.{checks}",
10
+ "state.loop_head.unbounded": "{start}{ref}{in_list}: a loop with no round limit.{checks}",
11
+ "state.final.done": "{start}{ref}{in_list}: the end; the strategy closes its positions and is done.{checks}",
12
+ "state.final.done.member": "{start}{ref}{in_list}: the end for that member; its position is closed.{checks}",
13
+ "state.final.hold": "{start}{ref}{in_list}: the end; the positions are held, resting orders that would add to a position are cancelled, and from here on no rule in any later state or list member opens or adds to a position.{checks}",
14
+ "state.final.hold.member": "{start}{ref}{in_list}: the end for that member; its position is held, and it never counts as ended.{checks}",
15
+ "rule.ref": "rule {n}",
16
+ "rule.do": "{when}{if}: {do}, then {go}.",
17
+ "rule.go": "{when}{if}: {go}.",
18
+ "rule.go.to": "go to {state}",
19
+ "rule.go.round": "go back to {state} for its next round: {reentry}",
20
+ "rule.go.round.then": "go back to {state} for its next round (after the last, go to {then}): {reentry}",
21
+ "rule.go.to.loop": "go to {state} (after its last round, {then} instead)",
22
+ "rule.go.to.self": "go to {state} (from {state} itself, re-enter it: {reentry})",
23
+ "rule.go.again": "re-enter {state}: {reentry}",
24
+ "rule.reentry": "its \"once the state has lasted\" clocks restart, crossings that have not fired start over, values remembered on entry are taken again, and the previous visit's resting orders that are not kept are cancelled",
25
+ "rule.if": ", if {cond}",
26
+ "rule.if.held": ", as soon as {cond}",
27
+ "rule.actions.join": ", then ",
28
+ "trigger.start": "When the strategy starts",
29
+ "trigger.cross.up": "When {value} crosses above {level}{band}",
30
+ "trigger.cross.down": "When {value} crosses below {level}{band}",
31
+ "trigger.cross.band": " (it fires again only after going back {band} past {level})",
32
+ "trigger.cross.band.odds.one": " (it fires again only after going back {band} point past {level})",
33
+ "trigger.cross.band.odds.other": " (it fires again only after going back {band} points past {level})",
34
+ "trigger.cross.no_band": " (it fires again only after going back past {level})",
35
+ "odds.level": "{value}%",
36
+ "trigger.every": "Every {period}, counted from Start",
37
+ "trigger.every.anchor": "Every {period}, counted from {anchor}",
38
+ "trigger.at.daily": "Every day at {time} UTC{day}",
39
+ "trigger.at.weekly": "Every week at {time} UTC{day}",
40
+ "trigger.at.day": ", on {day}s",
41
+ "trigger.elapsed": "Once the state has lasted {after}",
42
+ "trigger.filled": "When resting order {order} fills, even partly",
43
+ "trigger.stop_loss": "When the stop loss on {market} is hit ({levels})",
44
+ "trigger.take_profit": "When the take profit on {market} is hit ({levels})",
45
+ "trigger.instances_ended": "When every member of list {list} has reached a done end",
46
+ "trigger.refused": "When action {action} is refused",
47
+ "trigger.refused.any": "When any action is refused",
48
+ "trigger.close_open": "When a close or reduce is still not done after 2 minutes",
49
+ "trigger.source_unreadable": "When Polymarket's \"{question}\" can't be read",
50
+ "trigger.source_ended": "When Polymarket's \"{question}\" ends",
51
+ "levels.join": "; ",
52
+ "level.line": "{at}, {closes}",
53
+ "level.closes.all": "closes all of it",
54
+ "level.closes.size": "closes {size}",
55
+ "level.price": "at {price}",
56
+ "level.from_entry.pct": "{pct}% from the entry",
57
+ "level.from_entry.distance": "{distance} from the entry",
58
+ "level.trailing.pct": "trailing {pct}%{activation}",
59
+ "level.trailing.distance": "trailing {distance}{activation}",
60
+ "level.trailing.activation": " once the price reaches {activation}",
61
+ "level.expr": "at {value}",
62
+ "action.order": "{side} {size} of {market} at the market, at most {bps} bps from the mark",
63
+ "action.limit_orders.one": "place {count} resting order ({orders}); {keep}",
64
+ "action.limit_orders.other": "place {count} resting orders ({orders}); {keep}",
65
+ "action.limit_orders.keep": "they stay when {home} is left",
66
+ "action.limit_orders.no_keep": "they are cancelled when {home} is left",
67
+ "action.limit_orders.home": "the state they are placed in",
68
+ "action.close": "close the strategy's position on {market}",
69
+ "action.reduce": "reduce the strategy's position on {market} by {by}",
70
+ "action.close_set": "close every member of list {list}",
71
+ "action.rebalance": "rebalance list {list} to {total} by weight ({weights})",
72
+ "action.rebalance.total.account": "the account value",
73
+ "action.rebalance.total.account.paper": "this Paper run's margin",
74
+ "action.rebalance.total": "{total} rUSD",
75
+ "action.move_stop": "move level {level} of {rule} to {to}",
76
+ "orders.join": "; ",
77
+ "order.resting": "{side} {size} of {market} at {price}, {taker}",
78
+ "order.taker_ok": "may take",
79
+ "order.post_only": "post-only",
80
+ "price.fixed": "{price}",
81
+ "price.offset_bps.above": "{bps} bps above the mark when sent",
82
+ "price.offset_bps.below": "{bps} bps below the mark when sent",
83
+ "price.offset_bps.zero": "the mark when sent",
84
+ "price.expr": "{expr}",
85
+ "weights.join": "; ",
86
+ "weight.row": "{weight} for {members}",
87
+ "weight.row.otherwise": "otherwise {weight} for {members}",
88
+ "weight.if": "members where {cond}",
89
+ "weight.all": "every member",
90
+ "side.buy": "buy",
91
+ "side.sell": "sell",
92
+ "side.row": "buy or sell (the row's side)",
93
+ "size.rusd": "{rusd} rUSD",
94
+ "size.qty": "{qty}",
95
+ "size.expr": "{expr} rUSD",
96
+ "size.row": "the row's size",
97
+ "size.pct": "{pct}%",
98
+ "market.row": "the row's market",
99
+ "pin": "the chance of \"{outcome}\" on \"{question}\"",
100
+ "pin.line": "Reads {pin} on Polymarket; the market ends on {ends}.",
101
+ "list.fixed": "List {n}: {rows}. Each member starts at {start}.",
102
+ "list.filter": "List {n}: up to {max} markets from {from} where {where}. Each member starts at {start}.",
103
+ "list.rank": "List {n}: the {top} markets from {from} with the {order} {by}. Each member starts at {start}.",
104
+ "list.from.all": "every trading market",
105
+ "list.rank.desc": "highest",
106
+ "list.rank.asc": "lowest",
107
+ "rows.join": "; ",
108
+ "row": "{market}{side}{size}{reads}",
109
+ "row.side": ", {side}",
110
+ "row.size": ", {size}",
111
+ "row.reads": ", reading {pins}",
112
+ "setting.max_loss_rusd": "Max loss: {value} rUSD; when the account's loss since Start (open positions at the mark, fees and funding included; a position held at Start counts from its mark at Start) reaches it, the strategy closes every position on the account, including ones held before Start, and ends.",
113
+ "setting.max_loss_rusd.paper": "Max loss: {value} rUSD; when this Paper run's loss since Start (its Paper positions at the mark, simulated fees and funding included) reaches it, the run closes its Paper positions and ends. Nothing on your real account changes.",
114
+ "setting.max_loss_rusd.none": "No max loss is set.",
115
+ "setting.on_liquidation.close_and_end": "If the account is liquidated, the strategy closes every position on the account and ends.",
116
+ "setting.on_liquidation.close_and_end.paper": "Paper has no liquidation: nothing forces a Paper position closed. On Live, if the account is liquidated, the strategy closes every position on the account and ends.",
117
+ "setting.on_liquidation.carry_on": "If the account is liquidated, the strategy carries on.",
118
+ "setting.on_liquidation.carry_on.paper": "Paper has no liquidation: nothing forces a Paper position closed. On Live, if the account is liquidated, the strategy carries on.",
119
+ "setting.on_margin_skip.keep_running": "If an order is refused for lack of margin, the rule that placed it does nothing (no other action, no state change), a rule on a refused action can answer it, and the strategy keeps running.",
120
+ "setting.on_margin_skip.stop": "If an order is refused for lack of margin, the rule that placed it does nothing and the strategy stops.",
121
+ "series.mark": "the mark price of {market}",
122
+ "series.funding_rate": "the funding rate of {market} (a fraction per day)",
123
+ "series.funding_rate_avg_15m": "the 15-minute average funding rate of {market} (a fraction per day)",
124
+ "series.funding_paid": "the cumulative funding per unit of {market}",
125
+ "series.volume": "the volume of {market}",
126
+ "series.open_interest": "the open interest of {market}",
127
+ "series.spread": "the spread of {market}",
128
+ "series.depth": "the depth of {market}",
129
+ "series.trades": "the trades of {market}",
130
+ "row.reading": "the row's series {n}",
131
+ "input.balance": "the balance",
132
+ "input.position": "the account's signed position on {market}",
133
+ "input.position.paper": "this Paper run's signed position on {market}",
134
+ "input.entry": "the entry price on {market}",
135
+ "input.rounds": "the current round number {loop}",
136
+ "input.wins": "the winning rounds {loop}",
137
+ "input.losses": "the losing rounds {loop}",
138
+ "input.consecutive_losses": "the losing rounds in a row on {market}",
139
+ "input.last_round_pnl": "the last round's P&L on {market}",
140
+ "input.pnl": "the P&L on {market}",
141
+ "input.pnl.total": "the total P&L",
142
+ "input.high_since_state_entry": "the high of {market} since entering the state",
143
+ "input.low_since_state_entry": "the low of {market} since entering the state",
144
+ "input.remembered": "{of} as it was {anchor}",
145
+ "input.remembered.start": "at Start",
146
+ "input.remembered.state_entry": "on entering the state",
147
+ "input.remembered.any": "when remembered",
148
+ "input.loop": "in {state}",
149
+ "input.loop.innermost": "in this loop",
150
+ "op.add": "{a} + {b}",
151
+ "op.sub": "{a} − {b}",
152
+ "op.mul": "{a} × {b}",
153
+ "op.div": "{a} ÷ {b}",
154
+ "op.neg": "−{a}",
155
+ "op.gt": "{a} is above {b}",
156
+ "op.ge": "{a} is at or above {b}",
157
+ "op.lt": "{a} is below {b}",
158
+ "op.le": "{a} is at or below {b}",
159
+ "op.eq": "{a} equals {b}",
160
+ "op.ne": "{a} is not {b}",
161
+ "op.and": "{a} and {b}",
162
+ "op.or": "{a} or {b}",
163
+ "op.not": "not ({a})",
164
+ "op.raw": "{op} of ({args})",
165
+ "group": "({x})",
166
+ "fn.args.join": ", ",
167
+ "fn.window": " over {dur}",
168
+ "fn.period": ", period {period}",
169
+ "fn.ago": " {dur} ago",
170
+ "fn.bars.60": ", on 1-minute bars",
171
+ "fn.bars.3600": ", on hourly bars",
172
+ "fn.bars.86400": ", on daily bars",
173
+ "fn.anchor.rolling": ", rolling",
174
+ "fn.anchor.utc_midnight": ", since UTC midnight",
175
+ "fn.anchor.state_entry": ", since entering the state",
176
+ "fn.sma": "the average of {args}{window}{period}{ago}{bars}{anchor}",
177
+ "fn.ema": "the exponential average of {args}{window}{period}{ago}{bars}{anchor}",
178
+ "fn.high": "the high of {args}{window}{period}{ago}{bars}{anchor}",
179
+ "fn.low": "the low of {args}{window}{period}{ago}{bars}{anchor}",
180
+ "fn.stdev": "the standard deviation of {args}{window}{period}{ago}{bars}{anchor}",
181
+ "fn.pct_change": "the change of {args}{window}{period}{ago}{bars}{anchor}, as a fraction (0.05 is 5%)",
182
+ "fn.corr": "the correlation of {args}{window}{period}{ago}{bars}{anchor}",
183
+ "fn.value_ago": "the value of {args}{window}{period}{ago}{bars}{anchor}",
184
+ "fn.rsi": "the RSI of {args}{window}{period}{ago}{bars}{anchor}",
185
+ "fn.atr": "the ATR of {args}{window}{period}{ago}{bars}{anchor}",
186
+ "fn.n_of_m": "at least {n} of ({conds}){window}{period}{ago}{bars}{anchor}",
187
+ "fn.if_else": "({then} if {cond}, else {otherwise}){window}{period}{ago}{bars}{anchor}",
188
+ "fn.count_in_state": "the count in the state of {args}{window}{period}{ago}{bars}{anchor}",
189
+ "fn.sum": "the sum of {args}{window}{period}{ago}{bars}{anchor}",
190
+ "fn.any": "whether any of {args} holds{window}{period}{ago}{bars}{anchor}",
191
+ "fn.max_over": "the highest of {args}{window}{period}{ago}{bars}{anchor}",
192
+ "fn.min_over": "the lowest of {args}{window}{period}{ago}{bars}{anchor}",
193
+ "day.mon": "Monday",
194
+ "day.tue": "Tuesday",
195
+ "day.wed": "Wednesday",
196
+ "day.thu": "Thursday",
197
+ "day.fri": "Friday",
198
+ "day.sat": "Saturday",
199
+ "day.sun": "Sunday",
200
+ "dur.week.one": "1 week",
201
+ "dur.week.other": "{n} weeks",
202
+ "dur.day.one": "1 day",
203
+ "dur.day.other": "{n} days",
204
+ "dur.hour.one": "1 hour",
205
+ "dur.hour.other": "{n} hours",
206
+ "dur.minute.one": "1 minute",
207
+ "dur.minute.other": "{n} minutes",
208
+ "dur.second.one": "1 second",
209
+ "dur.second.other": "{n} seconds",
210
+ "list.join": ", ",
211
+ "time.unix": "unix time {secs}"
212
+ }
package/dist/hash.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The canonical text of a v3 document (RFC 8785 for the JSON v3 allows: ASCII keys, safe integers,
3
+ * no floats): keys sorted by UTF-16 code unit, no whitespace, leaves written by `JSON.stringify`.
4
+ */
5
+ export declare function canonical(value: unknown): string;
6
+ /** `keccak256(UTF-8(canonical(doc)))`, `0x` and 64 lower-case hex digits: what Start signs. */
7
+ export declare function versionHash(doc: unknown): string;
8
+ export declare const keccakHex: (bytes: Uint8Array) => string;
package/dist/hash.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keccakHex = exports.versionHash = exports.canonical = void 0;
4
+ const sha3_1 = require("@noble/hashes/sha3");
5
+ const utils_1 = require("@noble/hashes/utils");
6
+ /**
7
+ * The canonical text of a v3 document (RFC 8785 for the JSON v3 allows: ASCII keys, safe integers,
8
+ * no floats): keys sorted by UTF-16 code unit, no whitespace, leaves written by `JSON.stringify`.
9
+ */
10
+ function canonical(value) {
11
+ if (Array.isArray(value))
12
+ return `[${value.map(canonical).join(',')}]`;
13
+ if (value !== null && typeof value === 'object') {
14
+ const entries = Object.entries(value)
15
+ .filter(([, v]) => v !== undefined)
16
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
17
+ return `{${entries
18
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
19
+ .join(',')}}`;
20
+ }
21
+ return JSON.stringify(value);
22
+ }
23
+ exports.canonical = canonical;
24
+ /** `keccak256(UTF-8(canonical(doc)))`, `0x` and 64 lower-case hex digits: what Start signs. */
25
+ function versionHash(doc) {
26
+ return (0, exports.keccakHex)(new TextEncoder().encode(canonical(doc)));
27
+ }
28
+ exports.versionHash = versionHash;
29
+ const keccakHex = (bytes) => `0x${(0, utils_1.bytesToHex)((0, sha3_1.keccak_256)(bytes))}`;
30
+ exports.keccakHex = keccakHex;