tickwire 0.0.0-stage → 0.1.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 +15 -0
- package/README.md +209 -2
- package/dist/backtest/backtest.d.ts +101 -0
- package/dist/backtest/backtest.js +200 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +179 -0
- package/dist/core/aggregate.d.ts +19 -0
- package/dist/core/aggregate.js +64 -0
- package/dist/core/clock.d.ts +6 -0
- package/dist/core/clock.js +18 -0
- package/dist/core/errors.d.ts +51 -0
- package/dist/core/errors.js +53 -0
- package/dist/core/http.d.ts +38 -0
- package/dist/core/http.js +119 -0
- package/dist/core/instrument.d.ts +14 -0
- package/dist/core/instrument.js +22 -0
- package/dist/core/provider.d.ts +47 -0
- package/dist/core/provider.js +1 -0
- package/dist/core/rate-limiter.d.ts +30 -0
- package/dist/core/rate-limiter.js +68 -0
- package/dist/core/stream.d.ts +90 -0
- package/dist/core/stream.js +224 -0
- package/dist/core/timeframe.d.ts +16 -0
- package/dist/core/timeframe.js +21 -0
- package/dist/core/types.d.ts +52 -0
- package/dist/core/types.js +1 -0
- package/dist/core/util.d.ts +8 -0
- package/dist/core/util.js +24 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +22 -0
- package/dist/indicators/atr.d.ts +21 -0
- package/dist/indicators/atr.js +41 -0
- package/dist/indicators/bollinger.d.ts +22 -0
- package/dist/indicators/bollinger.js +42 -0
- package/dist/indicators/ema.d.ts +16 -0
- package/dist/indicators/ema.js +40 -0
- package/dist/indicators/index.d.ts +8 -0
- package/dist/indicators/index.js +8 -0
- package/dist/indicators/indicator.d.ts +15 -0
- package/dist/indicators/indicator.js +17 -0
- package/dist/indicators/macd.d.ts +31 -0
- package/dist/indicators/macd.js +48 -0
- package/dist/indicators/rsi.d.ts +17 -0
- package/dist/indicators/rsi.js +53 -0
- package/dist/indicators/sma.d.ts +14 -0
- package/dist/indicators/sma.js +43 -0
- package/dist/indicators/vwap.d.ts +25 -0
- package/dist/indicators/vwap.js +37 -0
- package/dist/providers/alpaca.d.ts +44 -0
- package/dist/providers/alpaca.js +227 -0
- package/dist/providers/binance.d.ts +31 -0
- package/dist/providers/binance.js +187 -0
- package/dist/providers/coinbase.d.ts +28 -0
- package/dist/providers/coinbase.js +179 -0
- package/dist/providers/create.d.ts +6 -0
- package/dist/providers/create.js +21 -0
- package/dist/providers/kraken.d.ts +30 -0
- package/dist/providers/kraken.js +203 -0
- package/dist/providers/options.d.ts +22 -0
- package/dist/providers/options.js +1 -0
- package/dist/providers/paging.d.ts +30 -0
- package/dist/providers/paging.js +59 -0
- package/dist/series/check.d.ts +32 -0
- package/dist/series/check.js +63 -0
- package/dist/series/live.d.ts +31 -0
- package/dist/series/live.js +121 -0
- package/dist/series/load.d.ts +35 -0
- package/dist/series/load.js +100 -0
- package/dist/series/store.d.ts +50 -0
- package/dist/series/store.js +148 -0
- package/dist/series/time.d.ts +15 -0
- package/dist/series/time.js +62 -0
- package/dist/watch/sinks.d.ts +7 -0
- package/dist/watch/sinks.js +22 -0
- package/dist/watch/watch.d.ts +78 -0
- package/dist/watch/watch.js +203 -0
- package/docs/agents.md +84 -0
- package/docs/positioning.md +94 -0
- package/docs/providers.md +92 -0
- package/package.json +68 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mathieu Colmon
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
10
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
11
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
13
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
14
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
15
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,210 @@
|
|
|
1
|
-
#
|
|
1
|
+
# TickWire
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<a href="https://github.com/Mathieu2301/tickwire"><img src="https://trendshift.io/api/badge/repositories/26416" alt="Mathieu2301/tickwire" width="250" height="55"/></a>
|
|
4
|
+
|
|
5
|
+
**The market toolkit for AI agents that write code.** Candle series you can trust, with a local cache, watchers that run around the clock, indicators and backtests, all from official exchange and broker APIs and running on your own machine.
|
|
6
|
+
|
|
7
|
+
> [!NOTE]
|
|
8
|
+
> This repository was previously known as TradingView-API. The TradingView integration has been removed at TradingView's request, and TickWire does not access TradingView's services in any way. Previous versions are no longer distributed.
|
|
9
|
+
|
|
10
|
+
- **Series you can trust:** history and live feed joined without gap or overlap, closed and forming candles told apart, gaps and duplicates detected, a local cache that only fetches what is new.
|
|
11
|
+
- **Watchers:** a condition in plain TypeScript, checked on every candle, for as many instruments as you like; an event when it triggers.
|
|
12
|
+
- **Official sources only:** public, documented exchange and broker APIs (Binance, Coinbase Exchange, Kraken, Alpaca), used within their limits.
|
|
13
|
+
- **One interface for every source:** the same `Candle`, `Quote` and `Trade` types, whichever provider you plug in.
|
|
14
|
+
- **Live streams that stay up:** WebSocket feeds as async iterables, with reconnection, backoff and re-subscription.
|
|
15
|
+
- **Local indicators and backtests:** SMA, EMA, RSI, MACD, Bollinger Bands, ATR and VWAP (incremental or batch), and an event-driven backtester with fees and slippage.
|
|
16
|
+
- **Small:** ESM, typed, no runtime dependencies. Node 20+ or Bun (streams need Node 22+, Bun, or a `WebSocket` you pass in). A small `tickwire` command for quick lookups.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm install tickwire # or: bun add tickwire
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { BinanceProvider, rsi } from 'tickwire';
|
|
26
|
+
|
|
27
|
+
const binance = new BinanceProvider();
|
|
28
|
+
|
|
29
|
+
// The latest 200 hourly candles, oldest first
|
|
30
|
+
const candles = await binance.getCandles('BTC/USDT', '1h', { limit: 200 });
|
|
31
|
+
console.log(rsi(candles.map((c) => c.close), 14).at(-1));
|
|
32
|
+
|
|
33
|
+
// Best bid/ask and last price
|
|
34
|
+
const quote = await binance.getQuote('BTC/USDT');
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Instruments are written `BASE/QUOTE` for crypto pairs (`BTC/USD`, `ETH/USDT`) and by ticker for stocks (`AAPL`). Each provider translates them into its own symbols. Timeframes are `1m`, `5m`, `1h`, `4h`, `1d`, `1w`, `1M`… (each provider lists what it supports in `provider.capabilities`).
|
|
38
|
+
|
|
39
|
+
### Series and cache
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { BinanceProvider, FileStore, loadCandles, checkCandles } from 'tickwire';
|
|
43
|
+
|
|
44
|
+
const store = new FileStore('.tickwire'); // JSON Lines files, readable by DuckDB, Polars or jq
|
|
45
|
+
const candles = await loadCandles({
|
|
46
|
+
provider: new BinanceProvider(),
|
|
47
|
+
instrument: 'ETH/USDT',
|
|
48
|
+
timeframe: '1h',
|
|
49
|
+
from: '6mo', // or a date
|
|
50
|
+
store, // the next call only fetches the hours that closed since
|
|
51
|
+
});
|
|
52
|
+
checkCandles(candles, '1h'); // { gaps, duplicates, unordered, misaligned, … }
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`liveCandles({ provider, instrument, timeframe, history: 200, store })` gives one continuous stream: the closed history first, then live updates. If the connection drops and periods are missed, they are fetched from the history API and emitted in order before going on.
|
|
56
|
+
|
|
57
|
+
### Watchers
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { BinanceProvider, watch, rsi, appendJsonl } from 'tickwire';
|
|
61
|
+
|
|
62
|
+
const log = appendJsonl('alerts.jsonl');
|
|
63
|
+
for await (const event of watch({
|
|
64
|
+
provider: new BinanceProvider(),
|
|
65
|
+
instruments: ['BTC/USDT', 'ETH/USDT', 'SOL/USDT'],
|
|
66
|
+
timeframe: '15m',
|
|
67
|
+
name: 'oversold',
|
|
68
|
+
when: ({ closes, candle }) => (rsi(closes, 14).at(-1) ?? 50) < 30 && { rsi: rsi(closes, 14).at(-1), price: candle.close },
|
|
69
|
+
})) {
|
|
70
|
+
await log(event); // or postJson(webhookUrl)
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
A watcher fires when its condition becomes true and waits for it to turn false before firing again (`mode: 'every'` to change that, `cooldownMs` to space triggers). It checks closed candles by default, or every live update with `on: 'update'`. It uses next to no CPU, so one process can watch dozens of markets around the clock.
|
|
75
|
+
|
|
76
|
+
### Command line
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
tickwire candles binance BTC/USDT 1h --since 7d # JSON summary + candles
|
|
80
|
+
tickwire candles alpaca AAPL 1d --since 1y --format csv
|
|
81
|
+
tickwire check coinbase ETH/USD 1h --since 30d # gaps and duplicates
|
|
82
|
+
tickwire quote kraken BTC/USD
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Output is JSON on stdout, errors are JSON on stderr. Candles go through the same cache (`$TICKWIRE_CACHE`, default `~/.cache/tickwire`).
|
|
86
|
+
|
|
87
|
+
### History over a range
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { CoinbaseProvider } from 'tickwire';
|
|
91
|
+
|
|
92
|
+
const coinbase = new CoinbaseProvider();
|
|
93
|
+
const november = await coinbase.getCandles('ETH/USD', '1h', {
|
|
94
|
+
from: '2026-11-01T00:00:00Z',
|
|
95
|
+
to: '2026-11-30T23:00:00Z',
|
|
96
|
+
}); // paged for you, within the provider's rate limit
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Live trades
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { KrakenProvider } from 'tickwire';
|
|
103
|
+
|
|
104
|
+
const kraken = new KrakenProvider();
|
|
105
|
+
const trades = kraken.streamTrades('BTC/USD', {
|
|
106
|
+
onStatus: (s) => console.log(s.type), // connecting, open, reconnecting, closed
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
for await (const trade of trades) {
|
|
110
|
+
console.log(trade.time, trade.side, trade.size, trade.price);
|
|
111
|
+
if (trade.size > 1) break; // breaking out of the loop closes the connection
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`streamCandles(instrument, timeframe)` works the same way: you get the running candle on every update, then the same candle with `closed: true` when its period ends. Stop a stream with `break`, `stream.close()`, or an `AbortSignal` (`{ signal }`).
|
|
116
|
+
|
|
117
|
+
### Indicators
|
|
118
|
+
|
|
119
|
+
Every indicator exists in two forms: a batch function over an array, and a class you feed one value at a time.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { EMA, macd, bollinger, ATR } from 'tickwire';
|
|
123
|
+
|
|
124
|
+
const closes = candles.map((c) => c.close);
|
|
125
|
+
macd(closes); // [undefined, …, { macd, signal, histogram }]
|
|
126
|
+
bollinger(closes, { period: 20, stdDev: 2 });
|
|
127
|
+
|
|
128
|
+
const ema = new EMA(21);
|
|
129
|
+
for await (const candle of binance.streamCandles('BTC/USDT', '1m')) {
|
|
130
|
+
if (candle.closed) console.log(ema.next(candle.close));
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Available: `SMA`, `EMA`, `RSI` (Wilder), `MACD`, `BollingerBands`, `ATR` (Wilder), `VWAP` (daily or unanchored). Values are `undefined` while an indicator warms up.
|
|
135
|
+
|
|
136
|
+
### Backtest
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { backtest, SMA } from 'tickwire';
|
|
140
|
+
|
|
141
|
+
const fast = new SMA(10);
|
|
142
|
+
const slow = new SMA(40);
|
|
143
|
+
|
|
144
|
+
const { metrics, trades } = backtest({
|
|
145
|
+
candles, // closed candles, oldest first
|
|
146
|
+
initialCash: 10_000,
|
|
147
|
+
feeRate: 0.001, // 0.1 % per fill
|
|
148
|
+
slippage: 0.0005,
|
|
149
|
+
strategy: (ctx) => {
|
|
150
|
+
const f = fast.next(ctx.candle.close);
|
|
151
|
+
const s = slow.next(ctx.candle.close);
|
|
152
|
+
if (f === undefined || s === undefined) return;
|
|
153
|
+
if (f > s && ctx.position === 0) ctx.buy();
|
|
154
|
+
if (f < s && ctx.position > 0) ctx.sell();
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
console.log(metrics); // totalReturn, maxDrawdown, sharpe, winRate, trades, totalFees, exposure…
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The strategy runs after each candle closes, and its orders fill at the **next** candle's open: a strategy cannot trade on a price it has not seen. `ctx.lookback(n)` returns past candles only. Positions are long only in 0.1.
|
|
162
|
+
|
|
163
|
+
More in [`examples/`](examples).
|
|
164
|
+
|
|
165
|
+
## Providers
|
|
166
|
+
|
|
167
|
+
| Provider | Key needed | Markets | Streams |
|
|
168
|
+
|---|---|---|---|
|
|
169
|
+
| `BinanceProvider` | no | crypto spot | trades, candles |
|
|
170
|
+
| `CoinbaseProvider` | no | crypto spot | trades, candles (built from trades) |
|
|
171
|
+
| `KrakenProvider` | no | crypto spot (latest 720 candles per timeframe) | trades, candles |
|
|
172
|
+
| `AlpacaProvider` | free Alpaca key (`APCA_API_KEY_ID`, `APCA_API_SECRET_KEY`) | US stocks, IEX feed on the free plan | trades, 1-minute bars |
|
|
173
|
+
|
|
174
|
+
**Your use of each source is governed by that provider's terms, not by TickWire.** Most of them limit market data to personal, research or internal use, forbid redistributing it, and are not available in every country. TickWire hosts and redistributes no data, and is not affiliated with or endorsed by any provider. Read [docs/providers.md](docs/providers.md) for each provider's endpoints, rate limits and terms before you use it.
|
|
175
|
+
|
|
176
|
+
## Use it with an agent
|
|
177
|
+
|
|
178
|
+
TickWire is built for agents that write and run code: plain TypeScript (Node or Bun), typed results, typed errors. [docs/agents.md](docs/agents.md) is a short guide written for them. To have an agent that learns your trading strategy and watches the markets for you around the clock, start from the [day trader agent dream on molted.studio](https://molted.studio/dreams/ai-agent-for-day-traders). See [docs/positioning.md](docs/positioning.md) for where the project is heading.
|
|
179
|
+
|
|
180
|
+
## Errors
|
|
181
|
+
|
|
182
|
+
Everything thrown by TickWire extends `TickwireError`:
|
|
183
|
+
|
|
184
|
+
| Error | When |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `InvalidArgumentError` | bad timeframe, instrument or range |
|
|
187
|
+
| `NotSupportedError` | the provider does not offer this timeframe or market |
|
|
188
|
+
| `AuthenticationError` | missing or rejected API key |
|
|
189
|
+
| `RateLimitError` | the provider rate-limited you (`retryAfterMs` when known) |
|
|
190
|
+
| `NetworkError` | the provider could not be reached or timed out |
|
|
191
|
+
| `ProviderError` | the provider returned an error (`status`, `code`) or an unexpected payload |
|
|
192
|
+
|
|
193
|
+
Requests are retried on network errors, 5xx and 429 answers (twice by default, `retries` option), honouring `Retry-After`.
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```sh
|
|
198
|
+
npm install
|
|
199
|
+
npm run typecheck && npm run lint && npm test && npm run build
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Tests run offline against responses recorded from the real APIs (`tests/fixtures`, refreshed with `npm run fixtures:record`). Live checks are opt-in: `npm run test:live`.
|
|
203
|
+
|
|
204
|
+
## Need help with a project?
|
|
205
|
+
|
|
206
|
+
Tell us about it through [this form](https://forms.gle/qPp5RKo8L55C5oJE7).
|
|
207
|
+
|
|
208
|
+
## License
|
|
209
|
+
|
|
210
|
+
ISC
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Candle } from '../core/types.js';
|
|
2
|
+
export interface StrategyContext {
|
|
3
|
+
/** The candle that just closed. */
|
|
4
|
+
readonly candle: Candle;
|
|
5
|
+
/** Index of `candle` in the input. */
|
|
6
|
+
readonly index: number;
|
|
7
|
+
/** Units currently held (long only, never negative). */
|
|
8
|
+
readonly position: number;
|
|
9
|
+
readonly cash: number;
|
|
10
|
+
/** Cash plus position valued at the current close. */
|
|
11
|
+
readonly equity: number;
|
|
12
|
+
/** The last `n` closed candles, oldest first, ending with the current one. Never includes future candles. */
|
|
13
|
+
lookback(n: number): readonly Candle[];
|
|
14
|
+
/**
|
|
15
|
+
* Market buy, filled at the next candle's open (plus slippage and fees).
|
|
16
|
+
* Without `quantity`, spends all the cash available at fill time.
|
|
17
|
+
*/
|
|
18
|
+
buy(quantity?: number): void;
|
|
19
|
+
/** Market sell, filled at the next candle's open. Without `quantity`, sells the whole position. */
|
|
20
|
+
sell(quantity?: number): void;
|
|
21
|
+
}
|
|
22
|
+
export type Strategy = (ctx: StrategyContext) => void;
|
|
23
|
+
export interface BacktestOptions {
|
|
24
|
+
/** Closed candles in ascending time order. */
|
|
25
|
+
candles: readonly Candle[];
|
|
26
|
+
strategy: Strategy;
|
|
27
|
+
/** Starting cash (default 10 000). */
|
|
28
|
+
initialCash?: number;
|
|
29
|
+
/** Fee as a fraction of each fill's notional value (default 0.001 = 0.1 %). */
|
|
30
|
+
feeRate?: number;
|
|
31
|
+
/** Adverse price move applied to each fill, as a fraction (default 0.0005 = 0.05 %). */
|
|
32
|
+
slippage?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Periods per year, used to annualize the Sharpe ratio. Default: inferred from the median spacing of
|
|
35
|
+
* the candles over a 365-day year (right for crypto; use 252 for daily stock candles).
|
|
36
|
+
*/
|
|
37
|
+
periodsPerYear?: number;
|
|
38
|
+
/** Close any open position at the last candle's close (default true). */
|
|
39
|
+
closeAtEnd?: boolean;
|
|
40
|
+
}
|
|
41
|
+
export interface Fill {
|
|
42
|
+
time: number;
|
|
43
|
+
side: 'buy' | 'sell';
|
|
44
|
+
quantity: number;
|
|
45
|
+
/** Execution price, slippage included. */
|
|
46
|
+
price: number;
|
|
47
|
+
fee: number;
|
|
48
|
+
}
|
|
49
|
+
/** A round trip: from a flat position to a long position and back to flat. */
|
|
50
|
+
export interface RoundTrip {
|
|
51
|
+
entryTime: number;
|
|
52
|
+
exitTime: number;
|
|
53
|
+
/** Average entry price (slippage included). */
|
|
54
|
+
entryPrice: number;
|
|
55
|
+
/** Average exit price (slippage included). */
|
|
56
|
+
exitPrice: number;
|
|
57
|
+
quantity: number;
|
|
58
|
+
/** Profit after fees. */
|
|
59
|
+
pnl: number;
|
|
60
|
+
/** `pnl` relative to the cost of entry (fees included). */
|
|
61
|
+
return: number;
|
|
62
|
+
}
|
|
63
|
+
export interface EquityPoint {
|
|
64
|
+
time: number;
|
|
65
|
+
equity: number;
|
|
66
|
+
}
|
|
67
|
+
export interface BacktestMetrics {
|
|
68
|
+
initialCash: number;
|
|
69
|
+
finalEquity: number;
|
|
70
|
+
/** finalEquity / initialCash - 1. */
|
|
71
|
+
totalReturn: number;
|
|
72
|
+
/** Largest peak-to-trough fall of equity, as a positive fraction (0.25 = -25 %). */
|
|
73
|
+
maxDrawdown: number;
|
|
74
|
+
/** Annualized Sharpe ratio of per-candle returns (risk-free rate 0). */
|
|
75
|
+
sharpe: number;
|
|
76
|
+
/** Share of round trips with a positive profit (0 when there is none). */
|
|
77
|
+
winRate: number;
|
|
78
|
+
/** Number of completed round trips. */
|
|
79
|
+
trades: number;
|
|
80
|
+
totalFees: number;
|
|
81
|
+
/** Share of candles ending with an open position. */
|
|
82
|
+
exposure: number;
|
|
83
|
+
}
|
|
84
|
+
export interface BacktestResult {
|
|
85
|
+
metrics: BacktestMetrics;
|
|
86
|
+
fills: Fill[];
|
|
87
|
+
trades: RoundTrip[];
|
|
88
|
+
/** Equity at each candle close (after that candle's fills). */
|
|
89
|
+
equity: EquityPoint[];
|
|
90
|
+
/** Orders placed on the last candle, which had no next candle to fill on. */
|
|
91
|
+
unfilledOrders: number;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Event-driven backtest on candles, long only. The strategy runs after each candle closes;
|
|
95
|
+
* its orders fill at the next candle's open, so it can never trade on prices it has not seen yet.
|
|
96
|
+
*/
|
|
97
|
+
export declare function backtest(options: BacktestOptions): BacktestResult;
|
|
98
|
+
/** Largest peak-to-trough fall, as a positive fraction. */
|
|
99
|
+
export declare function maxDrawdown(equity: readonly number[]): number;
|
|
100
|
+
/** Annualized Sharpe ratio of the simple returns of an equity series (risk-free rate 0, sample deviation). */
|
|
101
|
+
export declare function sharpe(equity: readonly number[], periodsPerYear: number): number;
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { InvalidArgumentError } from '../core/errors.js';
|
|
2
|
+
const EPS = 1e-12;
|
|
3
|
+
function settings(options) {
|
|
4
|
+
const s = {
|
|
5
|
+
initialCash: options.initialCash ?? 10_000,
|
|
6
|
+
feeRate: options.feeRate ?? 0.001,
|
|
7
|
+
slippage: options.slippage ?? 0.0005,
|
|
8
|
+
closeAtEnd: options.closeAtEnd ?? true,
|
|
9
|
+
};
|
|
10
|
+
if (!(s.initialCash > 0))
|
|
11
|
+
throw new InvalidArgumentError('backtest: initialCash must be positive');
|
|
12
|
+
if (!(s.feeRate >= 0 && s.feeRate < 1))
|
|
13
|
+
throw new InvalidArgumentError('backtest: feeRate must be in [0, 1)');
|
|
14
|
+
if (!(s.slippage >= 0 && s.slippage < 1))
|
|
15
|
+
throw new InvalidArgumentError('backtest: slippage must be in [0, 1)');
|
|
16
|
+
return s;
|
|
17
|
+
}
|
|
18
|
+
function validateCandles(candles) {
|
|
19
|
+
for (let i = 0; i < candles.length; i++) {
|
|
20
|
+
const c = candles[i];
|
|
21
|
+
if (![c.time, c.open, c.high, c.low, c.close].every(Number.isFinite) || c.open <= 0 || c.close <= 0) {
|
|
22
|
+
throw new InvalidArgumentError(`backtest: invalid candle at index ${i}`);
|
|
23
|
+
}
|
|
24
|
+
if (i > 0 && c.time <= candles[i - 1].time) {
|
|
25
|
+
throw new InvalidArgumentError(`backtest: candles must be in strictly ascending time order (index ${i})`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Cash, position, fills and round trips of a long-only account. */
|
|
30
|
+
class Account {
|
|
31
|
+
s;
|
|
32
|
+
cash;
|
|
33
|
+
position = 0;
|
|
34
|
+
totalFees = 0;
|
|
35
|
+
fills = [];
|
|
36
|
+
trades = [];
|
|
37
|
+
open = null;
|
|
38
|
+
constructor(s) {
|
|
39
|
+
this.s = s;
|
|
40
|
+
this.cash = s.initialCash;
|
|
41
|
+
}
|
|
42
|
+
execute(order, time, basePrice) {
|
|
43
|
+
if (order.side === 'buy')
|
|
44
|
+
this.buy(time, basePrice, order.quantity);
|
|
45
|
+
else
|
|
46
|
+
this.sell(time, basePrice, order.quantity);
|
|
47
|
+
}
|
|
48
|
+
buy(time, basePrice, quantity) {
|
|
49
|
+
const price = basePrice * (1 + this.s.slippage);
|
|
50
|
+
const affordable = this.cash / (price * (1 + this.s.feeRate));
|
|
51
|
+
const qty = Math.min(quantity ?? affordable, affordable);
|
|
52
|
+
if (!(qty > EPS))
|
|
53
|
+
return;
|
|
54
|
+
const notional = qty * price;
|
|
55
|
+
const fee = notional * this.s.feeRate;
|
|
56
|
+
this.cash = Math.max(0, this.cash - notional - fee);
|
|
57
|
+
this.position += qty;
|
|
58
|
+
this.totalFees += fee;
|
|
59
|
+
this.fills.push({ time, side: 'buy', quantity: qty, price, fee });
|
|
60
|
+
const open = (this.open ??= { entryTime: time, qty: 0, cost: 0, bought: 0, boughtValue: 0, sold: 0, soldValue: 0, realized: 0 });
|
|
61
|
+
open.qty += qty;
|
|
62
|
+
open.cost += notional + fee;
|
|
63
|
+
open.bought += qty;
|
|
64
|
+
open.boughtValue += notional;
|
|
65
|
+
}
|
|
66
|
+
sell(time, basePrice, quantity) {
|
|
67
|
+
const open = this.open;
|
|
68
|
+
const qty = Math.min(quantity ?? this.position, this.position);
|
|
69
|
+
if (!(qty > EPS) || !open)
|
|
70
|
+
return;
|
|
71
|
+
const price = basePrice * (1 - this.s.slippage);
|
|
72
|
+
const notional = qty * price;
|
|
73
|
+
const fee = notional * this.s.feeRate;
|
|
74
|
+
this.cash += notional - fee;
|
|
75
|
+
this.totalFees += fee;
|
|
76
|
+
this.fills.push({ time, side: 'sell', quantity: qty, price, fee });
|
|
77
|
+
const costShare = open.cost * (qty / open.qty);
|
|
78
|
+
open.realized += notional - fee - costShare;
|
|
79
|
+
open.cost -= costShare;
|
|
80
|
+
open.qty -= qty;
|
|
81
|
+
open.sold += qty;
|
|
82
|
+
open.soldValue += notional;
|
|
83
|
+
this.position -= qty;
|
|
84
|
+
if (this.position <= EPS * Math.max(1, open.bought))
|
|
85
|
+
this.closeTrade(open, time);
|
|
86
|
+
}
|
|
87
|
+
closeTrade(open, time) {
|
|
88
|
+
this.position = 0;
|
|
89
|
+
const entryCost = open.boughtValue * (1 + this.s.feeRate);
|
|
90
|
+
this.trades.push({
|
|
91
|
+
entryTime: open.entryTime,
|
|
92
|
+
exitTime: time,
|
|
93
|
+
entryPrice: open.boughtValue / open.bought,
|
|
94
|
+
exitPrice: open.soldValue / open.sold,
|
|
95
|
+
quantity: open.bought,
|
|
96
|
+
pnl: open.realized,
|
|
97
|
+
return: entryCost > 0 ? open.realized / entryCost : 0,
|
|
98
|
+
});
|
|
99
|
+
this.open = null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function order(side, quantity) {
|
|
103
|
+
if (quantity === undefined)
|
|
104
|
+
return { side };
|
|
105
|
+
if (!(quantity > 0))
|
|
106
|
+
throw new InvalidArgumentError(`${side}: quantity must be positive`);
|
|
107
|
+
return { side, quantity };
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Event-driven backtest on candles, long only. The strategy runs after each candle closes;
|
|
111
|
+
* its orders fill at the next candle's open, so it can never trade on prices it has not seen yet.
|
|
112
|
+
*/
|
|
113
|
+
export function backtest(options) {
|
|
114
|
+
const { candles, strategy } = options;
|
|
115
|
+
const s = settings(options);
|
|
116
|
+
validateCandles(candles);
|
|
117
|
+
const account = new Account(s);
|
|
118
|
+
const equity = [];
|
|
119
|
+
let pending = [];
|
|
120
|
+
let exposed = 0;
|
|
121
|
+
for (let i = 0; i < candles.length; i++) {
|
|
122
|
+
const candle = candles[i];
|
|
123
|
+
const due = pending;
|
|
124
|
+
pending = [];
|
|
125
|
+
for (const o of due)
|
|
126
|
+
account.execute(o, candle.time, candle.open);
|
|
127
|
+
strategy({
|
|
128
|
+
candle,
|
|
129
|
+
index: i,
|
|
130
|
+
position: account.position,
|
|
131
|
+
cash: account.cash,
|
|
132
|
+
equity: account.cash + account.position * candle.close,
|
|
133
|
+
lookback: (n) => candles.slice(Math.max(0, i + 1 - Math.max(0, Math.floor(n))), i + 1),
|
|
134
|
+
buy: (quantity) => void pending.push(order('buy', quantity)),
|
|
135
|
+
sell: (quantity) => void pending.push(order('sell', quantity)),
|
|
136
|
+
});
|
|
137
|
+
if (i === candles.length - 1 && s.closeAtEnd)
|
|
138
|
+
account.execute({ side: 'sell' }, candle.time, candle.close);
|
|
139
|
+
if (account.position > 0)
|
|
140
|
+
exposed++;
|
|
141
|
+
equity.push({ time: candle.time, equity: account.cash + account.position * candle.close });
|
|
142
|
+
}
|
|
143
|
+
const curve = [s.initialCash, ...equity.map((p) => p.equity)];
|
|
144
|
+
const finalEquity = curve[curve.length - 1];
|
|
145
|
+
const { trades } = account;
|
|
146
|
+
return {
|
|
147
|
+
metrics: {
|
|
148
|
+
initialCash: s.initialCash,
|
|
149
|
+
finalEquity,
|
|
150
|
+
totalReturn: finalEquity / s.initialCash - 1,
|
|
151
|
+
maxDrawdown: maxDrawdown(curve),
|
|
152
|
+
sharpe: sharpe(curve, options.periodsPerYear ?? inferPeriodsPerYear(candles)),
|
|
153
|
+
winRate: trades.length > 0 ? trades.filter((t) => t.pnl > 0).length / trades.length : 0,
|
|
154
|
+
trades: trades.length,
|
|
155
|
+
totalFees: account.totalFees,
|
|
156
|
+
exposure: candles.length > 0 ? exposed / candles.length : 0,
|
|
157
|
+
},
|
|
158
|
+
fills: account.fills,
|
|
159
|
+
trades,
|
|
160
|
+
equity,
|
|
161
|
+
unfilledOrders: pending.length,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** Largest peak-to-trough fall, as a positive fraction. */
|
|
165
|
+
export function maxDrawdown(equity) {
|
|
166
|
+
let peak = -Infinity;
|
|
167
|
+
let worst = 0;
|
|
168
|
+
for (const e of equity) {
|
|
169
|
+
if (e > peak)
|
|
170
|
+
peak = e;
|
|
171
|
+
if (peak > 0)
|
|
172
|
+
worst = Math.max(worst, 1 - e / peak);
|
|
173
|
+
}
|
|
174
|
+
return worst;
|
|
175
|
+
}
|
|
176
|
+
/** Annualized Sharpe ratio of the simple returns of an equity series (risk-free rate 0, sample deviation). */
|
|
177
|
+
export function sharpe(equity, periodsPerYear) {
|
|
178
|
+
const returns = [];
|
|
179
|
+
for (let i = 1; i < equity.length; i++) {
|
|
180
|
+
const prev = equity[i - 1];
|
|
181
|
+
if (prev > 0)
|
|
182
|
+
returns.push(equity[i] / prev - 1);
|
|
183
|
+
}
|
|
184
|
+
if (returns.length < 2)
|
|
185
|
+
return 0;
|
|
186
|
+
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
|
187
|
+
const variance = returns.reduce((a, r) => a + (r - mean) ** 2, 0) / (returns.length - 1);
|
|
188
|
+
const sd = Math.sqrt(variance);
|
|
189
|
+
return sd > 1e-15 ? (mean / sd) * Math.sqrt(periodsPerYear) : 0;
|
|
190
|
+
}
|
|
191
|
+
function inferPeriodsPerYear(candles) {
|
|
192
|
+
if (candles.length < 2)
|
|
193
|
+
return 365;
|
|
194
|
+
const gaps = [];
|
|
195
|
+
for (let i = 1; i < candles.length; i++)
|
|
196
|
+
gaps.push(candles[i].time - candles[i - 1].time);
|
|
197
|
+
gaps.sort((a, b) => a - b);
|
|
198
|
+
const median = gaps[Math.floor(gaps.length / 2)];
|
|
199
|
+
return (365 * 86_400_000) / median;
|
|
200
|
+
}
|
package/dist/cli.d.ts
ADDED