快速入门
一个无依赖的 Node.js 客户端:在测试网上绑定密钥、读取订单簿与账户,并下单和撤单。
本教程使用 Node.js 22,只依赖其内置的 crypto。同样的步骤适用于任何支持 Ed25519 和小端整数的语言;字节布局与测试向量见 API 参考。
开始之前
你需要一个测试网账户号和一次性邀请码。见测试网接入。
1. 客户端库
保存为 t17.mjs。它生成的字节与交易所校验的完全一致(已用交易所自己的测试向量核对)。
// Minimal Time Seventeen client: Node.js 22+, no dependencies.
import crypto from "node:crypto";
// ---- keys ------------------------------------------------------------------
// A new key: crypto.generateKeyPairSync("ed25519"). From a 32-byte seed:
export function keyFromSeed(seedHex) {
const der = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(seedHex, "hex")]);
const privateKey = crypto.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
return { privateKey, publicKeyHex: publicKeyHex(crypto.createPublicKey(privateKey)) };
}
export function publicKeyHex(publicKey) {
return Buffer.from(publicKey.export({ format: "jwk" }).x, "base64url").toString("hex");
}
const sign = (privateKey, bytes) => crypto.sign(null, bytes, privateKey); // 64 bytes
// ---- little-endian writer --------------------------------------------------
class Out {
b = [];
u8(v) { this.b.push(v & 0xff); return this; }
u16(v) { this.b.push(v & 0xff, (v >>> 8) & 0xff); return this; }
u32(v) { for (let i = 0; i < 4; i++) this.b.push((v >>> (8 * i)) & 0xff); return this; }
u64(v) { v = BigInt(v); for (let i = 0n; i < 8n; i++) this.b.push(Number((v >> (8n * i)) & 0xffn)); return this; }
bytes(x) { for (const v of x) this.b.push(v); return this; }
done() { return Buffer.from(this.b); }
}
// ---- commands (wire encoding) ----------------------------------------------
const TIF = { gtc: 0, ioc: 1, fok: 2 };
/** New limit order. price: own-outcome ticks (1 tick = $0.000001); qty: contracts. */
export function newOrder({ id, account, market, outcome, side, tif = "gtc", price, qty, postOnly = false, reduceOnly = false }) {
const flags = (outcome === "no" ? 1 : 0) | (side === "sell" ? 2 : 0) | (postOnly ? 4 : 0) | (reduceOnly ? 8 : 0);
return new Out().u8(10).u64(id).u32(account).u32(market).u8(flags)
.u8(0).u32(0).u32(0) // kind 0 = limit (no trigger, no offset)
.u8(TIF[tif]).u64(0) // time in force, GTD time
.u32(price).u64(qty)
.u64(0) // display quantity: 0 = all visible
.u64(0) // OCO sibling: none
.done();
}
export const cancel = (account, id) => new Out().u8(11).u32(account).u64(id).done();
export const cancelAll = (account, market = null) => new Out().u8(13).u32(account).u64(market == null ? 0 : BigInt(market) + 1n).done();
/** Order id: your account in the high 32 bits, any u32 of yours in the low 32. */
export const orderId = (account, local) => (BigInt(account) << 32n) | BigInt(local >>> 0);
/** Nonce: lane (0-255) in the top 8 bits; a counter you never reuse within the lane. */
export const nonce = (lane, counter) => (BigInt(lane) << 56n) | BigInt(counter);
// ---- signed frame ----------------------------------------------------------
export function frame(privateKey, account, nonceValue, body) {
const message = new Out().bytes(Buffer.from("T17-ORDER/2")).u32(account).u64(nonceValue).bytes(body).done();
const sig = sign(privateKey, message);
return new Out().u32(account).u16(body.length).u64(nonceValue).bytes(body).bytes(sig).done();
}
/** Headers of a signed account read (valid for 30 s). */
export function accountHeaders(privateKey, account, unixMs = Date.now()) {
const sig = sign(privateKey, Buffer.from(`T17-FAST-ACCOUNT/1|${account}|${unixMs}`));
return { "x-t17-ts": String(unixMs), "x-t17-signature": sig.toString("hex") };
}2. 创建并绑定密钥
import crypto from "node:crypto";
import fs from "node:fs";
import { publicKeyHex } from "./t17.mjs";
const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519");
fs.writeFileSync("t17-key.pem", privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o600 });
const res = await fetch("https://testnet.timeseventeen.com/api/gw/v2/enroll", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ account: 1001, invite: process.env.T17_INVITE, public_key: publicKeyHex(publicKey) }),
});
console.log(res.status, await res.json()); // 200 { registered: true }将 1001 替换为你的账户号,并设置 T17_INVITE。私钥只保存在 t17-key.pem 中,不会离开本机。
3. 读取市场与账户
import crypto from "node:crypto";
import fs from "node:fs";
import { accountHeaders } from "./t17.mjs";
const API = "https://api-testnet.timeseventeen.com";
const ACCOUNT = 1001;
const key = crypto.createPrivateKey(fs.readFileSync("t17-key.pem"));
const book = await (await fetch(`${API}/v2/book/1`, { headers: { "x-t17-depth": "5" } })).json();
console.log("best bid", book.bids[0], "best ask", book.asks[0]); // [price ticks, contracts]
const account = await (await fetch(`${API}/v2/account/${ACCOUNT}`, { headers: accountHeaders(key, ACCOUNT) })).json();
console.log("cash $", (account.balance.cash - account.balance.reserved) / 1e6, "positions", account.positions);4. 下单与撤单
import crypto from "node:crypto";
import fs from "node:fs";
import { newOrder, cancel, frame, orderId, nonce } from "./t17.mjs";
const API = "https://api-testnet.timeseventeen.com";
const ACCOUNT = 1001;
const key = crypto.createPrivateKey(fs.readFileSync("t17-key.pem"));
const LANE = 2; // your own nonce lane for this program (the web terminal uses lane 1)
let counter = Date.now() * 1000;
async function send(body) {
const res = await fetch(`${API}/v2/orders`, {
method: "POST",
headers: { "content-type": "application/octet-stream" },
body: frame(key, ACCOUNT, nonce(LANE, ++counter), body),
});
return (await res.json()).results[0];
}
// Buy 10 YES in market 1 at $0.25, resting until cancelled.
const id = orderId(ACCOUNT, Math.floor(Date.now() / 1000));
console.log(JSON.stringify(await send(newOrder({ id, account: ACCOUNT, market: 1, outcome: "yes", side: "buy", tif: "gtc", price: 250_000, qty: 10 }))));
// {"Applied":{"seq":…,"events":[{"Accepted":{…}},{"Book":{…}}, …]}}
console.log(JSON.stringify(await send(cancel(ACCOUNT, id))));
// {"Applied":{"seq":…,"events":[{"Done":{"id":…,"reason":"Cancelled"}}, …]}}结果要么是 {"Applied": {seq, events}}——交易所已接受该指令,其事件说明发生了什么,包括带原因的 Rejected;要么是 {"Refused": "<reason>"}——指令没有到达订单簿(签名错误、nonce 重放、限速……)。见错误。