bytx-trader 0.1.0__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.
@@ -0,0 +1,2 @@
1
+ """bytx-trader: crypto trading steps for AI assistants on bytx."""
2
+ __version__ = "0.1.0"
bytx_trader/cli.py ADDED
@@ -0,0 +1,75 @@
1
+ """bytx-trader <step> — the same functions the MCP server exposes, for scripts, cron and manual checks."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import inspect
7
+ import json
8
+ import sys
9
+
10
+ from bytx.errors import BytxError
11
+
12
+ from . import market, trade
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ p = argparse.ArgumentParser(prog='bytx-trader', description='Crypto trading steps on bytx. Paper by default.')
17
+ p.add_argument('--json', action='store_true', help='print the full JSON result')
18
+ sub = p.add_subparsers(dest='cmd', required=True)
19
+ s = sub.add_parser('scan', help='setups across the top perps')
20
+ s.add_argument('--top', type=int)
21
+ s.add_argument('symbols', nargs='*')
22
+ sub.add_parser('derivs', help='funding, open interest, basis').add_argument('symbols', nargs='*')
23
+ sub.add_parser('entry', help='waiting / triggered / expired').add_argument('symbol')
24
+ s = sub.add_parser('exit', help='stop and target before you enter -> plan.json')
25
+ s.add_argument('symbol')
26
+ s.add_argument('--stop', default='range-mid', help='range-mid | range | atr:K | a price')
27
+ s.add_argument('--target-r', type=float, default=2.0)
28
+ s.add_argument('--side', choices=['long', 'short'])
29
+ s.add_argument('--entry', type=float)
30
+ s = sub.add_parser('timemachine', help='replay the rest of the session many times')
31
+ s.add_argument('--days', type=int, default=30)
32
+ s.add_argument('--runs', type=int, default=10_000)
33
+ s.add_argument('--seed', type=int, default=19)
34
+ s = sub.add_parser('size', help='size from risk -> orders.json')
35
+ s.add_argument('--risk-usdt', type=float)
36
+ s.add_argument('--leverage', type=float)
37
+ sub.add_parser('risk', help='PASS / BLOCK per ticket')
38
+ sub.add_parser('show', help='tickets, READY or not')
39
+ sub.add_parser('execute', help='get a one-time confirm token (sends nothing)').add_argument('index', type=int, nargs='?', default=1)
40
+ s = sub.add_parser('confirm', help="send the ticket after the user's yes")
41
+ s.add_argument('token')
42
+ s.add_argument('reply', help="the user's reply, word for word")
43
+ sub.add_parser('flatten', help='close tickets for open positions').add_argument('symbol', nargs='?')
44
+ sub.add_parser('positions', help='recorded positions, marked to market')
45
+ sub.add_parser('reconcile', help='find an order of unknown outcome by client_id').add_argument('client_id')
46
+ a = p.parse_args(argv)
47
+
48
+ calls = {
49
+ 'scan': lambda: market.scan(a.top, a.symbols or None),
50
+ 'derivs': lambda: market.derivs(a.symbols or None),
51
+ 'entry': lambda: market.entry_check(a.symbol),
52
+ 'exit': lambda: market.exit_plan(a.symbol, a.stop, a.target_r, a.side, a.entry),
53
+ 'timemachine': lambda: market.timemachine(a.days, a.runs, a.seed),
54
+ 'size': lambda: trade.size(a.risk_usdt, a.leverage),
55
+ 'risk': trade.risk_check,
56
+ 'show': trade.tickets_show,
57
+ 'execute': lambda: trade.execute(a.index),
58
+ 'confirm': lambda: trade.confirm(a.token, a.reply),
59
+ 'flatten': lambda: trade.flatten(a.symbol),
60
+ 'positions': trade.positions,
61
+ 'reconcile': lambda: trade.reconcile(a.client_id),
62
+ }
63
+ try:
64
+ res = calls[a.cmd]()
65
+ if inspect.isawaitable(res):
66
+ res = asyncio.run(res)
67
+ except (ValueError, PermissionError, RuntimeError, BytxError) as e:
68
+ print(f'{type(e).__name__}: {e}', file=sys.stderr)
69
+ return 2
70
+ print(json.dumps(res, indent=2, ensure_ascii=False, default=str) if a.json else res['text'])
71
+ return 0
72
+
73
+
74
+ if __name__ == '__main__':
75
+ sys.exit(main())
bytx_trader/core.py ADDED
@@ -0,0 +1,138 @@
1
+ """Shared plumbing: the crypto/ folder, config, JSON state, exchanges and the session clock."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import json
6
+ import os
7
+ import time
8
+ from datetime import datetime, timedelta, timezone
9
+ from pathlib import Path
10
+ from typing import Any, Optional
11
+
12
+ DEFAULT_CONFIG: dict = {
13
+ 'mode': 'paper', # paper | demo | real (real is not executed by this package, see broker)
14
+ 'allow_real': False,
15
+ 'exchange': 'binance',
16
+ 'account_usdt': 1000, # paper balance and the cash check
17
+ 'default_leverage': 5,
18
+ 'session': { # all times UTC; crypto trades 24/7, so the "session" is yours to pick
19
+ 'start': '00:00',
20
+ 'range_minutes': 60,
21
+ 'timeframe': '5m',
22
+ 'entry_until': None, # "HH:MM" to stop new entries after it
23
+ 'flat_by': '23:55',
24
+ },
25
+ 'risk': {
26
+ 'max_loss_per_trade': 10,
27
+ 'daily_loss_limit': 30,
28
+ 'max_trades_per_day': 3,
29
+ 'min_rr': 1.5,
30
+ 'max_leverage': 5,
31
+ 'max_notional': 5000,
32
+ 'blocked_symbols': [],
33
+ },
34
+ 'scanner': {'top': 30},
35
+ }
36
+
37
+
38
+ def home() -> Path:
39
+ """The crypto/ folder every step reads from and writes to."""
40
+ return Path(os.environ.get('BYTX_TRADER_HOME') or Path.cwd() / 'crypto')
41
+
42
+
43
+ def _merge(base: dict, over: dict) -> dict:
44
+ out = copy.deepcopy(base)
45
+ for k, v in over.items():
46
+ out[k] = _merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
47
+ return out
48
+
49
+
50
+ def load_config() -> dict:
51
+ p = home() / 'config.json'
52
+ return _merge(DEFAULT_CONFIG, json.loads(p.read_text())) if p.exists() else copy.deepcopy(DEFAULT_CONFIG)
53
+
54
+
55
+ def read(name: str, default: Any = None) -> Any:
56
+ p = home() / name
57
+ return json.loads(p.read_text()) if p.exists() else default
58
+
59
+
60
+ def write(name: str, data: Any) -> Path:
61
+ p = home() / name
62
+ p.parent.mkdir(parents=True, exist_ok=True)
63
+ tmp = p.with_suffix(p.suffix + '.tmp')
64
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False, default=str))
65
+ tmp.replace(p) # atomic: a crash never leaves half a state file
66
+ return p
67
+
68
+
69
+ # ─── time ────────────────────────────────────────────────────────────────
70
+
71
+ def now_ms() -> int:
72
+ return int(os.environ.get('BYTX_TRADER_NOW_MS') or time.time() * 1000) # env pins the clock for tests/replays
73
+
74
+
75
+ def tf_ms(timeframe: str) -> int:
76
+ units = {'m': 60_000, 'h': 3_600_000, 'd': 86_400_000}
77
+ return int(timeframe[:-1]) * units[timeframe[-1]]
78
+
79
+
80
+ def _hhmm(s: str) -> timedelta:
81
+ h, m = s.split(':')
82
+ return timedelta(hours=int(h), minutes=int(m))
83
+
84
+
85
+ def session_window(cfg: dict, at_ms: Optional[int] = None) -> dict:
86
+ """Current session in ms: start, range end, entry deadline, flat-by. A session lasts at most 24h."""
87
+ s = cfg['session']
88
+ at = datetime.fromtimestamp((at_ms or now_ms()) / 1000, timezone.utc)
89
+ start = at.replace(hour=0, minute=0, second=0, microsecond=0) + _hhmm(s['start'])
90
+ if start > at:
91
+ start -= timedelta(days=1)
92
+
93
+ def after_start(hhmm: str) -> int:
94
+ t = start.replace(hour=0, minute=0) + _hhmm(hhmm)
95
+ while t <= start:
96
+ t += timedelta(days=1)
97
+ return int(t.timestamp() * 1000)
98
+
99
+ start_ms = int(start.timestamp() * 1000)
100
+ flat = after_start(s['flat_by'])
101
+ return {
102
+ 'start': start_ms,
103
+ 'range_end': start_ms + s['range_minutes'] * 60_000,
104
+ 'entry_until': after_start(s['entry_until']) if s.get('entry_until') else flat,
105
+ 'flat_by': flat,
106
+ }
107
+
108
+
109
+ def iso(ms: Optional[int]) -> Optional[str]:
110
+ return None if ms is None else datetime.fromtimestamp(ms / 1000, timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
111
+
112
+
113
+ # ─── exchanges ───────────────────────────────────────────────────────────
114
+
115
+ def _create(name: str, **kw: Any) -> Any:
116
+ from bytx import create_exchange
117
+ return create_exchange(name, **kw)
118
+
119
+
120
+ # Tests replace this with a bytx.testing emulator, so callers use core.open_exchange(...), not a from-import.
121
+ def open_exchange(cfg: dict, kind: str) -> Any:
122
+ """kind: 'data' — public data, no keys; 'trade' — the account of cfg['mode']; 'spot' — public spot data."""
123
+ name = cfg['exchange']
124
+ if kind == 'data':
125
+ return _create(name)
126
+ if kind == 'spot':
127
+ return _create(name, market='spot')
128
+ mode = cfg['mode']
129
+ if mode == 'paper':
130
+ from bytx.paper import PaperConfig
131
+ return _create(name, paper=True, paper_config=PaperConfig(balance={'USDT': float(cfg['account_usdt'])}))
132
+ if mode == 'demo':
133
+ keys = {k: os.environ.get(f'BYTX_{k.upper()}') for k in ('api_key', 'secret', 'password')}
134
+ if not keys['api_key'] or not keys['secret']:
135
+ raise RuntimeError('demo mode needs BYTX_API_KEY and BYTX_SECRET (and BYTX_PASSWORD for OKX/KuCoin/Bitget) '
136
+ 'in the environment. Never paste keys into the chat.')
137
+ return _create(name, demo=True, **{k: v for k, v in keys.items() if v})
138
+ raise RuntimeError(f"mode {mode!r} is not executed by bytx-trader; real orders go through the hosted BYTtrade MCP")
bytx_trader/market.py ADDED
@@ -0,0 +1,350 @@
1
+ """Read-only steps: scanner, derivs, entry, exit plan, time machine. No orders anywhere in this module.
2
+
3
+ Candles inside are plain lists [ts, open, high, low, close, volume] so the pure functions run on fixtures.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import random
9
+ import statistics
10
+ from typing import Any, Optional
11
+
12
+ from . import core
13
+
14
+ Bar = list # [ts, o, h, l, c, v]
15
+
16
+
17
+ def bars(candles: list) -> list[Bar]:
18
+ return [[c.timestamp, c.open, c.high, c.low, c.close, c.volume] for c in candles]
19
+
20
+
21
+ def closed(bs: list[Bar], tf: int, now: int) -> list[Bar]:
22
+ return [b for b in bs if b[0] + tf <= now]
23
+
24
+
25
+ # ─── opening-range breakout, the setup the scanner, entry and time machine share ─
26
+
27
+ def orb_state(bs: list[Bar], win: dict, tf: int, now: int) -> dict:
28
+ """Range of the first minutes of the session, then the first closed bar beyond it.
29
+
30
+ status: forming (range not done) | waiting | triggered | expired (past the entry deadline, no trigger).
31
+ """
32
+ done = closed(bs, tf, now)
33
+ rng = [b for b in done if win['start'] <= b[0] < win['range_end']]
34
+ if now < win['range_end'] or not rng:
35
+ return {'status': 'forming'}
36
+ hi, lo = max(b[2] for b in rng), min(b[3] for b in rng)
37
+ out = {'range_high': hi, 'range_low': lo, 'range_mid': (hi + lo) / 2}
38
+ for b in done:
39
+ if b[0] < win['range_end'] or b[0] + tf > win['entry_until']:
40
+ continue
41
+ if b[4] > hi or b[4] < lo:
42
+ side = 'long' if b[4] > hi else 'short'
43
+ edge = hi if side == 'long' else lo
44
+ return {**out, 'status': 'triggered', 'side': side, 'trigger_ts': b[0], 'trigger_close': b[4],
45
+ 'beyond_pct': round(abs(b[4] / edge - 1) * 100, 3)}
46
+ return {**out, 'status': 'expired' if now > win['entry_until'] else 'waiting'}
47
+
48
+
49
+ def rsi(closes: list[float], n: int = 14) -> Optional[float]:
50
+ if len(closes) <= n:
51
+ return None
52
+ gains = losses = 0.0
53
+ for a, b in zip(closes[-n - 1:-1], closes[-n:]):
54
+ d = b - a
55
+ gains, losses = gains + max(d, 0), losses + max(-d, 0)
56
+ return 100.0 if losses == 0 else 100 - 100 / (1 + gains / losses)
57
+
58
+
59
+ def atr(bs: list[Bar], n: int = 14) -> Optional[float]:
60
+ if len(bs) <= n:
61
+ return None
62
+ trs = [max(b[2] - b[3], abs(b[2] - p[4]), abs(b[3] - p[4])) for p, b in zip(bs[-n - 1:-1], bs[-n:])]
63
+ return sum(trs) / n
64
+
65
+
66
+ # ─── 1. scanner ──────────────────────────────────────────────────────────
67
+
68
+ async def _session_bars(ex: Any, symbol: str, cfg: dict, win: dict) -> list[Bar]:
69
+ tf = cfg['session']['timeframe']
70
+ limit = (core.now_ms() - win['start']) // core.tf_ms(tf) + 20 # session + RSI warm-up
71
+ return bars(await ex.candles(symbol, tf, since=win['start'] - 20 * core.tf_ms(tf), limit=min(int(limit), 1000)))
72
+
73
+
74
+ async def scan(top: Optional[int] = None, symbols: Optional[list[str]] = None) -> dict:
75
+ cfg = core.load_config()
76
+ win, now, tf = core.session_window(cfg), core.now_ms(), core.tf_ms(cfg['session']['timeframe'])
77
+ async with core.open_exchange(cfg, 'data') as ex:
78
+ if not symbols:
79
+ tick = await ex.tickers()
80
+ usdt = [t for s, t in tick.items() if s.endswith('/USDT:USDT') and t.quote_volume]
81
+ symbols = [t.symbol for t in sorted(usdt, key=lambda t: -t.quote_volume)[:top or cfg['scanner']['top']]]
82
+ sem = asyncio.Semaphore(5) # be polite to the public endpoint
83
+
84
+ async def one(sym: str) -> dict:
85
+ async with sem:
86
+ try:
87
+ bs = await _session_bars(ex, sym, cfg, win)
88
+ except Exception as e: # one bad symbol must not sink the scan
89
+ return {'symbol': sym, 'error': f'{type(e).__name__}: {e}'}
90
+ st = orb_state(bs, win, tf, now)
91
+ r = rsi([b[4] for b in closed(bs, tf, now)])
92
+ setups = []
93
+ if st['status'] == 'triggered':
94
+ setups.append(f"orb_{st['side']}")
95
+ if r is not None and r < 30:
96
+ setups.append('oversold')
97
+ if r is not None and r > 70:
98
+ setups.append('overbought')
99
+ return {'symbol': sym, 'setups': setups, 'orb': st, 'rsi': None if r is None else round(r, 1)}
100
+
101
+ rows = await asyncio.gather(*(one(s) for s in symbols))
102
+ hits = sorted((r for r in rows if r.get('setups')), key=lambda r: -r['orb'].get('trigger_ts', 0)) # freshest first
103
+ out = {'exchange': cfg['exchange'], 'at': core.iso(now), 'session_start': core.iso(win['start']),
104
+ 'scanned': len(rows), 'hits': hits, 'errors': [r for r in rows if 'error' in r]}
105
+ core.write('scan.json', out)
106
+ lines = [f"{out['at']}: {len(hits)} of {len(rows)} {cfg['exchange']} perps have a setup"]
107
+ for h in hits[:20]:
108
+ o = h['orb']
109
+ extra = (f" at {core.iso(o['trigger_ts'])[11:]}, close {o['trigger_close']} ({o['beyond_pct']}% beyond the range)"
110
+ if o.get('status') == 'triggered' else '')
111
+ lines.append(f" {h['symbol']}: {', '.join(h['setups'])}{extra}, RSI {h['rsi']}")
112
+ out['text'] = '\n'.join(lines)
113
+ return out
114
+
115
+
116
+ # ─── 2. derivs: funding, open interest, basis ────────────────────────────
117
+
118
+ FUNDING_HOT = 0.0005 # 0.05 % per funding period: crowded side pays a lot to stay in
119
+
120
+
121
+ async def derivs(symbols: Optional[list[str]] = None) -> dict:
122
+ cfg = core.load_config()
123
+ symbols = symbols or core.read('watchlist.json') or [h['symbol'] for h in (core.read('scan.json') or {}).get('hits', [])][:10]
124
+ if not symbols:
125
+ raise ValueError('no symbols: pass them, write crypto/watchlist.json, or run the scanner first')
126
+ prev = (core.read('state/derivs.json') or {}).get('oi', {})
127
+ week_ago = core.now_ms() - 7 * 86_400_000
128
+ rows = []
129
+ async with core.open_exchange(cfg, 'data') as ex, core.open_exchange(cfg, 'spot') as spot:
130
+ for sym in symbols:
131
+ fr, oi, tk = await ex.funding_rate(sym), await ex.open_interest(sym), await ex.ticker(sym)
132
+ hist = await ex.funding_history(sym, since=week_ago)
133
+ try:
134
+ spot_px = (await spot.ticker(sym.split(':')[0])).last
135
+ except Exception:
136
+ spot_px = None # not every perp has a spot pair
137
+ key = fr.symbol
138
+ oi_chg = None
139
+ if oi.size and prev.get(key):
140
+ oi_chg = round((oi.size / prev[key] - 1) * 100, 2)
141
+ flags = []
142
+ if fr.rate is not None and fr.rate >= FUNDING_HOT:
143
+ flags.append('crowded_long')
144
+ if fr.rate is not None and fr.rate <= -FUNDING_HOT:
145
+ flags.append('crowded_short')
146
+ if oi_chg is not None and tk.change_pct is not None:
147
+ if oi_chg > 3 and tk.change_pct < -1:
148
+ flags.append('oi_up_price_down')
149
+ if oi_chg > 3 and tk.change_pct > 1:
150
+ flags.append('oi_up_price_up')
151
+ rows.append({
152
+ 'symbol': key, 'price': tk.last, 'change_24h_pct': tk.change_pct,
153
+ 'funding_rate': fr.rate, 'next_funding': core.iso(fr.next_funding_time),
154
+ 'funding_7d_avg': statistics.fmean([h.rate for h in hist]) if hist else None,
155
+ 'open_interest': oi.size, 'oi_change_pct_since_last_run': oi_chg,
156
+ 'basis_pct': round((tk.last / spot_px - 1) * 100, 4) if spot_px and tk.last else None,
157
+ 'flags': flags,
158
+ })
159
+ core.write('state/derivs.json', {'at': core.now_ms(), 'oi': {r['symbol']: r['open_interest'] for r in rows}})
160
+ out = {'at': core.iso(core.now_ms()), 'rows': rows}
161
+ core.write('derivs.json', out)
162
+ out['text'] = '\n'.join(
163
+ f"{r['symbol']}: funding {_pct(r['funding_rate'])} (7d avg {_pct(r['funding_7d_avg'])}), "
164
+ f"OI {r['open_interest']} ({'first run' if r['oi_change_pct_since_last_run'] is None else str(r['oi_change_pct_since_last_run']) + '%'}), "
165
+ f"basis {r['basis_pct']}%{', ' + ', '.join(r['flags']) if r['flags'] else ''}" for r in rows)
166
+ return out
167
+
168
+
169
+ def _pct(x: Optional[float]) -> str:
170
+ return 'n/a' if x is None else f'{x * 100:.4f}%'
171
+
172
+
173
+ # ─── 3. entry ────────────────────────────────────────────────────────────
174
+
175
+ async def entry_check(symbol: str) -> dict:
176
+ cfg = core.load_config()
177
+ win, now, tf = core.session_window(cfg), core.now_ms(), core.tf_ms(cfg['session']['timeframe'])
178
+ async with core.open_exchange(cfg, 'data') as ex:
179
+ sym = (await ex.market(symbol)).symbol
180
+ st = orb_state(await _session_bars(ex, sym, cfg, win), win, tf, now)
181
+ out = {'symbol': sym, 'at': core.iso(now), **st}
182
+ entry = core.read('entry.json') or {}
183
+ entry[sym] = out
184
+ core.write('entry.json', entry)
185
+ if st['status'] == 'triggered':
186
+ out['text'] = (f"{sym}: TRIGGERED {st['side']} — the {core.iso(st['trigger_ts'])} bar closed at "
187
+ f"{st['trigger_close']}, {st['beyond_pct']}% beyond the range {st['range_low']}–{st['range_high']}")
188
+ elif st['status'] == 'forming':
189
+ out['text'] = f"{sym}: the opening range is still forming (ends {core.iso(win['range_end'])})"
190
+ else:
191
+ out['text'] = (f"{sym}: {st['status'].upper()} — range {st['range_low']}–{st['range_high']}, "
192
+ f"entries until {core.iso(win['entry_until'])}")
193
+ return out
194
+
195
+
196
+ # ─── 4. exit plan ────────────────────────────────────────────────────────
197
+
198
+ def stop_from(method: str, side: str, entry: float, orb: dict, atr_value: Optional[float]) -> float:
199
+ """method: range-mid | range (the far edge) | atr:K | a price."""
200
+ sign = -1 if side == 'long' else 1
201
+ if method == 'range-mid':
202
+ return orb['range_mid']
203
+ if method == 'range':
204
+ return orb['range_low'] if side == 'long' else orb['range_high']
205
+ if method.startswith('atr'):
206
+ k = float(method.split(':')[1]) if ':' in method else 1.5
207
+ if not atr_value:
208
+ raise ValueError('not enough bars for ATR')
209
+ return entry + sign * k * atr_value
210
+ return float(method)
211
+
212
+
213
+ async def exit_plan(symbol: str, stop: str = 'range-mid', target_r: float = 2.0, side: Optional[str] = None,
214
+ entry: Optional[float] = None) -> dict:
215
+ cfg = core.load_config()
216
+ win, tf = core.session_window(cfg), core.tf_ms(cfg['session']['timeframe'])
217
+ async with core.open_exchange(cfg, 'data') as ex:
218
+ sym = (await ex.market(symbol)).symbol
219
+ bs = await _session_bars(ex, sym, cfg, win)
220
+ last = (await ex.ticker(sym)).last
221
+ orb = (core.read('entry.json') or {}).get(sym) or orb_state(bs, win, tf, core.now_ms())
222
+ side = side or orb.get('side')
223
+ if side not in ('long', 'short'):
224
+ raise ValueError('no side: the entry has not triggered; pass side=long|short')
225
+ fresh = orb.get('side') == side and core.now_ms() - orb.get('trigger_ts', 0) <= 3 * tf # trigger bar just closed
226
+ entry = entry or (orb['trigger_close'] if fresh else last) # a stale trigger is planned from the price now
227
+ if stop in ('range-mid', 'range') and 'range_mid' not in orb:
228
+ raise ValueError('the opening range is not formed yet; use stop=atr:K or a price')
229
+ stop_px = stop_from(stop, side, entry, orb, atr(closed(bs, tf, core.now_ms())))
230
+ risk = entry - stop_px if side == 'long' else stop_px - entry
231
+ if risk <= 0:
232
+ raise ValueError(f'stop {stop_px} is on the wrong side of entry {entry} for a {side}')
233
+ tp = entry + target_r * risk if side == 'long' else entry - target_r * risk
234
+ plan = {'symbol': sym, 'side': side, 'entry': entry, 'stop': stop_px, 'take_profit': tp,
235
+ 'stop_method': stop, 'target_r': target_r, 'risk_per_unit': risk,
236
+ 'risk_pct': round(risk / entry * 100, 3), 'flat_by': win['flat_by'], 'flat_by_utc': core.iso(win['flat_by']),
237
+ 'created': core.now_ms()}
238
+ core.write('plan.json', plan)
239
+ plan['text'] = (f"{sym} {side}: entry ~{entry}, stop {stop_px:.6g} ({plan['risk_pct']}% away, {stop}), "
240
+ f"target {tp:.6g} ({target_r}R), flat by {plan['flat_by_utc']} either way")
241
+ return plan
242
+
243
+
244
+ # ─── 5. time machine ─────────────────────────────────────────────────────
245
+
246
+ def _outcome(side: str, path: list[Bar], stop: float, tp: float) -> str:
247
+ for b in path:
248
+ hit_stop = b[3] <= stop if side == 'long' else b[2] >= stop
249
+ hit_tp = b[2] >= tp if side == 'long' else b[3] <= tp
250
+ if hit_stop: # both in one bar: assume the stop came first (conservative)
251
+ return 'stop'
252
+ if hit_tp:
253
+ return 'target'
254
+ return 'open'
255
+
256
+
257
+ def by_day(bs: list[Bar], start_ms: int) -> dict[int, list[Bar]]:
258
+ """Group bars into sessions keyed by session start (same time of day as start_ms)."""
259
+ days: dict[int, list[Bar]] = {}
260
+ for b in bs:
261
+ k = start_ms + ((b[0] - start_ms) // 86_400_000) * 86_400_000
262
+ days.setdefault(k, []).append(b)
263
+ return days
264
+
265
+
266
+ def monte_carlo(days: dict[int, list[Bar]], tf: int, entry_slot: int, end_slot: int, side: str, entry: float,
267
+ stop: float, tp: float, n: int = 10_000, seed: int = 19) -> dict:
268
+ """Rest of the session n times: each bar drawn from the same time-of-day bar of a random past session."""
269
+ slots: dict[int, list[tuple]] = {}
270
+ for d, bs in days.items():
271
+ for b in bs:
272
+ if b[1] > 0:
273
+ slots.setdefault(int((b[0] - d) // tf), []).append((b[2] / b[1], b[3] / b[1], b[4] / b[1]))
274
+ rng = random.Random(seed)
275
+ counts = {'target': 0, 'stop': 0, 'open': 0}
276
+ open_r = []
277
+ risk = abs(entry - stop)
278
+ for _ in range(n):
279
+ px, res = entry, 'open'
280
+ for s in range(entry_slot + 1, end_slot):
281
+ if s not in slots:
282
+ continue
283
+ h, lo, c = rng.choice(slots[s])
284
+ res = _outcome(side, [[0, px, px * h, px * lo, px * c, 0]], stop, tp)
285
+ if res != 'open':
286
+ break
287
+ px *= c
288
+ counts[res] += 1
289
+ if res == 'open':
290
+ open_r.append(((px - entry) if side == 'long' else (entry - px)) / risk)
291
+ return {k: round(v / n * 100, 1) for k, v in counts.items()} | {
292
+ 'open_avg_r': round(statistics.fmean(open_r), 2) if open_r else None, 'runs': n, 'seed': seed,
293
+ 'sessions': len(days)}
294
+
295
+
296
+ def replay_rule(days: dict[int, list[Bar]], cfg: dict, tf: int, stop_method: str, target_r: float) -> dict:
297
+ """The same rule on every past session: did it fire, and which came first."""
298
+ res = {'fired': 0, 'target': 0, 'stop': 0, 'open': 0}
299
+ for d, bs in sorted(days.items()):
300
+ win = core.session_window(cfg, d)
301
+ st = orb_state(bs, win, tf, win['flat_by'] + tf)
302
+ if st['status'] != 'triggered':
303
+ continue
304
+ side, entry = st['side'], st['trigger_close']
305
+ try:
306
+ stop = stop_from(stop_method, side, entry, st, atr([b for b in bs if b[0] <= st['trigger_ts']]))
307
+ except ValueError:
308
+ continue
309
+ risk = entry - stop if side == 'long' else stop - entry
310
+ if risk <= 0:
311
+ continue
312
+ tp = entry + target_r * risk if side == 'long' else entry - target_r * risk
313
+ path = [b for b in bs if st['trigger_ts'] < b[0] and b[0] + tf <= win['flat_by']]
314
+ res['fired'] += 1
315
+ res[_outcome(side, path, stop, tp)] += 1
316
+ return res
317
+
318
+
319
+ async def timemachine(days: int = 30, runs: int = 10_000, seed: int = 19) -> dict:
320
+ cfg = core.load_config()
321
+ plan = core.read('plan.json')
322
+ if not plan:
323
+ raise ValueError('no crypto/plan.json: run the exit planner first')
324
+ tf_s = cfg['session']['timeframe']
325
+ tf, now = core.tf_ms(tf_s), core.now_ms()
326
+ win = core.session_window(cfg)
327
+ async with core.open_exchange(cfg, 'data') as ex:
328
+ h = await ex.history.candles(plan['symbol'], tf_s, since=win['start'] - days * 86_400_000, until=win['start'])
329
+ past = by_day(bars(h.rows), win['start'])
330
+ stop_method = plan['stop_method'] if plan['stop_method'] in ('range-mid', 'range') or plan['stop_method'].startswith('atr') else 'atr:1.5'
331
+ mc = monte_carlo(past, tf, int((min(now, win['flat_by']) - win['start']) // tf), int((win['flat_by'] - win['start']) // tf),
332
+ plan['side'], plan['entry'], plan['stop'], plan['take_profit'], runs, seed)
333
+ hist = replay_rule(past, cfg, tf, stop_method, plan['target_r'])
334
+ out = {'symbol': plan['symbol'], 'monte_carlo': mc, 'history': hist, 'history_stop_method': stop_method}
335
+ st = core.read('state/timemachine.json') or {}
336
+ st[plan['symbol']] = out
337
+ core.write('state/timemachine.json', st)
338
+ # expectancy in R before fees: target pays target_r, stop costs 1, neither counted as 0 (mc gives its avg)
339
+ mc_r = (mc['target'] * plan['target_r'] - mc['stop'] + mc['open'] * (mc['open_avg_r'] or 0)) / 100
340
+ hist_r = (hist['target'] * plan['target_r'] - hist['stop']) / hist['fired'] if hist['fired'] else None
341
+ out['expectancy_r'] = {'monte_carlo': round(mc_r, 2), 'history': None if hist_r is None else round(hist_r, 2)}
342
+ signs = {x > 0 for x in (mc_r, hist_r) if x is not None and abs(x) >= 0.2} # under 0.2R is noise
343
+ verdict = ('close to a coin flip' if not signs else 'mixed: the two disagree' if len(signs) > 1
344
+ else 'leans your way' if True in signs else 'leans against you')
345
+ out['text'] = (f"{plan['symbol']} {plan['side']}, {runs} replays of the rest of the session from {mc['sessions']} past sessions "
346
+ f"(seed {seed}): target first {mc['target']}%, stop first {mc['stop']}%, still open {mc['open']}%.\n"
347
+ f"Same rule on those sessions: fired {hist['fired']}x — target {hist['target']}, stop {hist['stop']}, "
348
+ f"neither {hist['open']}. Expectancy before fees: {out['expectancy_r']['monte_carlo']}R simulated, "
349
+ f"{out['expectancy_r']['history']}R historical. Verdict: {verdict}. A simulation, not a prediction.")
350
+ return out
@@ -0,0 +1,130 @@
1
+ """bytx-trader-mcp: the steps as MCP tools for any MCP client (stdio). The order gates are in trade.py."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional
5
+
6
+ try: # mcp 2.x renamed FastMCP to MCPServer; keep both working
7
+ from mcp.server.mcpserver import MCPServer as Server
8
+ except ImportError: # mcp 1.x
9
+ from mcp.server.fastmcp import FastMCP as Server
10
+
11
+ from . import market, trade, updates
12
+
13
+ _pending = {'notice': None} # set once at start, shown with the first tool result
14
+
15
+
16
+ def _note(res: dict) -> dict:
17
+ msg, _pending['notice'] = _pending['notice'], None
18
+ return {**res, 'update_notice': msg, 'text': f"{msg}\n\n{res['text']}"} if msg else res
19
+
20
+ mcp = Server('bytx-trader', instructions=(
21
+ 'Crypto trading steps on the bytx library. Paper trading by default (live order book, virtual money). '
22
+ 'One trade: scan -> derivs -> entry_check -> exit_plan -> timemachine -> size -> risk_check -> execute -> confirm. '
23
+ 'execute sends nothing: show its ticket to the user and wait for their reply; call confirm only with the '
24
+ "user's own reply word for word. Never invent a yes. Not financial advice."))
25
+
26
+
27
+ @mcp.tool()
28
+ async def scan(top: Optional[int] = None, symbols: Optional[list[str]] = None) -> dict:
29
+ """Scan the top perpetuals by 24h volume (or given symbols) for setups: opening-range breakout of the session,
30
+ RSI oversold/overbought. Writes crypto/scan.json."""
31
+ return _note(await market.scan(top, symbols))
32
+
33
+
34
+ @mcp.tool()
35
+ async def derivs(symbols: Optional[list[str]] = None) -> dict:
36
+ """Funding rate (now and 7-day average), open interest and its change since the last run, perp/spot basis,
37
+ with flags like crowded_long / oi_up_price_down. Defaults to crypto/watchlist.json or the scanner's hits."""
38
+ return _note(await market.derivs(symbols))
39
+
40
+
41
+ @mcp.tool()
42
+ async def entry_check(symbol: str) -> dict:
43
+ """Is the opening-range breakout on: waiting, triggered (first closed bar beyond the range), expired or forming."""
44
+ return _note(await market.entry_check(symbol))
45
+
46
+
47
+ @mcp.tool()
48
+ async def exit_plan(symbol: str, stop: str = 'range-mid', target_r: float = 2.0, side: Optional[str] = None,
49
+ entry: Optional[float] = None) -> dict:
50
+ """Stop and target before entering. stop: range-mid | range | atr:K | a price; target in R multiples;
51
+ flat-by time from the session config. Writes crypto/plan.json."""
52
+ return _note(await market.exit_plan(symbol, stop, target_r, side, entry))
53
+
54
+
55
+ @mcp.tool()
56
+ async def timemachine(days: int = 30, runs: int = 10_000, seed: int = 19) -> dict:
57
+ """Replay the rest of the session `runs` times from the symbol's own past bars at the same time of day, and
58
+ re-run the same rule on each past session. Odds of target/stop/neither. A simulation, not a prediction."""
59
+ return _note(await market.timemachine(days, runs, seed))
60
+
61
+
62
+ @mcp.tool()
63
+ async def size(risk_usdt: Optional[float] = None, leverage: Optional[float] = None) -> dict:
64
+ """Position size from the money at risk and the plan's stop (fees included), margin, liquidation estimate,
65
+ funding cost. Places nothing. Writes the ticket to crypto/orders.json."""
66
+ return _note(await trade.size(risk_usdt, leverage))
67
+
68
+
69
+ @mcp.tool()
70
+ def risk_check() -> dict:
71
+ """PASS or BLOCK every ticket against the user's limits (loss per trade, daily limit, trades per day,
72
+ reward:risk, leverage, notional, liquidation vs stop, entry window, duplicates, mode)."""
73
+ return _note(trade.risk_check())
74
+
75
+
76
+ @mcp.tool()
77
+ def tickets_show() -> dict:
78
+ """The tickets in plain words, READY (passed the risk check today) or not."""
79
+ return _note(trade.tickets_show())
80
+
81
+
82
+ @mcp.tool()
83
+ def execute(index: int = 1) -> dict:
84
+ """Prepare ticket #index for sending. SENDS NOTHING: returns the ticket and a one-time confirm_token (5 min).
85
+ Show the ticket to the user and ask yes or no for exactly this order."""
86
+ return _note(trade.execute(index))
87
+
88
+
89
+ @mcp.tool()
90
+ async def confirm(confirm_token: str, user_reply: str) -> dict:
91
+ """Send the ticket of confirm_token. user_reply must be the user's own message word for word; anything but a
92
+ plain yes cancels. The risk check runs again. Paper and demo only; real orders go through the hosted BYTtrade MCP."""
93
+ return _note(await trade.confirm(confirm_token, user_reply))
94
+
95
+
96
+ @mcp.tool()
97
+ def flatten(symbol: Optional[str] = None) -> dict:
98
+ """Write close tickets for the open positions (all or one symbol). They still need execute + confirm."""
99
+ return _note(trade.flatten(symbol))
100
+
101
+
102
+ @mcp.tool()
103
+ async def positions() -> dict:
104
+ """Positions opened through this server, marked to market, with stop/target/flat-by warnings."""
105
+ return _note(await trade.positions())
106
+
107
+
108
+ @mcp.tool()
109
+ async def reconcile(client_id: str) -> dict:
110
+ """Look up an order whose outcome was unknown (timeout) by its client_id. Never resends it."""
111
+ return _note(await trade.reconcile(client_id))
112
+
113
+
114
+ @mcp.prompt()
115
+ def trade_pipeline(symbol: str = '') -> str:
116
+ """The whole trade, step by step, with the user deciding at every gate."""
117
+ target = f' on {symbol}' if symbol else ''
118
+ return (f'Walk me through one trade{target} with the bytx-trader tools. 1) scan (skip if I named a symbol) '
119
+ '2) derivs for the candidates 3) entry_check 4) exit_plan 5) timemachine and tell me the odds plainly '
120
+ '6) size 7) risk_check — stop on BLOCK and tell me why 8) execute, show me the ticket and wait for my '
121
+ 'answer 9) confirm only with my exact reply. Say which mode (paper/demo) we are in at every step.')
122
+
123
+
124
+ def main() -> None:
125
+ _pending['notice'] = updates.notice()
126
+ mcp.run()
127
+
128
+
129
+ if __name__ == '__main__':
130
+ main()
bytx_trader/trade.py ADDED
@@ -0,0 +1,317 @@
1
+ """Steps that lead to an order: size, risk, broker. The gates live here, not in any SKILL.md.
2
+
3
+ An order is sent only by confirm(), and only when: the risk check passed this exact ticket today,
4
+ execute() issued a one-time token for it, and the user's own reply is a plain yes.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import re
11
+ import secrets
12
+ from datetime import datetime, timezone
13
+ from typing import Any, Optional
14
+
15
+ from . import core
16
+
17
+ TOKEN_TTL_MS = 300_000
18
+ FINGERPRINT_KEYS = ('kind', 'symbol', 'side', 'risk_usdt', 'stop', 'take_profit', 'leverage', 'mode', 'size')
19
+
20
+
21
+ def fingerprint(t: dict) -> str:
22
+ return hashlib.sha256(json.dumps({k: t.get(k) for k in FINGERPRINT_KEYS}, sort_keys=True).encode()).hexdigest()[:16]
23
+
24
+
25
+ def _today(ms: Optional[int] = None) -> str:
26
+ return datetime.fromtimestamp((ms or core.now_ms()) / 1000, timezone.utc).strftime('%Y-%m-%d')
27
+
28
+
29
+ # ─── 6. size ─────────────────────────────────────────────────────────────
30
+
31
+ async def size(risk_usdt: Optional[float] = None, leverage: Optional[float] = None) -> dict:
32
+ """Size from risk with bytx.risk_size on a paper account (no keys, no orders); writes crypto/orders.json."""
33
+ cfg = core.load_config()
34
+ plan = core.read('plan.json')
35
+ if not plan:
36
+ raise ValueError('no crypto/plan.json: run the exit planner first')
37
+ risk_usdt = float(risk_usdt or cfg['risk']['max_loss_per_trade'])
38
+ leverage = float(leverage or cfg['default_leverage'])
39
+ async with core.open_exchange({**cfg, 'mode': 'paper'}, 'trade') as ex:
40
+ rp = await ex.risk_size(plan['symbol'], plan['side'], risk_usdt=risk_usdt, stop=plan['stop'],
41
+ take_profit=plan['take_profit'], leverage=leverage)
42
+ async with core.open_exchange(cfg, 'data') as ex:
43
+ fr = await ex.funding_rate(plan['symbol'])
44
+ t = {'kind': 'open', 'symbol': rp.symbol, 'side': plan['side'], 'risk_usdt': risk_usdt, 'stop': rp.stop_price,
45
+ 'take_profit': rp.take_profit, 'leverage': leverage, 'mode': cfg['mode'],
46
+ 'entry_est': rp.entry_price, 'size_est': rp.size, 'notional_est': rp.notional, 'margin_est': rp.margin,
47
+ 'liquidation_est': rp.liquidation_price, 'loss_at_stop_est': rp.risk, 'fees_est': rp.fees,
48
+ 'funding_rate': fr.rate, 'funding_per_period_est': None if fr.rate is None else rp.notional * fr.rate,
49
+ 'flat_by': plan.get('flat_by'), 'created': core.now_ms()}
50
+ t['id'] = fingerprint(t)
51
+ core.write('orders.json', [t])
52
+ t['text'] = ticket_text(t)
53
+ return t
54
+
55
+
56
+ def ticket_text(t: dict) -> str:
57
+ if t['kind'] == 'close':
58
+ return f"[{t['mode'].upper()}] CLOSE {t['side']} {t['symbol']} {t['size']} at market (reduce-only)"
59
+ pay = t.get('funding_per_period_est')
60
+ pay_s = '' if pay is None else f", funding ≈ {abs(pay):.2f} USDT per period ({'you pay' if (pay > 0) == (t['side'] == 'long') else 'you receive'})"
61
+ return (f"[{t['mode'].upper()}] OPEN {t['side'].upper()} {t['symbol']} ≈{t['size_est']} at ≈{t['entry_est']} "
62
+ f"(≈{t['notional_est']:.2f} USDT, {t['leverage']:g}x, margin ≈{t['margin_est']:.2f}); "
63
+ f"stop {t['stop']}, take-profit {t['take_profit']}; loss at the stop ≈{t['loss_at_stop_est']:.2f} USDT "
64
+ f"incl. fees (cap {t['risk_usdt']}); liquidation ≈{_num(t['liquidation_est'])}{pay_s}")
65
+
66
+
67
+ def _num(x: Optional[float]) -> str:
68
+ return 'n/a' if x is None else f'{x:.6g}'
69
+
70
+
71
+ # ─── 7. risk ─────────────────────────────────────────────────────────────
72
+
73
+ def _log() -> list[dict]:
74
+ return (core.read('state/broker.json') or {}).get('log', [])
75
+
76
+
77
+ def check_ticket(t: dict, cfg: dict, log: list[dict], now: int) -> list[str]:
78
+ """Reasons to block; empty = PASS. Getting out (kind=close) is never blocked by limits."""
79
+ if t['kind'] == 'close':
80
+ pos = (core.read('state/broker.json') or {}).get('positions', {})
81
+ return [] if t['symbol'] in pos else ['no open position recorded for this symbol (already closed?)']
82
+ r, why = cfg['risk'], []
83
+ today = [e for e in log if e['date'] == _today(now) and e['kind'] == 'open' and e['status'] in ('placed', 'unknown')]
84
+ if t['mode'] == 'real' and not cfg.get('allow_real'):
85
+ why.append('real mode is off (allow_real=false)')
86
+ if t['mode'] != cfg['mode']:
87
+ why.append(f"ticket was sized for {t['mode']}, config is now {cfg['mode']}: size it again")
88
+ if not t.get('stop'):
89
+ why.append('no stop')
90
+ if t['symbol'] in r['blocked_symbols'] or t['symbol'].split(':')[0] in r['blocked_symbols']:
91
+ why.append(f"{t['symbol']} is blocked")
92
+ if t['risk_usdt'] > r['max_loss_per_trade']:
93
+ why.append(f"risk {t['risk_usdt']} > max loss per trade {r['max_loss_per_trade']}")
94
+ used = sum(e['risk_usdt'] for e in today)
95
+ if used + t['risk_usdt'] > r['daily_loss_limit']:
96
+ why.append(f"today's risk {used} + {t['risk_usdt']} > daily loss limit {r['daily_loss_limit']}")
97
+ if len(today) >= r['max_trades_per_day']:
98
+ why.append(f"{len(today)} trades today, max {r['max_trades_per_day']}")
99
+ if any(e['id'] == t['id'] for e in today):
100
+ why.append('this exact order was already sent today (or its outcome is unknown: reconcile first)')
101
+ if t['leverage'] > r['max_leverage']:
102
+ why.append(f"leverage {t['leverage']:g}x > max {r['max_leverage']}x")
103
+ if t['notional_est'] > r['max_notional']:
104
+ why.append(f"notional {t['notional_est']:.2f} > max {r['max_notional']}")
105
+ if t['margin_est'] and t['margin_est'] > cfg['account_usdt']:
106
+ why.append(f"margin {t['margin_est']:.2f} > account {cfg['account_usdt']}")
107
+ risk_dist = abs(t['entry_est'] - t['stop'])
108
+ if t.get('take_profit') is None:
109
+ if r['min_rr']:
110
+ why.append('no take-profit, reward:risk unknown')
111
+ elif risk_dist and abs(t['take_profit'] - t['entry_est']) / risk_dist < r['min_rr']:
112
+ why.append(f"reward:risk {abs(t['take_profit'] - t['entry_est']) / risk_dist:.2f} < min {r['min_rr']}")
113
+ liq = t.get('liquidation_est')
114
+ if liq and ((t['side'] == 'long' and t['stop'] <= liq) or (t['side'] == 'short' and t['stop'] >= liq)):
115
+ why.append(f"stop {t['stop']} is beyond the liquidation estimate {liq}: lower the leverage")
116
+ win = core.session_window(cfg, now)
117
+ if now > win['entry_until']:
118
+ why.append(f"outside the entry window (until {core.iso(win['entry_until'])})")
119
+ if t.get('flat_by') and now >= t['flat_by']:
120
+ why.append('past the flat-by time of the plan')
121
+ return why
122
+
123
+
124
+ def risk_check() -> dict:
125
+ cfg, now = core.load_config(), core.now_ms()
126
+ tickets = core.read('orders.json') or []
127
+ if not tickets:
128
+ raise ValueError('no crypto/orders.json: run the sizer first')
129
+ state = core.read('state/risk.json') or {}
130
+ rows = []
131
+ for i, t in enumerate(tickets, 1):
132
+ why = check_ticket(t, cfg, _log(), now)
133
+ state[t['id']] = {'verdict': 'BLOCK' if why else 'PASS', 'reasons': why, 'date': _today(now), 'at': now}
134
+ rows.append({'index': i, 'id': t['id'], 'verdict': state[t['id']]['verdict'], 'reasons': why})
135
+ core.write('state/risk.json', state)
136
+ return {'rows': rows, 'text': '\n'.join(
137
+ f"#{r['index']} {r['verdict']}" + (': ' + '; '.join(r['reasons']) if r['reasons'] else '') for r in rows)}
138
+
139
+
140
+ # ─── 8. broker ───────────────────────────────────────────────────────────
141
+
142
+ YES = re.compile(r"^\s*(yes|y|yep|confirm(ed)?|go|do it|place it|да|ага|подтверждаю|давай|ок|ok)\b[\s.!]*", re.I)
143
+ NO = re.compile(r"\b(no|not|don'?t|cancel|stop|wait|нет|не|стоп|отмена|подожди)\b", re.I)
144
+
145
+
146
+ def is_yes(reply: str) -> bool:
147
+ return bool(YES.match(reply or '')) and not NO.search(reply or '')
148
+
149
+
150
+ def _ready(t: dict, now: int) -> bool:
151
+ v = (core.read('state/risk.json') or {}).get(t['id'])
152
+ return bool(v) and v['verdict'] == 'PASS' and v['date'] == _today(now)
153
+
154
+
155
+ def tickets_show() -> dict:
156
+ now = core.now_ms()
157
+ tickets = core.read('orders.json') or []
158
+ rows = [{'index': i, 'id': t['id'], 'ready': _ready(t, now), 'ticket': ticket_text(t)} for i, t in enumerate(tickets, 1)]
159
+ return {'rows': rows, 'text': '\n'.join(
160
+ f"#{r['index']} {'READY' if r['ready'] else 'NOT READY (run the risk check)'}: {r['ticket']}" for r in rows) or 'no tickets'}
161
+
162
+
163
+ def execute(index: int = 1) -> dict:
164
+ """Step one of two: nothing is sent. Returns the ticket and a one-time token for confirm()."""
165
+ now = core.now_ms()
166
+ tickets = core.read('orders.json') or []
167
+ if not 1 <= index <= len(tickets):
168
+ raise ValueError(f'no ticket #{index}')
169
+ t = tickets[index - 1]
170
+ if not _ready(t, now):
171
+ raise PermissionError('this ticket has no PASS from the risk check today: run risk_check first')
172
+ tok = secrets.token_urlsafe(12)
173
+ toks = {k: v for k, v in (core.read('state/tokens.json') or {}).items() if v['expires'] > now}
174
+ toks[tok] = {'id': t['id'], 'index': index, 'expires': now + TOKEN_TTL_MS}
175
+ core.write('state/tokens.json', toks)
176
+ return {'confirm_token': tok, 'expires_in_s': TOKEN_TTL_MS // 1000, 'ticket': ticket_text(t),
177
+ 'text': f"{ticket_text(t)}\nNothing is sent yet. Ask the user to answer yes or no for exactly this order, "
178
+ f"then call confirm with this token and the user's reply word for word."}
179
+
180
+
181
+ def _record(entry: dict) -> None:
182
+ st = core.read('state/broker.json') or {'log': [], 'positions': {}}
183
+ st['log'].append(entry)
184
+ core.write('state/broker.json', st)
185
+
186
+
187
+ async def confirm(confirm_token: str, user_reply: str) -> dict:
188
+ """Step two: checks the token, the user's reply and the risk verdict again, then sends exactly that ticket."""
189
+ cfg, now = core.load_config(), core.now_ms()
190
+ toks = core.read('state/tokens.json') or {}
191
+ tk = toks.pop(confirm_token, None)
192
+ core.write('state/tokens.json', toks) # one use, even when it fails below
193
+ if not tk or tk['expires'] < now:
194
+ raise PermissionError('unknown or expired token: call execute again')
195
+ tickets = core.read('orders.json') or []
196
+ t = next((x for x in tickets if x['id'] == tk['id']), None)
197
+ if t is None:
198
+ raise PermissionError('the ticket changed since execute: show it to the user again')
199
+ base = {'id': t['id'], 'kind': t['kind'], 'symbol': t['symbol'], 'side': t['side'], 'mode': t['mode'],
200
+ 'risk_usdt': t.get('risk_usdt', 0), 'reply': user_reply, 'date': _today(now), 'at': now}
201
+ if not is_yes(user_reply):
202
+ _record({**base, 'status': 'declined'})
203
+ return {'status': 'declined', 'text': 'Not sent: the reply is not a plain yes.'}
204
+ why = check_ticket(t, cfg, _log(), now)
205
+ if why:
206
+ raise PermissionError('risk check fails now: ' + '; '.join(why))
207
+ if t['mode'] not in ('paper', 'demo'):
208
+ raise PermissionError('real orders are not sent by bytx-trader: use the hosted BYTtrade MCP')
209
+ cid = f"bt{t['id'][:14]}" # same ticket → same client_id, so a retry can be reconciled, never duplicated
210
+ from bytx.errors import BytxError, OrderStatusUnknown
211
+ async with core.open_exchange(cfg, 'trade') as ex:
212
+ try:
213
+ if t['kind'] == 'close':
214
+ res = await _close(ex, t, cfg)
215
+ else:
216
+ r = await ex.open_position(t['symbol'], t['side'], risk_usdt=t['risk_usdt'], stop=t['stop'],
217
+ take_profit=t['take_profit'], leverage=t['leverage'], client_id=cid)
218
+ res = {'status': 'placed' if r.status == 'opened' else 'not_filled', 'filled_size': r.filled_size,
219
+ 'average': r.average, 'risk': r.risk, 'warnings': list(r.warnings)}
220
+ except OrderStatusUnknown as e:
221
+ _record({**base, 'status': 'unknown', 'client_id': cid})
222
+ return {'status': 'unknown', 'client_id': cid, 'text':
223
+ f'The exchange did not say whether the order went through ({e}). It is NOT resent. '
224
+ f'Run reconcile for client_id {cid} before doing anything else.'}
225
+ except BytxError as e:
226
+ _record({**base, 'status': 'failed', 'error': f'{type(e).__name__}: {e}'})
227
+ raise
228
+ _record({**base, **res, 'client_id': cid})
229
+ if t['kind'] == 'open' and res['status'] == 'placed':
230
+ _set_position(t, res)
231
+ elif t['kind'] == 'close':
232
+ _set_position(t, None)
233
+ fill = (f"filled {res['filled_size']} @ {res['average']}" if res.get('average')
234
+ else 'sent; the exchange reports the fill shortly, check positions')
235
+ return {**res, 'client_id': cid, 'text': f"{res['status'].upper()}: {ticket_text(t)}; {fill}"}
236
+
237
+
238
+ async def _close(ex: Any, t: dict, cfg: dict) -> dict:
239
+ if cfg['mode'] == 'paper':
240
+ # shortcut: a paper account lives only inside one process, so the exit is a fresh opposite market order
241
+ # on the live book (real fill price and fee); upgrade if paper state is persisted across runs.
242
+ await ex.set_leverage(t['symbol'], t['position_leverage'] or 1)
243
+ o = await (ex.sell if t['side'] == 'long' else ex.buy)(t['symbol'], size=t['size'])
244
+ else:
245
+ o = await ex.close_position(t['symbol'])
246
+ return {'status': 'placed', 'filled_size': getattr(o, 'filled', None), 'average': getattr(o, 'average', None)}
247
+
248
+
249
+ def _set_position(t: dict, res: Optional[dict]) -> None:
250
+ st = core.read('state/broker.json')
251
+ if res is None:
252
+ st['positions'].pop(t['symbol'], None)
253
+ else:
254
+ st['positions'][t['symbol']] = {'side': t['side'], 'size': res['filled_size'], 'entry': res['average'],
255
+ 'stop': t['stop'], 'take_profit': t['take_profit'], 'mode': t['mode'],
256
+ 'leverage': t['leverage'],
257
+ 'flat_by': t.get('flat_by')}
258
+ core.write('state/broker.json', st)
259
+
260
+
261
+ def flatten(symbol: Optional[str] = None) -> dict:
262
+ """Write close tickets for open positions (all, or one symbol). They still need execute + confirm."""
263
+ cfg = core.load_config()
264
+ pos = (core.read('state/broker.json') or {}).get('positions', {})
265
+ tickets = []
266
+ for sym, p in pos.items():
267
+ if symbol and symbol not in (sym, sym.split(':')[0]):
268
+ continue
269
+ t = {'kind': 'close', 'symbol': sym, 'side': p['side'], 'size': p['size'], 'mode': p['mode'],
270
+ 'risk_usdt': 0, 'stop': None, 'take_profit': None, 'leverage': None,
271
+ 'position_leverage': p.get('leverage'), 'created': core.now_ms()}
272
+ if p['mode'] != cfg['mode']:
273
+ raise ValueError(f"{sym} was opened in {p['mode']}, config is {cfg['mode']}")
274
+ t['id'] = fingerprint(t)
275
+ tickets.append(t)
276
+ if not tickets:
277
+ return {'rows': [], 'text': 'no open positions recorded'}
278
+ core.write('orders.json', tickets)
279
+ out = risk_check() # close tickets always PASS; this records the verdict so execute accepts them
280
+ out['text'] = 'Close tickets written:\n' + tickets_show()['text']
281
+ return out
282
+
283
+
284
+ async def positions() -> dict:
285
+ cfg = core.load_config()
286
+ pos = (core.read('state/broker.json') or {}).get('positions', {})
287
+ rows = []
288
+ if pos:
289
+ async with core.open_exchange(cfg, 'data') as ex:
290
+ for sym, p in pos.items():
291
+ px = (await ex.ticker(sym)).last
292
+ sign = 1 if p['side'] == 'long' else -1
293
+ hit = ('stop' if sign * (px - p['stop']) <= 0 else
294
+ 'target' if p['take_profit'] and sign * (px - p['take_profit']) >= 0 else None)
295
+ rows.append({'symbol': sym, **p, 'price': px, 'pnl_est': sign * (px - p['entry']) * p['size'],
296
+ 'level_crossed': hit, 'past_flat_by': bool(p.get('flat_by') and core.now_ms() >= p['flat_by'])})
297
+ note = ('Paper positions are tracked here, not by the exchange: stop/target are not watched between runs; '
298
+ 'if a level is crossed or flat-by passed, flatten.' if cfg['mode'] == 'paper' else '')
299
+ text = '\n'.join(
300
+ f"{r['symbol']} {r['side']} {r['size']} @ {r['entry']}: now {r['price']}, PnL ≈{r['pnl_est']:.2f}"
301
+ + (f", {r['level_crossed']} crossed" if r['level_crossed'] else '')
302
+ + (', past flat-by' if r['past_flat_by'] else '') for r in rows) or 'no open positions recorded'
303
+ return {'rows': rows, 'text': f'{text}\n{note}' if rows and note else text}
304
+
305
+
306
+ async def reconcile(client_id: str) -> dict:
307
+ """Find an order whose outcome was unknown, by its client_id. Never resends."""
308
+ cfg = core.load_config()
309
+ entry = next((e for e in reversed(_log()) if e.get('client_id') == client_id), None)
310
+ if not entry:
311
+ raise ValueError(f'no order with client_id {client_id} in the log')
312
+ if cfg['mode'] == 'paper':
313
+ return {'status': entry['status'], 'text': 'paper orders never reach an exchange; nothing to reconcile'}
314
+ async with core.open_exchange(cfg, 'trade') as ex:
315
+ o = await ex.order(entry['symbol'], client_id=client_id)
316
+ _record({**entry, 'status': 'reconciled', 'order_status': o.status, 'at': core.now_ms()})
317
+ return {'order_status': o.status, 'filled': o.filled, 'text': f'{client_id}: {o.status}, filled {o.filled}'}
bytx_trader/updates.py ADDED
@@ -0,0 +1,66 @@
1
+ """Tell pip users when a newer bytx-trader or compatible bytx is out. uvx users get it automatically.
2
+
3
+ One request per package to pypi.org at most once a day, nothing about the user is sent;
4
+ BYTX_TRADER_NO_UPDATE_CHECK=1 turns it off. Never installs anything itself.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import time
11
+ import urllib.request
12
+ from importlib.metadata import PackageNotFoundError, version
13
+ from pathlib import Path
14
+ from typing import Callable, Optional
15
+
16
+ CACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'bytx-trader' / 'update.json'
17
+ DAY = 86_400
18
+
19
+
20
+ def _ver(s: str) -> Optional[tuple[int, ...]]:
21
+ parts = s.split('.')
22
+ return tuple(int(p) for p in parts) if all(p.isdigit() for p in parts) else None # skips pre-releases
23
+
24
+
25
+ def pypi_releases(name: str) -> list[str]:
26
+ with urllib.request.urlopen(f'https://pypi.org/pypi/{name}/json', timeout=3) as r:
27
+ data = json.load(r)
28
+ return [v for v, files in data['releases'].items() if files and not all(f.get('yanked') for f in files)]
29
+
30
+
31
+ def newest(releases: list[str], series: Optional[tuple[int, int]] = None) -> Optional[str]:
32
+ ok = [(_ver(v), v) for v in releases if _ver(v) and (series is None or _ver(v)[:2] == series)]
33
+ return max(ok)[1] if ok else None
34
+
35
+
36
+ def notice(fetch: Callable[[str], list[str]] = pypi_releases, now: Optional[float] = None) -> Optional[str]:
37
+ if os.environ.get('BYTX_TRADER_NO_UPDATE_CHECK'):
38
+ return None
39
+ now = now or time.time()
40
+ try:
41
+ cached = json.loads(CACHE.read_text())
42
+ if now - cached['at'] < DAY:
43
+ return cached['notice']
44
+ except (OSError, ValueError, KeyError):
45
+ pass
46
+ msgs = []
47
+ try:
48
+ mine = version('bytx-trader')
49
+ latest = newest(fetch('bytx-trader'))
50
+ if latest and _ver(latest) > _ver(mine):
51
+ msgs.append(f'bytx-trader {latest} is out (you run {mine})')
52
+ lib = version('bytx')
53
+ # only the series bytx-trader allows (<0.3 today); a new series arrives with a new bytx-trader
54
+ lib_latest = newest(fetch('bytx'), _ver(lib)[:2])
55
+ if lib_latest and _ver(lib_latest) > _ver(lib):
56
+ msgs.append(f'bytx {lib_latest} is out (you run {lib})')
57
+ except (OSError, ValueError, KeyError, TypeError, PackageNotFoundError):
58
+ return None # offline or PyPI hiccup: never block the server over a hint
59
+ text = ('Update available: ' + '; '.join(msgs) + '. Run: pip install -U bytx-trader bytx '
60
+ '(or start the server with uvx to always get the latest).') if msgs else None
61
+ try:
62
+ CACHE.parent.mkdir(parents=True, exist_ok=True)
63
+ CACHE.write_text(json.dumps({'at': now, 'notice': text}))
64
+ except OSError:
65
+ pass
66
+ return text
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.5
2
+ Name: bytx-trader
3
+ Version: 0.1.0
4
+ Summary: Crypto trading steps for AI assistants on bytx: scanner, funding/OI, entry, exit, time machine, risk-based size, risk gate, paper/demo broker. MCP server + CLI.
5
+ Project-URL: Homepage, https://github.com/byttrade/bytx-skills
6
+ Project-URL: Repository, https://github.com/byttrade/bytx-skills
7
+ Project-URL: Issues, https://github.com/byttrade/bytx-skills/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: bytx,claude,crypto,mcp,paper-trading,trading
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: bytx<0.3,>=0.2.1
13
+ Requires-Dist: mcp>=1.2
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
16
+ Requires-Dist: pytest>=8; extra == 'test'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # bytx-skills — crypto trading skills for AI assistants
20
+
21
+ **English** | [Русский](docs/README.ru.md)
22
+
23
+ Eight steps for one crypto trade, from "what's moving" to the order: scan the perps, read funding and open interest,
24
+ time the entry, plan the exit, replay the rest of the session 10,000 times, size the position from the money you
25
+ are ready to lose, check it against your limits, and send it — paper by default, never without your yes.
26
+
27
+ Works with **any AI assistant that supports MCP — for example, Claude**. The logic is a Python package with an MCP
28
+ server and a CLI on the [bytx](https://pypi.org/project/bytx/) exchange library; for Claude there are also skills
29
+ (`/crypto-scanner` …) on top.
30
+
31
+ Paper trading runs on the exchange's live order book with virtual money: no keys, no signup.
32
+
33
+ ## Install
34
+
35
+ You need [uv](https://docs.astral.sh/uv/) (`brew install uv` or `curl -LsSf https://astral.sh/uv/install.sh | sh`).
36
+
37
+ **Any MCP client** (Claude Desktop, Claude Code, Cursor, …): add the server to the client's MCP config —
38
+ templates in [`mcp-configs/`](mcp-configs/):
39
+
40
+ ```json
41
+ { "mcpServers": { "bytx-trader": {
42
+ "command": "uvx",
43
+ "args": ["--refresh-package", "bytx", "--refresh-package", "bytx-trader",
44
+ "--from", "bytx-trader@latest", "bytx-trader-mcp"],
45
+ "env": { "BYTX_TRADER_HOME": "/absolute/path/to/your/project/crypto" } } } }
46
+ ```
47
+
48
+ Then ask "scan the crypto market" or start from the server's `trade_pipeline` prompt. Set the `confirm` tool to ask
49
+ you every time. Without uv: `pip install bytx-trader` and `"command": "bytx-trader-mcp"`.
50
+
51
+ **Claude only, on top of that:**
52
+
53
+ ```
54
+ /plugin marketplace add byttrade/bytx-skills
55
+ /plugin install bytx-trader@bytx-skills
56
+ ```
57
+
58
+ or copy the folders: `cp -r bytx-skills/crypto-* ~/.claude/skills/` (or your project's `.claude/skills/`).
59
+
60
+ | | any MCP client | Claude only |
61
+ |---|---|---|
62
+ | all eight steps, paper and demo | MCP tools | |
63
+ | risk gate and one-time confirm token | in the server | |
64
+ | the trade as a script | `trade_pipeline` prompt | skills |
65
+ | `/crypto-*` commands, triggers by phrase, plugin install | | ✓ |
66
+
67
+ ## The steps
68
+
69
+ | step | MCP tool / CLI | what it does |
70
+ |---|---|---|
71
+ | `crypto-scanner` | `scan` | Top perps by 24h volume: breakout of the session's opening range, RSI extremes. |
72
+ | `crypto-derivs` | `derivs` | Funding now and 7-day average, open interest change, perp/spot basis, crowded-side flags. |
73
+ | `crypto-entry` | `entry_check` | Waiting / triggered / expired, on closed bars only. |
74
+ | `crypto-exit` | `exit_plan` | Stop (range-mid, range, ATR, price), target in R, flat-by time. |
75
+ | `crypto-timemachine` | `timemachine` | 10,000 replays of the rest of the session from the coin's own bars + the same rule on every past session. |
76
+ | `crypto-size` | `size` | Size from risk with fees, margin, liquidation estimate, funding cost. Places nothing. |
77
+ | `crypto-risk` | `risk_check` | PASS / BLOCK against your limits. |
78
+ | `crypto-broker` | `execute`, `confirm`, `flatten`, `positions`, `reconcile` | The only step that sends anything. |
79
+
80
+ Crypto trades 24/7, so the "session" is yours: `crypto/config.json` → `session.start` (00:00 UTC by default),
81
+ `range_minutes`, `entry_until`, `flat_by`. Everything lands in `crypto/` and each step reads what the last one wrote.
82
+
83
+ ## An example: BTC on Binance, November 18 2026, real candles
84
+
85
+ 1. **scan** at 01:05 UTC: BTC broke its first-hour range (64,673.5–64,976.3) to the downside; the 01:00 bar closed at
86
+ 64,588.5, 0.131 % below.
87
+ 2. **entry_check**: triggered, short.
88
+ 3. **exit_plan** `--stop range-mid --target-r 2`: stop 64,824.9 (0.366 % away), target 64,115.7, flat by 23:55 UTC.
89
+ 4. **timemachine**: 10,000 replays from the last 30 sessions (seed 19): target first 37.6 %, stop first 62.4 %. The same
90
+ rule on those 30 sessions: fired 30 times, 9 targets, 21 stops. Expectancy before fees +0.13R simulated, −0.10R
91
+ historical. Verdict: close to a coin flip — that is the point of looking before you risk a dollar.
92
+ 5. **size** with 10 USDT at risk, 5x: ≈0.033 BTC, ≈2,131 USDT notional, margin ≈426, loss at the stop ≈9.94 USDT with fees.
93
+ 6. **risk_check**: PASS.
94
+ 7. **execute** shows the ticket and returns a one-time token; you answer yes; **confirm** sends it to the paper account.
95
+
96
+ `tests/` reproduce these numbers offline from the candles in `tests/fixtures/`.
97
+
98
+ ## Modes and the gates
99
+
100
+ | mode | how | keys |
101
+ |---|---|---|
102
+ | **paper** (default) | live order book, virtual balance `account_usdt`, real taker fees | none |
103
+ | **demo** | `"mode": "demo"`: the exchange's demo/testnet | `BYTX_API_KEY`, `BYTX_SECRET` (`BYTX_PASSWORD` for OKX, KuCoin, Bitget) in the server's environment |
104
+ | **real** | not sent by this package: real orders go through the hosted [BYTtrade](https://byttrade.com) MCP | kept by BYTtrade |
105
+
106
+ Every order, in every mode, passes three gates, enforced in the code:
107
+
108
+ 1. the risk check passed **this exact ticket** today (fingerprint);
109
+ 2. `execute` sends nothing — it returns the ticket and a one-time token (5 min); `confirm` takes the token and **your
110
+ reply word for word**, and anything but a plain yes cancels; the risk check runs again;
111
+ 3. your client's own approval prompt for `confirm`.
112
+
113
+ The client order id comes from the ticket, so if the exchange times out the order is found by that id with
114
+ `reconcile` — it is never sent twice. Getting out (`flatten`) is never blocked by daily limits.
115
+
116
+ ## Updates
117
+
118
+ Started with `uvx` as above, the server picks up the newest `bytx-trader` and the newest compatible `bytx` every time
119
+ your assistant starts it: fixes and new exchange features arrive with no action on your side. `bytx-trader` accepts
120
+ `bytx` within one series (`>=0.2.1,<0.3`), so a breaking `bytx` release never arrives on its own: it comes with a
121
+ `bytx-trader` release that was tested against it. Installed with `pip`, the server checks PyPI once a day and tells you
122
+ in its first answer when an update is out (`BYTX_TRADER_NO_UPDATE_CHECK=1` turns that off). Claude skills installed as
123
+ a plugin update with the marketplace (`/plugin`).
124
+
125
+ ## Development
126
+
127
+ ```bash
128
+ pip install -e ".[test]" && pytest
129
+ ```
130
+
131
+ Tests are offline: real candles in `tests/fixtures/`, orders on `bytx.testing` paper accounts.
132
+
133
+ ## Fine print
134
+
135
+ **Not financial advice.** Most people who trade actively lose money; leverage makes it faster. A stop is a plan, not
136
+ a guarantee: gaps, slippage and auto-deleveraging can fill it far away, and liquidation can come first if leverage is
137
+ high. Funding is charged every period while a position is open. The time machine is a simulation from the last few
138
+ weeks, not a prediction. Paper trading simplifies margin and liquidation and does not watch your stop between runs.
139
+ Keys live in environment variables, never in the chat.
140
+
141
+ MIT. Built on [bytx](https://pypi.org/project/bytx/) (BYTtrade Source-Available License, installed from PyPI, not
142
+ copied here). No-code bots, backtests and trade confirmations in Telegram — at [byttrade.com](https://byttrade.com).
143
+
144
+ <sub>**All risk is yours.** bytx-skills is a tool, provided as is, without any warranty. You alone decide whether and
145
+ how to use it, and you alone bear every loss, missed profit or other consequence, including those caused by errors in
146
+ the software, the data, an exchange or an AI assistant. Test it yourself — on paper, then on an exchange demo account —
147
+ and only once you are satisfied that it works for you, use it with real money, in amounts you can afford to lose.
148
+ The authors and BYTtrade are not liable for any trading results.</sub>
@@ -0,0 +1,12 @@
1
+ bytx_trader/__init__.py,sha256=n1cBu07beafBaigI-FyN771zFYCAs5OcEZmaX9veFT4,89
2
+ bytx_trader/cli.py,sha256=jhEtqQd8IR1vTcfZVngYEAQZ3TftSDDbl35mPBhLSHU,3609
3
+ bytx_trader/core.py,sha256=zG7aOVs6b6C55Yg_9pAB1PhbHr30uOCrQBiTIRY_A5Y,5351
4
+ bytx_trader/market.py,sha256=bTxBFDSOge7Q0Civ7gRS1tixk_RixRs2DCPkAJGD-98,18382
5
+ bytx_trader/mcp_server.py,sha256=CWOZwPPH84_BQRjOFk8rOZkg888toIVPTifmd-iUreQ,5689
6
+ bytx_trader/trade.py,sha256=1z_RVJF7Nspj4KT-L-nq_TfU7PHMCImHDPjqDIzb2lM,17535
7
+ bytx_trader/updates.py,sha256=TK1a0nJsBeuCayXlNteN76PVkqrYAxELT9aD55stUtM,2756
8
+ bytx_trader-0.1.0.dist-info/METADATA,sha256=UNwZOf0WTK2fBGmay_rYIk8MLpp5H0hJycFbN56oWoo,8303
9
+ bytx_trader-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ bytx_trader-0.1.0.dist-info/entry_points.txt,sha256=l-8e770CsbVlnJYpNxhXIwCPN6x3WeokeZThNEvllh0,99
11
+ bytx_trader-0.1.0.dist-info/licenses/LICENSE,sha256=n7mL_YnBvCeKhqcSLUlliayQlqaAMQdKnIoRoNZQn8E,1743
12
+ bytx_trader-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ bytx-trader = bytx_trader.cli:main
3
+ bytx-trader-mcp = bytx_trader.mcp_server:main
@@ -0,0 +1,33 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BYTtrade
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.
22
+
23
+ ---
24
+
25
+ RISK NOTICE. The Software is a tool for working with cryptocurrency exchanges.
26
+ It is not financial, investment or trading advice. Trading cryptocurrency,
27
+ especially with leverage, carries a high risk of loss. All risk of using the
28
+ Software is borne solely by the user, including losses caused by errors in the
29
+ Software, in market data, at an exchange or in an AI assistant. Each user must
30
+ test the Software on their own (paper trading, then an exchange demo account)
31
+ and use it with real funds only after satisfying themselves that it works as
32
+ they need, and only with amounts they can afford to lose. The authors and
33
+ BYTtrade accept no liability for any trading results.