binance-trading-bot 环境变量完整配置指南:必填项、登录方式与 Worker 调优实战
binance-trading-bot 环境变量完整配置指南:必填项、登录方式与 Worker 调优实战
环境变量是 binance-trading-bot 进程级配置的唯一入口:认证密钥、数据库与 Redis 连接、登录方式、HTTP 端口、Worker 并发调优、可观测性与构建部署参数全部由 .env 驱动。本文以仓库自动生成的环境变量参考表(docs/_generated/config/env.md)为骨架,结合 .env.example、zod 校验 schema 与数据库连接池源码逐项展开,读完你就能从零配出一个安全、稳定、适合自己机器拓扑的实例。
这份参考表从哪来:生成管道与防漂移机制
环境变量参考表不是手写的,而是由生成脚本 scripts/docs/gen-config-tables.ts 从 packages/core/src/env/catalogue.ts 中的 ENV_CATALOGUE 渲染而来。目录文件头部的注释明确写着:不要手改,运行 bun run docs:gen 重新生成(bun run docs:gen --check 则用于 CI 校验表格是否过期)。
这条生成链路带来三重保证:
- 默认值与真实 schema 一一钉死:每个被应用解析(
parsed: true)的变量的默认值,都由 apps/api/tests/env-docs.test.ts 和 apps/worker/tests/env-docs.test.ts 通过“解析空环境”断言与 schema 默认值一致。改动默认值而不同步目录,CI 会直接失败,杜绝“文档写着 2、代码实际是 5”的漂移。 - 每个变量必须有完整说明:
description、when、expect、values全部必填,缺失即构建失败,因此目录中每一个变量都带“何时设置”和“设置后的预期”,这是运营文档而非纯参数罗列。 env-contract.json是部署契约:目录还会生成 env-contract.json,供 Helm chart 检查其 ConfigMap 和 Secret 是否覆盖了仓库全部环境变量面。每个变量都被标记为config或secret,避免把凭据放进 ConfigMap 或把普通旋钮藏进 Secret。
叙述性入口在 docs/operations/env-vars.md:它解释了通用工作流,并用 --8<-- 把本表嵌入正文。注意,策略级交易参数(网格级别、指标、通知器、技术面闸门)不是环境变量,它们存在数据库里、在应用内编辑,参见 docs/get-started/configure.md。
快速上手:怎么设置这些变量
在仓库根目录的 .env.example 基础上创建 .env,逐行编辑后重启进程:
cp .env.example .env
# 编辑 .env,然后:
bun run dev # 本地开发,Bun 自动加载 .env
# 或 Docker Compose 方式:
docker compose -f deploy/compose/docker-compose.yml --env-file .env up
启动时所有值都会经过 zod 校验:无效或缺失的必填值会直接让启动失败并报出精确错误,而不是带病运行。packages/core/src/env/schema.ts 中的 parseEnvOrThrow 会把所有 zod issue 压成一行可操作的错误信息(例如 Invalid api environment: AUTH_SECRET: String must contain at least 32 character(s))。
变量的消费方被划分为四类,这也是文档分组的依据:
| 消费方 | 含义 |
|---|---|
shared |
每个进程都读(api、worker 共用一份定义,见 packages/core/src/env/schema.ts) |
api |
仅 api 进程解析,schema 在 apps/api/src/env.ts |
worker |
仅 worker 进程解析,schema 在 apps/worker/src/env.ts |
compose |
只有 Docker Compose 读取,应用代码从不读 |
build |
Vite 在构建时烙进前端 bundle,运行时改无效 |
必填变量(Required)
以下变量没有默认值,缺失即启动失败。表格为权威参考(下同)。
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
AUTH_SECRET |
Signs your login-session cookie. | 64 hex characters | required | Always, on every deployment. Generate it with openssl rand -hex 32 — never reuse one between instances. |
No default. Boot fails if it is shorter than 32 characters. Changing it invalidates every existing session, so you are signed out. |
WEB_ORIGIN |
Comma-separated list of exact browser origins allowed for CORS, login CSRF, and the WebSocket upgrade. | comma-separated origins, no wildcards | required | Always. Set it to the address you open the app at, e.g. https://bot.example.com. List several, comma-separated, to serve the SPA on more than one origin. |
No default. Boot fails if it is empty or if any entry contains * — credentialed CORS forbids a wildcard, and allowing one would loosen the auth gate only. A mismatch shows as a browser that loads the page but cannot sign in. |
DATABASE_URL |
Postgres connection string, read by every process. | a Postgres connection string | required | Always, unless you use the bundled Compose Postgres — the compose files supply an in-network default. | No default. Boot crashes if unset rather than silently connecting to localhost, which is the failure a fallback would hide. |
REDIS_URL |
Redis connection string for the job queues and caches. | a Redis connection string | required | Always, unless you use the bundled Compose Redis. Include the password when Redis requires auth: redis://:pw@host:6379. |
No default. Boot crashes if unset, for the same reason as the database URL. |
POSTGRES_PASSWORD |
Password the bundled Postgres container initialises with. | any string | postgres — the production overlay uses a secret file instead |
On any Compose deployment. Change it from the shipped value before exposing the stack to anything. | .env.example ships postgres. The production overlay reads a deploy/secrets/* file instead and ignores this variable. Changing it after first boot does NOT change the existing database password — the container only initialises once. |
源码层面的几个关键实现点:
AUTH_SECRET的“短于 32 字符启动失败”由 apps/api/src/env.ts 的z.string().min(32)强制执行;.env.example特意把占位值设成一个过短的REPLACE_ME,就是为了让未编辑的副本在启动时失败,而不是带着公开的密钥上线。WEB_ORIGIN的解析在 apps/api/src/env.ts:逗号分隔、逐项 trim、过滤空白,然后两个.refine()分别拒绝“空列表”和“含*的项”。注释解释得很透彻:Better Auth 会把*当作 CSRF 通配符,而 CORS 与 WS 检查却是字面匹配——允许通配符只会悄悄松开认证闸门,因此三者必须全部精确匹配。DATABASE_URL/REDIS_URL在 packages/core/src/env/schema.ts 定义为z.string().min(1),没有默认值。注释明确说明:缺失必须崩溃启动,而不是静默连到localhost——那正是??回退会掩盖的故障。Compose 部署时若不设置,deploy/compose/docker-compose.yml 会提供网络内默认值(postgres://postgres:postgres@postgres:5432/binance_trading_bot与redis://redis:6379)。POSTGRES_PASSWORD是parsed: false的 compose-only 变量:只有 postgres 容器首次初始化时读取,事后修改不会改变已存在数据库的密码。生产 overlay 从deploy/secrets/*文件读取并忽略此变量。
运行时(Runtime)
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
NODE_ENV |
Selects development or production framework behaviour. | development, test, production |
development |
Rarely — the container image sets it. Set it to production if you run the app outside the image. |
Development mode adds verbose framework output and disables some caching. |
LOG_LEVEL |
Log verbosity for the worker, the loudest process in the stack. | fatal, error, warn, info, debug, trace |
info |
While debugging. Turn it back down afterwards. | debug and trace flood stdout and can fill a disk on a busy account. warn and above will hide the routine decision log you usually want. |
ROLE |
Which listeners and consumers this process runs. | all, api, worker, study |
all |
Only when splitting the stack across containers. The single-box default runs everything in one process. | all runs the api, the live worker and the backtest consumer on one event loop, which is why the tuning defaults below are conservative. Splitting into api + worker + study keeps a long backtest off the trading loop. Only the api role runs database migrations. |
LIVE_DEMO |
Turns the instance into a public, no-login sandbox. | 1 or true to enable; anything else is off |
off — the flag parses to a boolean, so the schema default is false |
Only on a throwaway public demo box. Never on an instance holding your keys. | Injects a demo operator for every anonymous request; blocks credential, notifier, backup/restore, account-creation, account-rename/delete, retention-change, diagnosis-start, fee-reconciliation, and archive-backfill routes; suppresses all notifier sending; and refuses to boot if any account is on live Binance. Trading remains interactive on Binance testnet. Only 1 or true enable it. |
MCP_ENABLED |
Mounts the authenticated MCP control plane an AI agent drives the bot through. | 1 or true to enable; anything else is off |
off — the flag parses to a boolean, so the schema default is false |
Only when you want Claude Code or ChatGPT to read and trade this instance. It is a public, internet-reachable trading surface, so leave it off until you have read the MCP architecture doc. | Off, no /api/mcp route is mounted at all and no protected-resource metadata is published, so there is no agent surface to secure rather than a guarded one to trust. On, the route is mounted behind OAuth 2.1 bearer authorization and requires MCP_RESOURCE_URL. It is refused outright while LIVE_DEMO is on, because that mode injects the operator id for anonymous callers. |
MCP_RESOURCE_URL |
Canonical resource identifier agents bind their access tokens to, normally https://<your-host>/api/mcp. |
an absolute https URL with no query string, fragment or embedded credentials, no trailing slash |
required — optional while MCP_ENABLED is off; required when it is on |
Whenever MCP_ENABLED is true. |
Must be the URL an agent actually reaches, not an internal or container address: tokens are audience-bound to this exact string, so a value that disagrees with the public hostname produces a 401 that explains nothing. A trailing slash is trimmed automatically. https is required because this value is also the auth base URL, so the issuer, the JWKS document and every authorization endpoint follow it; plain http is accepted only when the host is loopback (localhost, 127.0.0.0/8, [::1]), where the bytes never leave the machine, which is what local development uses. Boot fails if it is missing while MCP_ENABLED is true, if it is not a valid URL, if it is plaintext http on a non-loopback host, or if it carries a query string, a fragment or userinfo. |
PUBLIC_WEB_URL |
Base URL used to build tap-through links inside operator notifications. | an absolute URL, no trailing slash | required — optional: unset means notifications send without a link | When you want a Slack or Telegram alert to link straight to the relevant screen. | Optional. Unset, notifications still send — just without a link. A trailing slash is trimmed automatically. Boot fails if the value is not a valid URL. |
源码要点:
- 布尔类变量(
LIVE_DEMO、MCP_ENABLED)都通过 packages/core/src/env/schema.ts 的booleanEnvFlag()解析:只有字面1或true(大小写不敏感)算开启,false、0、未设置统统为关。注释说明这是刻意避开z.coerce.boolean()——后者会把任何非空字符串(甚至'false')都当成 true。 ROLE决定进程跑哪些监听器与消费者。docker-compose.yml默认ROLE=all单进程跑全部;横向拆分见 deploy/compose/docker-compose.scale.yml(将app停用,改为独立的 api/worker/study 服务,用同一个镜像)。MCP_ENABLED与LIVE_DEMO的组合被 apps/api/src/env.ts 的.refine()直接拒绝启动:demo 模式为每个匿名请求注入同一个操作者身份,此时再挂 MCP 控制面等于在“无人需要证明身份”的盒子上发布整个 OAuth 授权服务器及其发现文档。想开 MCP 控制面,先读 docs/architecture/mcp.md。MCP_RESOURCE_URL的校验最严格:url()+ “必须 https 或 loopback http” + “无 query/fragment/userinfo”三个 refine 叠加,末尾还会自动去掉尾部斜杠。理由在源码注释里:这个值既是 OAuth 资源标识符、又是 Better Auth 的baseURL,明文 http 会把 issuer、JWKS 文档和每个授权端点暴露在存有 Binance API 密钥的机器上。豁免键在主机名而非NODE_ENV,因为真正重要的是“字节不离开机器”,而不是环境变量名。
登录方式(Sign-in)
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
PASSWORD_SIGN_IN_ENABLED |
Whether the sign-in page offers the email and password form. | 1, true, 0 or false; any other value fails boot |
on — the flag parses to a boolean, so the schema default is true |
Turn it off once single sign-on works and you want the identity provider, and the multi-factor authentication you turned on there, to be the only way in. | Off, the form is hidden and the password sign-in and sign-up endpoints answer 404. A mistyped value fails boot rather than silently turning the form off. At least one of this and SINGLE_SIGN_ON_ENABLED must be on. If single sign-on then cannot be reached at boot and no other method works, password sign-in is switched back on for that run and a security alert is sent, so the instance is never left with no way in. The reset-password command works either way. |
SINGLE_SIGN_ON_ENABLED |
Offers "sign in with single sign-on" through an OpenID Connect identity provider such as Auth0. | 1 or true to enable; anything else is off |
off — the flag parses to a boolean, so the schema default is false |
When you want your identity provider (and its multi-factor authentication) to guard sign-in. | On, it requires SINGLE_SIGN_ON_ISSUER_URL, SINGLE_SIGN_ON_CLIENT_ID, SINGLE_SIGN_ON_CLIENT_SECRET and PUBLIC_BASE_URL, and it is refused together with LIVE_DEMO. The provider is checked at boot with a 5-second limit; if it cannot be reached the app still starts with the button disabled, raises a security alert, and exits once the provider answers again so it restarts with the provider registered. That restart depends on the container restart policy (restart: unless-stopped in the prod and scale compose files); with no policy the api stays stopped. Only the identity that created the operator, or one linked later from Settings > Security, can sign in; nobody else can create an account through it. |
SINGLE_SIGN_ON_ISSUER_URL |
The identity provider's issuer, for example https://your-tenant.auth0.com/. |
an absolute https URL, written exactly as the provider publishes it |
required — optional while SINGLE_SIGN_ON_ENABLED is off; required when it is on |
Whenever SINGLE_SIGN_ON_ENABLED is on. |
It is compared character for character with the issuer in the provider's discovery document and with every ID token, so keep the trailing slash Auth0 uses. A mismatch disables single sign-on at boot. Plain http is accepted only for a loopback host. |
SINGLE_SIGN_ON_CLIENT_ID |
Identifies this app to the identity provider. | the client ID of the application you created at the provider | required — optional while SINGLE_SIGN_ON_ENABLED is off; required when it is on |
Whenever SINGLE_SIGN_ON_ENABLED is on. |
A wrong value makes the provider refuse the sign-in; the app records the failure and the sign-in page shows a plain error. |
SINGLE_SIGN_ON_CLIENT_SECRET |
Proves to the identity provider that sign-in requests really come from this app. | the client secret of the application you created at the provider | required — optional while SINGLE_SIGN_ON_ENABLED is off; required when it is on |
Whenever SINGLE_SIGN_ON_ENABLED is on. |
Kept in the environment only, never in the database, so a stolen session cannot read or change it. Rotating it at the provider needs a restart with the new value. |
SINGLE_SIGN_ON_BUTTON_LABEL |
The text on the single sign-on button, for example Sign in with Auth0. |
1 to 40 characters | Single sign-on |
When you want the button to name your provider. | Shown only when single sign-on is enabled. Boot fails if it is empty or longer than 40 characters. |
PUBLIC_BASE_URL |
The address you reach this app at, as the browser sees it. | an origin only, for example https://bot.example.com: scheme, host and optional port, no path |
required — optional while SINGLE_SIGN_ON_ENABLED is off; required when it is on |
Whenever SINGLE_SIGN_ON_ENABLED is on. Register <PUBLIC_BASE_URL>/api/auth/callback/oidc as the callback URL at the provider. |
The single sign-on callback address is built from it, never from request headers, so a proxy or a forged Host header cannot redirect a sign-in elsewhere. Must be https except on a loopback host, and must share its origin with MCP_RESOURCE_URL when both are set. |
源码要点:
PASSWORD_SIGN_IN_ENABLED用的是严格枚举解析(z.enum(['0','1','true','false'])),而不是宽松布尔解析:因为默认值是开,宽松解析会把yes这种手误静默变成“关”,症状只是一张缺失的表单。四个.refine()依次保证:密码与 SSO 至少开一个;SSO 开启时四个配套变量齐全;SSO 与LIVE_DEMO互斥;PUBLIC_BASE_URL与MCP_RESOURCE_URL同源。SINGLE_SIGN_ON_ISSUER_URL被“按原样保留”(包括尾部斜杠),因为它是与 provider 发现文档的iss声明逐字节比较的,而 Auth0 的 issuer 以斜杠结尾。- 完整的安全与运维说明见 docs/operations/sign-in-and-security.md;
reset-password命令行工具在 apps/api/scripts/reset-password.ts,无论哪种登录方式开启与否都可用。
HTTP 与 Admin 端口
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
PORT |
Port serving the API and the single-page app. | a port number | 3000 |
If 3000 is already taken on the host. | Must differ from the admin port, or boot fails with a clear message rather than a port-in-use crash. |
ADMIN_PORT |
Port for the api's health and metrics endpoints. | a port number | 9100 |
If 9100 is taken. Kept separate from the public port so a slow scrape cannot starve it. | Serves /healthz, /readyz and /metrics, all unauthenticated. |
ADMIN_HOST |
Interface the api's admin server binds. | an interface address | 127.0.0.1 |
On Kubernetes, set it to 0.0.0.0 so the kubelet probes reach the pod IP. |
The default binds loopback only, keeping the unauthenticated admin endpoints off the LAN. If you open it up, restrict the port with a NetworkPolicy — a Service is not a firewall. |
WORKER_ADMIN_PORT |
Port for the worker's health and metrics endpoints. | a port number | 9101 |
If 9101 is taken on the host. | Defaults to one above the api's so both can run on one host during development. Inside Compose each container has its own loopback, so they could share a port. |
WORKER_ADMIN_HOST |
Interface the worker's admin server binds. | an interface address | 127.0.0.1 |
On Kubernetes, for the same probe reason as the api. | Loopback by default; the same NetworkPolicy caveat applies if you widen it. |
APP_HTTP_PORT |
Host port the app publishes on under Docker Compose. | a host port number | 80 — unset, the base and scale compose files publish on 3000 and the production file on 80 |
To publish on a port other than the compose default, e.g. behind a reverse proxy on 8080. | Compose-only; the application never reads it. Unset, the base and scale compose files publish on 3000 and the production file on 80. |
源码要点:
PORT与ADMIN_PORT的互斥由 apps/api/src/env.ts 的.refine((env) => env.PORT !== env.ADMIN_PORT)在环境解析阶段就拦住——避免两个监听器第二个 bind 时的EADDRINUSE崩溃,给操作者一条清晰消息而非裸错误。ADMIN_HOST/WORKER_ADMIN_HOST默认只绑 loopback,把未认证的/healthz、/readyz、/metrics隔离在局域网之外;Kubernetes 下才需要0.0.0.0让 kubelet 探针能到达 Pod IP,并配 NetworkPolicy 收紧端口(注释原话:“Service 不是防火墙”)。APP_HTTP_PORT在 deploy/compose/docker-compose.yml 中体现为'${APP_HTTP_PORT:-3000}:3000',是纯 compose 层端口发布,应用从不读取。
数据库
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
POSTGRES_DB |
Database name the bundled Postgres creates on first boot. | a Postgres identifier | binance_trading_bot — compose-only |
Rarely. Change it only before the first boot — it has no effect afterwards. | Compose-only. The application reads the database name out of the connection string, not from here, so changing one without the other breaks the connection. |
POSTGRES_USER |
Superuser the bundled Postgres creates on first boot. | a Postgres identifier | postgres — compose-only |
Rarely, and only before first boot. | Compose-only, and subject to the same first-boot-only caveat as the database name. |
PGSSLMODE |
libpq SSL mode used by the backup and restore commands. | disable, allow, prefer, require, verify-ca, verify-full |
prefer |
When Postgres is behind TLS and you want backups to require or verify it. | Applies to pg_dump and pg_restore only — the app's own driver has its own SSL configuration and ignores this. .env.example ships disable for a local plaintext Postgres. |
API_DB_POOL_MAX |
Maximum Postgres connections the api process opens. | a positive integer | 10 — hard-coded in packages/db/src/pool.ts; no zod schema parses it |
When Postgres reports too many clients, or when the api queues behind its own pool under load. | Read straight off the environment, and only a plain run of digits is accepted: 10.5, 1e3 and +5 all fail pool creation outright, while an empty or whitespace-only value falls back to the default. Every replica opens up to this many connections, so the server-side limit is this times the replica count. Exhausting the pool no longer hangs: a checkout that waits longer than the 5s deadline in packages/db/src/pool.ts fails, and the request answers 503 SERVICE_UNAVAILABLE with a db_pool_checkout_timeout warn line naming the path — so raising this value is a response to those 503s, not to a silent stall. Raise it only for that log name. Its sibling db_connect_timeout is the same 5s deadline expiring on a new connection the database never finished accepting, which means the pool had room and more connections would only aim more concurrent attempts at a server already failing to answer. |
WORKER_DB_POOL_MAX |
Maximum Postgres connections the worker process opens. | a positive integer | 25 — hard-coded in packages/db/src/pool.ts; no zod schema parses it |
For the same reasons as the api pool. The worker default is larger because tick jobs run concurrently. | Sized against TICK_CONCURRENCY: set it below that and ticks serialise on connection checkout rather than on the concurrency limit you configured. Read straight off the environment, and only a plain run of digits is accepted: 10.5, 1e3 and +5 all fail pool creation outright, while an empty or whitespace-only value falls back to the default. |
ADMIN_DB_POOL_MAX |
Maximum Postgres connections the migration and maintenance pool opens. | a positive integer | 2 — hard-coded in packages/db/src/pool.ts; no zod schema parses it |
Almost never. This pool runs migrations and admin tasks, which are serial by nature. | Deliberately tiny so a maintenance task cannot starve the trading pools. Raising it buys nothing, because nothing here runs in parallel. Read straight off the environment, and only a plain run of digits is accepted: 10.5, 1e3 and +5 all fail pool creation outright, while an empty or whitespace-only value falls back to the default. |
源码要点(这是文档里最有深度的部分,全部由 packages/db/src/pool.ts 落实):
- 三个池的默认值硬编码在
DEFAULT_MAX中:api 10、worker 25、admin 2,不经任何 zod schema 解析,直接envMaxFor()读process.env。 - 严格数字解析:
/^\d+$/全串数字才通过,且必须是 safe integer 且大于 0。10.5、1e3、+5全部直接抛错让启动失败;空串或纯空白按“未设置”回退默认。原因在注释里:Number.parseInt会把1e3读成 1、10abc读成 10,一个想要一千连接的运营者会静默只拿到一个。 - 5 秒 checkout 超时(
POOL_CHECKOUT_TIMEOUT_MS = 5_000)同时武装了 pg-pool 的两个计时器:队列等待(池满,无连接释放)和冷连接(新建连接握手超时)。两者不是同一故障,修复方向相反:queue-wait是容量问题,加连接有用;cold-connect说明池子没满、数据库本身应答失败,再加连接只会向一个已经失败的服务器发射更多并发尝试。api 把拒绝翻译成 503SERVICE_UNAVAILABLE并打db_pool_checkout_timeoutwarn 日志;worker 则表现为 BullMQ 普通任务失败。 - 诊断线索:看到
db_pool_checkout_timeout才需要调大API_DB_POOL_MAX,看到db_connect_timeout则不要动池子大小。
保留期(Retention,按天数清理)
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
DISCOVERY_SNAPSHOT_RETENTION_DAYS |
How long auto-discovery universe snapshots are kept. | a positive integer | 180 |
Raise it before running a discovery net-edge backtest, which needs a long series. | Deliberately generous, because this series is meant to accumulate. A short horizon defeats its purpose and cannot be backfilled. |
EQUITY_SNAPSHOT_RETENTION_DAYS |
How long the per-profile equity series behind the profit-vs-hold chart is kept. | a positive integer | 365 |
Raise it to keep a multi-year equity curve. | Roughly 96 rows per profile per day, so the storage cost is modest. Trimming it shortens the chart permanently. |
源码要点:
- 两个保留期都由 apps/worker/src/env.ts 以
z.coerce.number().int().positive()解析,分别驱动discovery-snapshot-prune与 equity-snapshot 清理 cron。注释强调:discovery 快照系列是刻意要累积的(供净边回测使用),设太短会毁掉它的用途且无法回填。 - 注意:操作日志与审计日志的保留不是环境变量,而是存在
retention_config表中、在 Settings → Retention 界面编辑。.env.example注释解释了这个设计——同一个时间窗若有两个所有者,就会重现“表被提前几天清掉而面板还显示旧值”的教训。
Worker 调优
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
BACKTEST_CONCURRENCY |
How many backtest replays may run at once. | a positive integer | 1 |
Raise it on a dedicated backtest box; keep it at 1–2 when the worker shares a core with live trading. | Replays are CPU-bound, so raising this on a shared box adds tail latency to the dashboard and the trading loop. .env.example ships 4 for a dedicated study box. |
STUDY_CPU_SHARE |
Fraction of one core a backtest replay may consume. | a number in (0, 1] | required — resolved at boot: 0.5 under ROLE=all, else 1.0 |
To trade backtest speed against live responsiveness when both share a process. | Unset resolves to 0.5 under ROLE=all and 1.0 for a dedicated worker or study process, so the default already does the right thing. The runner sleeps at yield points to hold the share, so a low value makes backtests proportionally slower. |
TICK_CONCURRENCY |
How many per-symbol tick jobs may run at once. | a positive integer | 25 |
Lower it if the dashboard feels sluggish while many symbols are active under ROLE=all. |
Ordering per (profile, symbol) is enforced regardless of this value, so lowering it only reduces throughput — never correctness. |
KLINE_CONCURRENCY |
How many Binance candle fetches the technicals job runs at once per interval. | a positive integer | 8 |
Lower it if technical-rating computation is monopolising the event loop, or to reduce burst request weight. | Each fetched symbol then runs synchronous indicator maths, so this bounds how many bursts stack up. |
TICK_PERSIST_TIMEOUT_MS |
Time budget for the durable per-tick strategy-state write. | a positive integer, milliseconds | 100 |
Raise it on network-replicated storage, where a commit is a cross-node round trip. | On timeout the tick falls back to a degraded cache path, which is safe but is meant to be rare. Left too low on slow storage, the fallback becomes the steady state. The default suits a local SSD. |
WORKER_FRAME_TRACE |
Records live tick inputs and decisions as JSONL for deterministic replay. | 1 to enable; anything else is off |
off — read directly by the frame-recorder factory; unset is off |
Only while diagnosing replay drift, then disable it and protect or delete the trace. | Each completed strategy tick appends balances, holdings, inputs, and decisions. The trace contains financial state and must not be committed. |
WORKER_FRAME_TRACE_FILE |
Output path for the optional worker frame trace. | a writable file path | worker-frame-trace.jsonl under the OS temp directory — resolved at runtime by tmpdir() when unset |
When the default temporary path is unsuitable for a short diagnostic capture. | Used only when WORKER_FRAME_TRACE=1. Write failures are reported without stopping the trading tick. |
WORKER_REPLICAS |
Live-worker replica count in the scale compose file. | a positive integer | 1 — compose-only |
Keep it at 1. Multi-replica scale-out is merged but dormant. | Compose interpolates it into the service replica count; application code never reads it. Raising it today runs untested concurrency paths. |
源码要点:
STUDY_CPU_SHARE的默认解析在 apps/worker/src/env.ts 的resolveStudyCpuShare():显式值优先,否则ROLE=all取 0.5、专用 worker/study 进程取 1.0。schema 层用z.coerce.number().gt(0).lte(1).optional()校验。BACKTEST_CONCURRENCY的 schema 默认是 1,而.env.example给专用 study 盒子发的是 4——这正是目录里shippedDefault与def分离的典型例子,envGaps()会校验.env.example与目录声明一致。TICK_CONCURRENCY的注释点明:per-key 顺序由chainByKey+jobId合并强制保证,与并发值无关,所以调低只降低不同 (profile, symbol) 键的吞吐,绝不损正确性。TICK_PERSIST_TIMEOUT_MS控制持久化symbol_statesCAS 写入的预算:超时后 tick 退回降级缓存路径(经 Redis 保持 read-your-writes),默认 100ms 适合本地 SSD;网络复制块存储(如 Longhorn)上一次提交 fsync 是跨节点往返,应调高,否则降级路径会变成常态。WORKER_FRAME_TRACE由 frame-recorder 工厂直读,实现在 apps/worker/src/tick/frame-recorder.ts,测试在 apps/worker/tests/tick/frame-recorder.test.ts,流水线文档见 docs/architecture/worker-pipeline.md。它记录的是金融状态,绝不能提交进版本库。
可观测性(OpenTelemetry)
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
OTEL_SERVICE_NAME |
Service name stamped on exported traces. | any string | binance-trading-bot — compose-only |
When you export traces and run more than one instance. | Ignored unless the OTLP endpoint below is set. |
OTEL_EXPORTER_OTLP_ENDPOINT |
OTLP collector endpoint. Setting it is what enables trace export. | a collector URL | required — compose-only; empty disables the exporter | When you have a collector to send traces to. | Empty by default, so the exporter is off and no telemetry leaves the box. |
OTEL_EXPORTER_OTLP_HEADERS |
Extra headers attached to the OTLP export request. | key=value pairs |
required — compose-only; empty by default | When your collector needs authentication. | Treat the value as a credential — it typically carries a token. |
OTEL_EXPORTER_OTLP_TIMEOUT |
Timeout for one OTLP trace export request. | milliseconds | 3000 — read directly by the OpenTelemetry bootstrap when export is enabled |
Raise it only when a reachable collector routinely needs more than three seconds. | A timed-out export is counted as a dropped span batch. Trading work continues without waiting for telemetry. |
DEPLOY_ENV |
Deployment environment attached to exported traces. | an environment name such as development, staging, or production |
development — read directly; unset falls back to NODE_ENV, then development |
When the deployment name should differ from NODE_ENV. |
production enables sampled tracing; other values keep the always-on development sampler unless code supplies an explicit environment. |
源码要点:
OTEL_EXPORTER_OTLP_ENDPOINT为空即关闭 exporter——设置它才是开启 trace 导出的动作,默认情况下没有任何遥测离开机器。OTEL_EXPORTER_OTLP_HEADERS在目录中被标记为kind: 'secret':它携带 collector 的认证令牌,部署时必须走 Secret 而非 ConfigMap。配套 collector 配置见 deploy/observability/otel-collector.yaml,告警规则见 deploy/observability/alerts.yml。- 导出超时(3 秒)只计一次 dropped span batch,交易工作不会等待遥测。
构建与部署
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
IMAGE_TAG |
Image tag Docker Compose pulls. | a Docker tag | latest — compose-only |
To pin a release instead of tracking the moving latest tag. | The default moves with every release, so an unpinned deployment can change under you on the next pull. |
BACKUP_DIR |
Directory the scheduled backup writes dump files into. | an absolute path | /backups |
To write backups somewhere other than the bundled volume. | The backup job creates the directory if missing, and the backup screen lists what is there. Point it outside the container volume and the dumps will not survive a container rebuild. |
GIT_SHA |
Build commit stamped into the image, surfaced on the status endpoint. | a git commit sha | "" |
Never by hand — the Docker build injects it. | Empty in a local build, where boot falls back to the local git commit or unknown. It is what lets the status bar spot api/worker version skew. |
WEB_DIST_DIR |
Directory of the built web app the api serves. | a directory path | apps/web/dist |
Never by hand — the container image sets it. | If the directory is absent the api serves no web app at all, which is correct during development (Vite serves it) and for an api behind a CDN. |
源码要点:
BACKUP_DIR在 packages/core/src/env/schema.ts 默认/backups,与 compose 的 bind mount 一致(deploy/compose/docker-compose.yml 中 Postgres 与 app 容器都挂载./../../backups:/backups)。备份的调度(开关、间隔小时数、保留份数)在应用内 Account → Backup 配置,不走环境变量。GIT_SHA由 Docker build-arg 注入(compose 中GIT_SHA: ${GIT_SHA:-}),空值回退本地 git commit 或unknown,状态条用它来发现 api/worker 版本错位。WEB_DIST_DIR默认为仓库相对路径apps/web/dist,容器镜像会覆盖为构建产物的实际路径;目录缺失时 api 不提供任何前端——这在开发期(Vite 自服务)和 CDN 后面都是正确行为。
Web 构建期变量(build-time only)
| Variable | What it is | Values | Default | When to set it | What to expect |
|---|---|---|---|---|---|
VITE_API_BASE_URL |
Base URL the web app calls. | a URL path or absolute URL | /api — build-time only |
Only when the API is served under a different base path. | Baked into the bundle at build time. Changing it after the build has no effect — you must rebuild. |
VITE_PWA |
Builds the app as an installable progressive web app. | 0 or 1 |
0 — build-time only |
To install the dashboard to a phone home screen. | Build-time only. Enabling it adds a service worker, which caches aggressively — expect to hard-refresh after a deploy. |
这两个变量在 bun run build / compose build 之前设置,由 Vite 在构建时烙进 bundle,运行时修改无效。.env.example 注释明确警告:开启 PWA 会加入 aggressive 缓存的 service worker,部署后要硬刷新。
实战配置模板:三套典型拓扑
把上面的参数串成可直接落地的三份配置:
1. 单机开发(host dev)——直接 cp .env.example .env 即可,核心几行:
NODE_ENV=development
LOG_LEVEL=info
ROLE=all
WEB_ORIGIN=http://localhost:5173
AUTH_SECRET=<openssl rand -hex 32 的输出>
DATABASE_URL=postgres://postgres:postgres@localhost:55432/binance_trading_bot
REDIS_URL=redis://localhost:56379
PORT=3000
ADMIN_PORT=9100
WORKER_ADMIN_PORT=9101
注意:bun run dev 会同时拉起一个 ROLE=study 的第二个 worker,它把 admin 端口固定到 9102(见 .env.example 注释)。
2. 生产单机(Compose,ROLE=all)——用 deploy/compose/docker-compose.yml 加 deploy/compose/docker-compose.prod.yml:
# 生产密钥绝不放在 .env:放入 deploy/secrets/*,由 prod overlay 读取
AUTH_SECRET=<openssl rand -hex 32 的输出,且与 .env 中不同来源>
WEB_ORIGIN=https://bot.example.com
DATABASE_URL=postgres://postgres:postgres@postgres:5432/binance_trading_bot
REDIS_URL=redis://redis:6379
NODE_ENV=production
APP_HTTP_PORT=80
IMAGE_TAG=v1.0.0 # 固定版本,别追 latest
3. 拆分拓扑(Compose scale)——用 deploy/compose/docker-compose.scale.yml 把 app 停用,拆成 api/worker/study 三个服务(同一镜像,ROLE 各司其职),此时 STUDY_CPU_SHARE 未设置会自动解析为 1.0(专用进程全速回测),BACKTEST_CONCURRENCY 可放心提到 4。
4. 公开演示盒(Live demo)——用 deploy/compose/docker-compose.demo.yml,核心是 LIVE_DEMO=1,同时把 MCP_ENABLED 与 SINGLE_SIGN_ON_ENABLED 保持关闭(两个组合都会被启动校验拒绝)。
排查速查:常见启动失败与对应变量
| 现象 | 变量 | 根因 |
|---|---|---|
启动即报 String must contain at least 32 character(s) |
AUTH_SECRET |
未用 openssl rand -hex 32 生成,或沿用 REPLACE_ME |
| 页面加载了但无法登录 | WEB_ORIGIN |
与浏览器地址不一致(含端口),或写了 * 通配符 |
Invalid api environment: PORT and ADMIN_PORT must differ |
PORT / ADMIN_PORT |
两个端口撞在一起 |
| 回测 401 且报错不说明原因 | MCP_RESOURCE_URL |
与 agent 实际到达的公网地址不一致(令牌 audience 绑定该字符串) |
启动时 MCP_ENABLED and LIVE_DEMO cannot both be true |
MCP_ENABLED / LIVE_DEMO |
demo 盒上挂 MCP 控制面被拒绝 |
api 报 503 SERVICE_UNAVAILABLE + db_pool_checkout_timeout |
API_DB_POOL_MAX |
池满且 5 秒无连接释放,此时才需要调大池子 |
同一条日志出现 db_connect_timeout |
API_DB_POOL_MAX |
数据库本身握手超时,加连接只会更糟 |
结语:把“文档”当成一张自检清单
binance-trading-bot 的环境变量体系有一个少见的工程特性:这份参考表本身就是代码的产物,且由测试钉死——每个默认值、每段“何时设置/预期结果”都与实际解析的 zod schema 一一对应,CI 绿则文档不可能撒谎。因此配置时不需要在文档与源码之间来回猜,直接以本文表格为准即可;部署到 Kubernetes/Helm 时,以 env-contract.json 校验 ConfigMap 与 Secret 的覆盖完整性。记住三条原则:密钥类变量(AUTH_SECRET、DATABASE_URL、REDIS_URL、SINGLE_SIGN_ON_CLIENT_SECRET、OTEL_EXPORTER_OTLP_HEADERS)永远走 Secret;只有 1 或 true 才算开启布尔开关;改完任何变量都要重启进程让 zod 校验重新生效。