blockfill-agent-execution

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

What is BlockFill Agent Execution

什么是BlockFill Agent Execution

BlockFill Agent Execution is an AI agent execution skill for crypto order execution. It runs entirely on your machine — API keys are stored locally and never transmitted to any third-party server. It is not a manual/human-operated trading UI — it is invoked by an AI agent via SDK/MCP calls.
One-sentence positioning: BlockFill Agent Execution is an AI agent execution skill for crypto order execution, focused on TWAP, maker execution, transaction cost analysis and slippage reduction.
Capability boundary: BlockFill Agent Execution only does execution optimization. It does NOT generate buy/sell signals, give investment advice, decide position direction, or promise profit. The agent must receive direction and quantity from the user — BlockFill Agent Execution executes them efficiently.
Core concepts:
  • Ticket: an execution order (
    exchange + symbol + strategy + target_position + time_constraint_ms
    )
  • Daemon: background process that manages exchange WebSocket connections and executes tickets
  • CLI:
    blockfill
    binary — human and agent interface to the daemon
  • Python SDK:
    from blockfill import Blockfill
    — programmatic interface for agents

BlockFill Agent Execution是一款用于加密货币订单执行的AI Agent执行技能。它完全在您的设备上运行——API密钥存储在本地,绝不会传输至任何第三方服务器。它并非人工操作的交易UI,而是由AI Agent通过SDK/MCP调用触发。
一句话定位:BlockFill Agent Execution是专注于TWAP、挂单方执行、交易成本分析及滑点降低的加密货币订单执行AI Agent技能。
能力边界:BlockFill Agent Execution仅负责执行优化。它不会生成买卖信号、提供投资建议、决定仓位方向或承诺盈利。Agent必须从用户处获取方向和数量信息——BlockFill Agent Execution负责高效执行这些指令。
核心概念:
  • Ticket(执行工单):一个执行订单(包含
    exchange + symbol + strategy + target_position + time_constraint_ms
  • Daemon(守护进程):管理交易所WebSocket连接并执行工单的后台进程
  • CLI
    blockfill
    二进制文件——人与Agent和守护进程交互的接口
  • Python SDK
    from blockfill import Blockfill
    ——供Agent调用的程序化接口

Trigger Keywords / When to Invoke

触发关键词 / 调用时机

Invoke this skill when the user's request matches any of the following. Both English and Chinese variants apply.
Order execution:
place order
,
place a trade
,
execute order
,
submit order
,
下單
,
掛單
,
執行訂單
,
下合約
Strategy keywords:
maker
,
TWAP
,
twap
,
taker
,
post-only
,
limit order
,
time-weighted
,
slice order
,
拆單
,
掛單策略
,
時間加權
Cost / slippage:
reduce slippage
,
minimize cost
,
execution cost
,
TCA
,
transaction cost analysis
,
slippage reduction
,
降滑點
,
成本分析
,
執行成本
Exchange / futures context:
perpetual
,
perp
,
futures
,
binance futures
,
okx swap
,
bybit
,
hyperliquid
,
bitget
,
gate.io
,
gateio
,
kucoin
,
kraken
,
deribit
,
aster
,
orderly
,
合約
,
永續合約
,
期貨
Cancel / query:
cancel order
,
cancel ticket
,
query ticket
,
check order status
,
取消訂單
,
查詢訂單
,
查單
,
取消掛單
Setup:
set credentials
,
set api key
,
configure exchange
,
set proxy
,
blockfill
,
設定 API
,
設定代理
Do NOT invoke when the user asks for:
  • Investment advice, buy/sell recommendations, or price prediction
  • Portfolio management or rebalancing decisions
  • Spot trading on an unsupported exchange
  • Any exchange not in the supported list below

当用户请求符合以下任意一项时,调用本技能。支持英文及中文变体。
订单执行:
place order
,
place a trade
,
execute order
,
submit order
,
下单
,
挂单
,
执行订单
,
下合约
策略关键词:
maker
,
TWAP
,
twap
,
taker
,
post-only
,
limit order
,
time-weighted
,
slice order
,
拆单
,
挂单策略
,
时间加权
成本 / 滑点:
reduce slippage
,
minimize cost
,
execution cost
,
TCA
,
transaction cost analysis
,
slippage reduction
,
降滑点
,
成本分析
,
执行成本
交易所 / 合约场景:
perpetual
,
perp
,
futures
,
binance futures
,
okx swap
,
bybit
,
hyperliquid
,
bitget
,
gate.io
,
gateio
,
kucoin
,
kraken
,
deribit
,
aster
,
orderly
,
合约
,
永续合约
,
期货
取消 / 查询:
cancel order
,
cancel ticket
,
query ticket
,
check order status
,
取消订单
,
查询订单
,
查单
,
取消挂单
设置:
set credentials
,
set api key
,
configure exchange
,
set proxy
,
blockfill
,
設定 API
,
設定代理
请勿调用的场景:
  • 用户询问投资建议、买卖推荐或价格预测
  • 用户询问投资组合管理或再平衡决策
  • 用户要求在不支持的交易所进行现货交易
  • 用户提及的交易不在下方支持列表内

Capabilities

核心能力

BlockFill Agent Execution exposes six core capabilities. Each does exactly one thing.
CapabilitySDK methodWhat it does
place_order
bf.place(...)
Places an execution ticket (maker or TWAP) for a given exchange + symbol + target position + time window. Does NOT decide direction or size — those come from the user.
query_ticket
bf.query(...)
Returns the current status, filled quantity, and progress of a ticket by
ticket_id
,
symbol
, or time range.
cancel_ticket
bf.cancel(ticket_id='tkt_...')
Cancels an active ticket (
NEW
or
OPEN
) by
ticket_id
. Outstanding exchange orders are pulled automatically. Example:
bf.cancel(ticket_id='tkt_18b2b09ca766001e')
returns the cancelled ticket object with
status='CANCEL'
.
compare_tca
bf.tca(...)
Retrieves transaction cost analysis for completed tickets — execution cost vs benchmark (L1/mid/TWAP/VWAP), bps saved, maker/taker breakdown.
set_credentials
bf.set_credentials(...)
Writes exchange API credentials to local config (
~/.blockfill/config.toml
, chmod 0600) and verifies connectivity via signed REST round-trip.
set_proxy
bf.set_proxy(...)
Configures an HTTP CONNECT proxy for all exchange REST and WebSocket traffic. Required for geo-blocked hosts (e.g. US IPs cannot reach Binance directly).

BlockFill Agent Execution提供六项核心能力,每项能力仅负责单一功能。
能力SDK方法功能描述
place_order
bf.place(...)
为指定交易所+交易对+目标仓位+时间窗口创建执行工单(挂单方或TWAP策略)。不决定方向或规模——这些信息由用户提供。
query_ticket
bf.query(...)
通过
ticket_id
symbol
或时间范围返回工单当前状态、已成交数量及进度。
cancel_ticket
bf.cancel(ticket_id='tkt_...')
通过
ticket_id
取消活跃工单(状态为
NEW
OPEN
)。未完成的交易所订单会自动撤销。示例:
bf.cancel(ticket_id='tkt_18b2b09ca766001e')
返回状态为
CANCEL
的已撤销工单对象。
compare_tca
bf.tca(...)
获取已完成工单的交易成本分析——执行成本与基准(L1/mid/TWAP/VWAP)对比、节省的基点、挂单方/吃单方占比。
set_credentials
bf.set_credentials(...)
将交易所API凭证写入本地配置文件(
~/.blockfill/config.toml
,权限设置为chmod 0600),并通过签名REST往返请求验证连通性。
set_proxy
bf.set_proxy(...)
为所有交易所REST和WebSocket流量配置HTTP CONNECT代理。适用于受地理限制的主机(例如美国IP无法直接访问Binance)。

When to Use BlockFill Agent Execution

适用场景

Use BlockFill Agent Execution when the user needs to:
  • Execute a large order with reduced market impact (TWAP slicing or maker posting)
  • Minimize execution cost — maker rebates, reduced slippage vs a market order
  • Automate order execution in an AI agent trading workflow
  • Analyze execution quality — compare realized price vs L1/mid/TWAP/VWAP benchmark
  • Route orders to multiple exchanges from a single agent call
  • Execute on geo-blocked exchanges (Binance from US/CN) via proxy
Typical triggers: user has a direction and size, and wants efficient execution. BlockFill Agent Execution handles the how — not the what or why.

当用户有以下需求时,使用BlockFill Agent Execution:
  • 执行大额订单并降低市场冲击(TWAP拆分或挂单方委托)
  • 最小化执行成本——挂单方返佣、相较于市价单降低滑点
  • 在AI Agent交易工作流中自动化订单执行
  • 分析执行质量——对比实际成交价与L1/mid/TWAP/VWAP基准
  • 通过单一Agent调用将订单路由至多个交易所
  • 通过代理在受地理限制的交易所执行订单(例如从美国/中国访问Binance)
典型触发场景:用户已确定方向和规模,需要高效执行订单。BlockFill Agent Execution负责处理执行方式——而非决策交易内容或原因。

When NOT to Use BlockFill Agent Execution

不适用场景

Do NOT use BlockFill Agent Execution when:
  • The user has not specified exchange, symbol, side, or quantity — ask first, do not guess
  • The user is asking for a buy/sell recommendation or price target — BlockFill Agent Execution does not provide investment advice; redirect to the appropriate research tool
  • The target market is spot on an unsupported exchange — check the supported exchange list
  • The user wants to trade stock, forex, or non-crypto assets — out of scope
  • The environment is not configured (no API credentials, no proxy for geo-blocked hosts) — set up first, then trade
  • The user requests a position larger than their stated risk tolerance — confirm with user before proceeding
  • The user has not confirmed
    mainnet
    vs
    testnet
    default to testnet and ask before trading live

请勿在以下场景使用BlockFill Agent Execution:
  • 用户未指定交易所、交易对、方向或数量——先询问用户,不要自行假设方向、规模或环境的默认值
  • 用户询问买卖推荐或价格目标——BlockFill Agent Execution不提供投资建议;引导用户使用合适的研究工具
  • 目标市场为不支持交易所的现货交易——请核对支持交易所列表
  • 用户希望交易股票、外汇或非加密资产——超出服务范围
  • 环境未配置完成(无API凭证、受地理限制主机未设置代理)——先完成设置,再进行交易
  • 用户请求的仓位超出其声明的风险承受能力——执行前请与用户确认
  • 用户未确认
    mainnet
    (主网)与
    testnet
    (测试网)——默认使用测试网,主网交易前需确认

Before Placing an Order — Agent Checklist

下单前——Agent检查清单

Before calling
place_order
, confirm you have all required information. If any is missing, ask the user — do not assume defaults for direction, size, or environment.
ItemRequiredIf missing
ExchangeAsk: "Which exchange? (e.g. binance-futures, okx-swap)"
SymbolAsk: "Which symbol? Use native format (e.g. btcusdt for Binance)"
Side (long / short / close)Ask: "Buy or sell? What target position?"
Quantity / target positionAsk: "How much? In base asset units."
Environment (testnet / mainnet)Default to testnet. Confirm before mainnet.
StrategyDefault:
maker
. Inform user.
Time windowDefault: 300,000 ms (5 min). Inform user.
Proxy (if geo-blocked)Warn if Binance + non-whitelisted region. Offer
sc-vpn
.
调用
place_order
前,请确认已获取所有必要信息。若有缺失,询问用户——不要自行假设方向、规模或环境的默认值。
项目是否必填缺失时处理
交易所询问:"请问是哪个交易所?(例如binance-futures、okx-swap)"
交易对询问:"请问是哪个交易对?请使用交易所原生格式(例如Binance的btcusdt)"
方向(做多/做空/平仓)询问:"买入还是卖出?目标仓位是多少?"
数量 / 目标仓位询问:"数量是多少?以基础资产单位计算。"
环境(测试网/主网)默认使用测试网。主网交易前需确认。
策略默认:
maker
。告知用户。
时间窗口默认:300,000毫秒(5分钟)。告知用户。
代理(若受地理限制)若为Binance+非白名单地区,发出警告。提供
sc-vpn
选项。

Binance TradFi symbols

Binance TradFi交易对

binance-futures
also lists 157 TradFi perpetuals — equities (
tslausdt
,
nvdausdt
,
skhynixusdt
), commodities (
xauusdt
,
xagusdt
,
clusdt
) and pre-IPO (
openaiusdt
,
anthropicusdt
). Binance gates them behind a one-time account agreement; without it every order is rejected
-4411
and the ticket sits at 0% filled until it expires.
set_credentials
/
check_credentials
sign that agreement on mainnet and report
"tradfi_perps": "signed"
, so these symbols need no extra setup. If a TradFi ticket never fills, run
check_credentials()
and read that field first.
Tell the user what was accepted on their behalf: a binding agreement with Binance's ADGM-regulated entity covering 24/7 trading outside cash-market hours, no ownership of the underlying asset, and funding up to ±2.00% (vs ±0.30% for
btcusdt
). Binance provides no API to revoke it.
Note
paxgusdt
/
xautusdt
are not TradFi — ordinary gold-backed tokens, contract type
PERPETUAL
, no agreement needed.
binance-futures
还列出了157个TradFi永续合约——股票(
tslausdt
nvdausdt
skhynixusdt
)、大宗商品(
xauusdt
xagusdt
clusdt
)及Pre-IPO资产(
openaiusdt
anthropicusdt
)。Binance要求用户签署一次性账户协议才能交易这些合约;未签署时,所有订单会被拒绝(错误码
-4411
),工单会保持0%成交直至过期。
set_credentials
/
check_credentials
会在主网自动签署该协议,并返回
"tradfi_perps": "signed"
,因此这些交易对无需额外设置。若TradFi工单始终无法成交,请先运行
check_credentials()
并查看该字段。
请告知用户代为签署的协议内容:与Binance受ADGM监管实体的绑定协议,涵盖现金市场外的7×24小时交易,不持有底层资产所有权,资金费率最高±2.00%(对比
btcusdt
的±0.30%)。Binance未提供撤销该协议的API。
注意
paxgusdt
/
xautusdt
不属于TradFi——它们是普通的黄金代币,合约类型为
PERPETUAL
,无需签署协议。

Hyperliquid / Aster builder-fee approval

Hyperliquid / Aster builder-fee授权

Both DEX venues reject any order carrying an unapproved builder code — Hyperliquid with
Builder fee has not been approved
— and the ticket then sits at 0% filled until its window expires. The user must approve once, on-chain, signed by their MAIN wallet:
VenueBuilder addressApprove at
Hyperliquid (perp + spot)
0xB972e5151b20863380A3E7354dd93F1b888E3352
≥ 0.015% (1.5 bp)
Aster (perp only)
0xB972e5151b20863380A3E7354dd93F1b888E3352
≥ 0.015% (1.5 bp)
BlockFill signs this for the user. These venues take the account owner's wallet
private_key
(not a delegated agent key) precisely so it can:
check_credentials()
reads the current approval and signs
approveBuilderFee
/
approveBuilder
when ours is missing or below rate, reporting
"builder_fee": "approved just now at 0.015%"
. Only if signing fails does the check fail. Aster spot needs nothing; Aster Code is perp-only.
Tell the user what that key can do: it signs orders and this one fee authorization, and it could withdraw — the exchange no longer prevents that, only the absence of withdrawal code in the engine does. See
docs/security/trade-only-permissions.md
for the exhaustive signable-action list.
⚠️ Testnet attaches no builder code, so it never surfaces this. A testnet run can pass completely and the first mainnet order still fail. When moving a user from testnet to mainnet on these venues, re-run
check_credentials()
before placing.

这两个DEX平台会拒绝携带未授权builder代码的订单——Hyperliquid会返回
Builder fee has not been approved
,工单会保持0%成交直至时间窗口过期。用户必须通过链上操作,使用主钱包签署一次授权:
平台Builder地址授权费率要求
Hyperliquid(永续合约+现货)
0xB972e5151b20863380A3E7354dd93F1b888E3352
≥0.015%(1.5基点)
Aster(仅永续合约)
0xB972e5151b20863380A3E7354dd93F1b888E3352
≥0.015%(1.5基点)
BlockFill会代为用户签署授权。这些平台要求用户提供账户钱包的
private_key
(而非委托代理密钥),以便:
check_credentials()
会读取当前授权状态,若未授权或费率不足,则签署
approveBuilderFee
/
approveBuilder
,并返回
"builder_fee": "approved just now at 0.015%"
。仅当签署失败时,检查才会失败。Aster现货无需授权;Aster代码仅适用于永续合约。
请告知用户该密钥的权限:可签署订单和此次费用授权,也可能提取资金——交易所不再阻止该操作,仅引擎中无提取代码。详情请查看
docs/security/trade-only-permissions.md
中的可签署操作列表。
⚠️ 测试网不绑定builder代码,因此不会出现此问题。测试网运行完全正常,但首次主网订单仍可能失败。当用户从测试网切换至这些平台的主网时,下单前请重新运行
check_credentials()

Install

安装

bash
pip install blockfill                    # latest
pip install -U blockfill                 # upgrade
The wheel ships with the executor binary bundled inside (no separate download). PyPI publishes only platform-specific wheels. Currently supported:
manylinux2014_x86_64
(Linux x86_64).
The blockfill-server endpoint and API key are hardcoded into the binary at release time — users never set them.

bash
pip install blockfill                    # 安装最新版本
pip install -U blockfill                 # 升级版本
安装包中捆绑了执行器二进制文件(无需单独下载)。PyPI仅发布平台特定安装包。当前支持:
manylinux2014_x86_64
(Linux x86_64)。
blockfill-server端点和API密钥在发布时已硬编码到二进制文件中——用户无需设置。

Supported Exchanges

支持的交易所

Every venue runs perp/futures + spot from one daemon. Exchange id is
<venue>-<product>
(e.g.
binance-futures
,
okx-swap
,
bybit-perp
,
<venue>-spot
).
ExchangeExchange id (perp/futures · spot)CredentialsClass
Binance
binance-futures
·
binance-spot
api_key
,
api_secret
(HMAC or Ed25519 PEM),
testnet
CEX
OKX
okx-swap
·
okx-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Bybit
bybit-perp
·
bybit-spot
api_key
,
api_secret
,
testnet
CEX
Bitget
bitget-futures
·
bitget-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Gate.io
gateio-futures
·
gateio-spot
api_key
,
api_secret
,
testnet
CEX
KuCoin
kucoin-futures
·
kucoin-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Kraken
kraken-futures
·
kraken-spot
api_key
,
api_secret
,
testnet
CEX
Deribit
deribit-perp
·
deribit-spot
api_key
,
api_secret
,
testnet
CEX
Hyperliquid
hyperliquid-perp
·
hyperliquid-spot
private_key
(account wallet, EIP-712)
DEX
Aster
aster-perp
·
aster-spot
private_key
(account wallet, EIP-712)
DEX
Orderly
orderly-<broker>
account_id
,
orderly_secret
,
broker_id
(Ed25519; see below)
DEX
A single daemon can run all exchanges concurrently. CEX are billed by x402 quota (see Payment); DEX (Hyperliquid / Aster / Orderly) pay builder-code execution fees and have no quota.
Hyperliquid / Aster — wallet-signed DEX:
python
bf.set_credentials("hyperliquid-perp",
                   private_key="0x...")
bf.set_credentials("aster-perp",
                   private_key="0x...")
Binance Ed25519 keys — Binance Futures testnet issues Ed25519 keys (no HMAC secret). Pass
api_key
= the Ed25519 API Key id,
api_secret
= the PEM private key. The daemon auto-detects and signs with Ed25519.
python
bf.set_credentials("binance-futures",
    api_key="<Ed25519 API Key id>",
    api_secret="-----BEGIN PRIVATE KEY-----\nMC4CAQAw...\n-----END PRIVATE KEY-----",
    testnet=True)
Orderly — model each broker as its own exchange instance named
orderly-<broker>
:
python
bf.set_credentials("orderly-woofi",
    account_id="0x...", orderly_secret="ed25519:...", broker_id="woofi_pro", testnet=True)

每个平台都可通过一个守护进程运行永续合约/期货+现货交易。交易所ID格式为
<venue>-<product>
(例如
binance-futures
okx-swap
bybit-perp
<venue>-spot
)。
交易所交易所ID(永续合约/期货 · 现货)凭证要求类型
Binance
binance-futures
·
binance-spot
api_key
,
api_secret
(HMAC Ed25519 PEM),
testnet
CEX
OKX
okx-swap
·
okx-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Bybit
bybit-perp
·
bybit-spot
api_key
,
api_secret
,
testnet
CEX
Bitget
bitget-futures
·
bitget-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Gate.io
gateio-futures
·
gateio-spot
api_key
,
api_secret
,
testnet
CEX
KuCoin
kucoin-futures
·
kucoin-spot
api_key
,
api_secret
,
api_passphrase
,
testnet
CEX
Kraken
kraken-futures
·
kraken-spot
api_key
,
api_secret
,
testnet
CEX
Deribit
deribit-perp
·
deribit-spot
api_key
,
api_secret
,
testnet
CEX
Hyperliquid
hyperliquid-perp
·
hyperliquid-spot
private_key
(账户钱包,EIP-712)
DEX
Aster
aster-perp
·
aster-spot
private_key
(账户钱包,EIP-712)
DEX
Orderly
orderly-<broker>
account_id
,
orderly_secret
,
broker_id
(Ed25519;详见下文)
DEX
单个守护进程可同时运行所有交易所。CEX按x402配额计费(详见支付部分);DEX(Hyperliquid / Aster / Orderly)直接支付builder-code执行费,无配额限制。
Hyperliquid / Aster — 钱包签署型DEX:
python
bf.set_credentials("hyperliquid-perp",
                   private_key="0x...")
bf.set_credentials("aster-perp",
                   private_key="0x...")
Binance Ed25519密钥 — Binance Futures测试网使用Ed25519密钥(无HMAC密钥)。传入
api_key
= Ed25519 API密钥ID,
api_secret
= PEM私钥。守护进程会自动检测并使用Ed25519签名。
python
bf.set_credentials("binance-futures",
    api_key="<Ed25519 API Key id>",
    api_secret="-----BEGIN PRIVATE KEY-----\nMC4CAQAw...\n-----END PRIVATE KEY-----",
    testnet=True)
Orderly — 将每个经纪商视为独立的交易所实例,命名为
orderly-<broker>
:
python
bf.set_credentials("orderly-woofi",
    account_id="0x...", orderly_secret="ed25519:...", broker_id="woofi_pro", testnet=True)

Supported Symbols

支持的交易对

Each exchange uses its own native symbol format.
ExchangeFormatExamples
binance-futures
Lowercase, concatenated
btcusdt
,
ethusdt
,
solusdt
okx-swap
Dash-separated + SWAP suffix
BTC-USDT-SWAP
,
ETH-USDT-SWAP
bybit-perp
UPPERCASE, concatenated
BTCUSDT
,
ETHUSDT
bitget-futures
UPPERCASE, concatenated
BTCUSDT
,
ETHUSDT
gateio-futures
Underscore-separated
BTC_USDT
,
ETH_USDT
kucoin-futures
Contract code
XBTUSDTM
,
ETHUSDTM
kraken-futures
PF_ prefix + base/quote
PF_XBTUSD
,
PF_ETHUSD
deribit-perp
Dash-separated + PERPETUAL suffix
BTC-PERPETUAL
,
ETH-PERPETUAL
hyperliquid-perp
Coin only
BTC
,
ETH
,
SOL
aster-perp
UPPERCASE, concatenated
BTCUSDT
,
ETHUSDT
orderly-<broker>
Exchange-specific via brokerUse
bf.instruments(substring)
to discover
Use the exact format the target exchange expects — BlockFill Agent Execution does NOT cross-translate. Discover the exact string for any venue:
bash
blockfill check instrument --symbol btc

每个交易所使用其原生交易对格式
交易所格式示例
binance-futures
小写拼接
btcusdt
,
ethusdt
,
solusdt
okx-swap
短横线分隔+SWAP后缀
BTC-USDT-SWAP
,
ETH-USDT-SWAP
bybit-perp
大写拼接
BTCUSDT
,
ETHUSDT
bitget-futures
大写拼接
BTCUSDT
,
ETHUSDT
gateio-futures
下划线分隔
BTC_USDT
,
ETH_USDT
kucoin-futures
合约代码
XBTUSDTM
,
ETHUSDTM
kraken-futures
PF_前缀+基础/计价资产
PF_XBTUSD
,
PF_ETHUSD
deribit-perp
短横线分隔+PERPETUAL后缀
BTC-PERPETUAL
,
ETH-PERPETUAL
hyperliquid-perp
仅币种名称
BTC
,
ETH
,
SOL
aster-perp
大写拼接
BTCUSDT
,
ETHUSDT
orderly-<broker>
经纪商指定格式使用
bf.instruments(substring)
查询
请使用目标交易所要求的精确格式——BlockFill Agent Execution不提供跨格式转换。查询任意平台的精确交易对字符串:
bash
blockfill check instrument --symbol btc

Execution Strategies

执行策略

StrategyBehaviorWhen to use
maker
Posts PostOnly limit orders; earns maker rebate. Falls back to IOC at end of window for any unfilled remainder.Default. Cost-optimal when fill speed is not critical.
twap
Places IOC orders on a TWAP schedule across the full window — always crosses the spread.When you need guaranteed completion and accept taker cost.
Default strategy:
maker
.

策略行为适用场景
maker
提交PostOnly限价单;赚取挂单方返佣。时间窗口结束时,未成交部分自动切换为IOC订单。默认策略。当成交速度非关键时,成本最优。
twap
在整个时间窗口内按TWAP计划提交IOC订单——始终跨越买卖价差。需要保证完成订单且接受吃单方成本时使用。
默认策略:
maker

Ticket Parameters

工单参数

ParameterTypeRequiredDefaultDescription
exchange
stringSupported exchange id, e.g.
binance-futures
,
okx-swap
symbol
stringExchange-native format, e.g.
btcusdt
(Binance),
BTC-USDT-SWAP
(OKX)
target_position
floatTarget position in base asset. Positive = long, negative = short (perp). For spot: absolute base-asset holding to end up with.
strategy
string
maker
maker
|
twap
time_constraint_ms
int
300000
Execution window in milliseconds. Range: 60,000–86,400,000 (1 min to 24h). At window end, executor falls back to taker fills for any unfilled remainder.
Auto-supersede: placing a new ticket for the same
exchange+symbol
automatically cancels existing
NEW
and
OPEN
tickets for that pair.
Spot vs perp
target_position
: perp = net directional position (positive = long, negative = short). Spot = absolute base-asset holding to end up with (
target=0.001
on a 1.0 BTC balance sells 0.999; to add, set
target = current_holding + delta
).

参数类型是否必填默认值描述
exchange
string支持的交易所ID,例如
binance-futures
,
okx-swap
symbol
string交易所原生格式的交易对,例如
btcusdt
(Binance)、
BTC-USDT-SWAP
(OKX)
target_position
float基础资产的目标仓位。正数=做多,负数=做空(永续合约)。现货交易:最终持有的基础资产绝对数量。
strategy
string
maker
maker
|
twap
time_constraint_ms
int
300000
执行窗口(毫秒)。范围:60,000–86,400,000(1分钟至24小时)。窗口结束时,未成交部分自动切换为吃单方成交。
自动替换:为同一
exchange+symbol
提交新工单时,会自动取消该交易对下所有状态为
NEW
OPEN
的现有工单。
现货与永续合约的
target_position
区别
:永续合约=净方向仓位(正数=做多,负数=做空)。现货=最终持有的基础资产绝对数量(当前持有1.0 BTC,设置
target=0.001
卖出0.999 BTC;若要加仓,设置
target = 当前持有量 + 增量
)。

Ticket Schema

工单结构

json
{
    "ticket_id": "tkt_18b2b09ca766001e",
    "status": "OPEN",
    "exchange": "binance-futures",
    "symbol": "btcusdt",
    "strategy": "maker",
    "target_position": 0.5,
    "init_position": 0.0,
    "executed_position": 0.13,
    "time_constraint_ms": 300000,
    "start_time_ms": 1779287926007,
    "last_update_time_ms": 1779287935063,
    "is_expired": false,
    "cancel_reason": null
}
FieldTypeDescription
ticket_id
string
tkt_<hex>
status
string
NEW
|
OPEN
|
COMPLETE
|
CANCEL
exchange
stringExchange id used
symbol
stringNative symbol format
strategy
string
maker
|
twap
target_position
floatRequested net position
init_position
float | nullPosition at activation (null while NEW)
executed_position
floatNet delta filled so far
time_constraint_ms
intExecution window in ms
start_time_ms
int | nullSet when executor activates (NEW → OPEN)
last_update_time_ms
int | nullRefreshed on every state change
is_expired
boolTrue when window elapsed; status stays OPEN until cancelled
cancel_reason
string | null
external
|
superseded
|
stale
|
rejected
|
min_notional
|
risk_breach
|
insufficient_margin
|
paused
Note: The ticket has no
avg_price
or
cost
field. For execution cost, opportunity cost, and benchmark comparisons, call
compare_tca
(
bf.tca(...)
) — it returns
execution_cost_usd
,
opportunity_cost_usd
, and benchmarks (l1/mid/twap/vwap) per ticket.

json
{
    "ticket_id": "tkt_18b2b09ca766001e",
    "status": "OPEN",
    "exchange": "binance-futures",
    "symbol": "btcusdt",
    "strategy": "maker",
    "target_position": 0.5,
    "init_position": 0.0,
    "executed_position": 0.13,
    "time_constraint_ms": 300000,
    "start_time_ms": 1779287926007,
    "last_update_time_ms": 1779287935063,
    "is_expired": false,
    "cancel_reason": null
}
字段类型描述
ticket_id
string
tkt_<十六进制字符串>
status
string
NEW
|
OPEN
|
COMPLETE
|
CANCEL
exchange
string使用的交易所ID
symbol
string原生格式交易对
strategy
string
maker
|
twap
target_position
float请求的净仓位
init_position
float | null工单激活时的仓位(状态为NEW时为null)
executed_position
float已成交的净仓位变化量
time_constraint_ms
int执行窗口(毫秒)
start_time_ms
int | null执行器激活时设置(状态从NEW变为OPEN)
last_update_time_ms
int | null每次状态变更时刷新
is_expired
bool窗口过期时为true;状态保持OPEN直至被取消
cancel_reason
string | null
external
|
superseded
|
stale
|
rejected
|
min_notional
|
risk_breach
|
insufficient_margin
|
paused
注意:工单无
avg_price
cost
字段。如需执行成本、机会成本及基准对比,请调用
compare_tca
bf.tca(...)
)——它会返回每个工单的
execution_cost_usd
opportunity_cost_usd
及基准值(l1/mid/twap/vwap)。

Quickstart (Testnet)

快速开始(测试网)

python
from blockfill import Blockfill

bf = Blockfill()
python
from blockfill import Blockfill

bf = Blockfill()

Step 1: Set credentials (SDK default is testnet=False/MAINNET — agents MUST pass testnet=True explicitly for sandboxed testing)

步骤1:设置凭证(SDK默认testnet=False/主网——Agent必须显式传入testnet=True进行沙箱测试)

bf.set_credentials( exchange="binance-futures", api_key="...", api_secret="...", testnet=True, # ALWAYS start with testnet )
bf.set_credentials( exchange="binance-futures", api_key="...", api_secret="...", testnet=True, # 始终从测试网开始 )

Step 2: Start daemon (~50s warmup while it fetches market data)

步骤2:启动守护进程(约50秒预热时间,用于获取市场数据)

bf.start() bf.status() # DaemonStatus(running=True, ready_exchanges=['binance-futures'], ...)
bf.start() bf.status() # DaemonStatus(running=True, ready_exchanges=['binance-futures'], ...)

Step 3: Place a ticket

步骤3:创建工单

ticket = bf.place( exchange="binance-futures", symbol="btcusdt", target_position=0.1, # base asset units (BTC) strategy="maker", # default time_constraint_ms=60_000, # 60 seconds ) print(ticket.ticket_id, ticket.status)

---
ticket = bf.place( exchange="binance-futures", symbol="btcusdt", target_position=0.1, # 基础资产单位(BTC) strategy="maker", # 默认策略 time_constraint_ms=60_000, # 60秒 ) print(ticket.ticket_id, ticket.status)

---

Diagnostics

诊断工具

python
bf.check_credentials() -> None
python
bf.check_credentials() -> None

Hits a SIGNED REST endpoint per configured exchange; prints one line each:

针对每个已配置的交易所调用带签名的REST端点;每个交易所输出一行:

<name> / ✗ <name> <reason>.

✓ <名称> / ✗ <名称> <原因>.

Detects: wrong key/secret, IP whitelist mismatch, testnet/mainnet mix-up,

检测:密钥错误、IP白名单不匹配、测试网/主网混淆、

network/proxy/geo block. Auto-invoked at end of set_credentials().

网络/代理/地理限制。在set_credentials()结束时自动调用。

bf.positions() -> list[dict]
bf.positions() -> list[dict]

Aggregated positions from each running executor.

汇总每个运行中执行器的仓位。

Each entry: {exchange, symbol, size, entry_price, update_ts_ms}

每个条目:{exchange, symbol, size, entry_price, update_ts_ms}

bf.open_orders() -> list[dict]
bf.open_orders() -> list[dict]

Active orders on each configured exchange right now.

当前每个已配置交易所的活跃订单。

bf.nav() -> dict
bf.nav() -> dict

Net Asset Value across all running executors.

所有运行中执行器的净资产值(NAV)。

{exchanges: [{exchange, nav, wallet_balance, margin_value, unrealized_pnl}],

{exchanges: [{exchange, nav, wallet_balance, margin_value, unrealized_pnl}],

total_nav, exchanges_queried}

total_nav, exchanges_queried}

bf.tca(ticket_id=None, symbol=None, from_ms=None, to_ms=None, limit=100, history=False) -> list[dict]
bf.tca(ticket_id=None, symbol=None, from_ms=None, to_ms=None, limit=100, history=False) -> list[dict]

Transaction cost analysis for completed tickets.

已完成工单的交易成本分析。

history=False: active session (in-memory).

history=False:当前会话(内存中)。

history=True: persistent across all sessions (blockfill-server).

history=True:跨所有会话持久化数据(存储在blockfill-server)。

Each entry: benchmarks (l1/mid/twap/vwap), fills, maker/taker breakdown,

每个条目:基准值(l1/mid/twap/vwap)、成交记录、挂单方/吃单方占比、

execution_cost_usd, opportunity_cost_usd, duration_ms.

execution_cost_usd、opportunity_cost_usd、duration_ms。

bf.instruments(substring) -> list[dict]
bf.instruments(substring) -> list[dict]

Per-exchange instrument lookup — returns native-format symbols matching

按交易所查询交易工具——返回与substring匹配的原生格式交易对。下单前请使用此工具确认精确交易对字符串。

substring. Use this to find the exact symbol string before placing.


---

---

Proxy / Geo-bypass

代理 / 地理限制绕过

For hosts that can't reach Binance directly (US IPs return HTTP 451), route exchange REST and WebSocket traffic through an HTTP CONNECT proxy.
Starchild users — free
sc-vpn
skill, 18 countries, 500 GB/month:
python
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")   # Japan (lowest latency for Binance)
bf.set_proxy("http://sg:x@sc-vpn.internal:8080")   # Singapore
bf.set_proxy("http://hk:x@sc-vpn.internal:8080")   # Hong Kong
bf.set_proxy()                                      # clear proxy
Asia-PacificEuropeAmericas
jp
Japan
uk
United Kingdom
ca
Canada
sg
Singapore
de
Germany
br
Brazil
hk
Hong Kong
fr
France
mx
Mexico
kr
South Korea
nl
Netherlands
tw
Taiwan
ch
Switzerland
au
Australia
it
Italy
in
India
es
Spain
se
Sweden
Any HTTP CONNECT proxy also works:
python
bf.set_proxy("http://user:pass@proxy.example.com:8080")
set_proxy
restarts the daemon so the new setting takes effect. The proxy covers both REST and WebSocket — every exchange WS connection is tunneled.
Verify reachability before placing real orders:
python
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
bf.set_credentials("binance-futures", api_key=..., api_secret=...)
对于无法直接访问Binance的主机(美国IP返回HTTP 451),可通过HTTP CONNECT代理路由交易所REST和WebSocket流量。
Starchild用户——免费
sc-vpn
技能,覆盖18个国家,每月500 GB流量:
python
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")   # 日本(Binance延迟最低)
bf.set_proxy("http://sg:x@sc-vpn.internal:8080")   # 新加坡
bf.set_proxy("http://hk:x@sc-vpn.internal:8080")   # 香港
bf.set_proxy()                                      # 清除代理
亚太地区欧洲美洲
jp
日本
uk
英国
ca
加拿大
sg
新加坡
de
德国
br
巴西
hk
香港
fr
法国
mx
墨西哥
kr
韩国
nl
荷兰
tw
台湾
ch
瑞士
au
澳大利亚
it
意大利
in
印度
es
西班牙
se
瑞典
任何HTTP CONNECT代理均可使用:
python
bf.set_proxy("http://user:pass@proxy.example.com:8080")
set_proxy
会重启守护进程,使新设置生效。代理覆盖REST和WebSocket——所有交易所WS连接均通过隧道传输。
实盘交易前请验证连通性:
python
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
bf.set_credentials("binance-futures", api_key=..., api_secret=...)

set_credentials auto-runs check_credentials() — a ✓ proves both proxy + auth work.

set_credentials会自动运行check_credentials()——出现✓表示代理和认证均正常。


---

---

Failure Modes

故障排查

When something fails, diagnose in this order: credentials → proxy → environment → symbol → margin.
SymptomLikely causeFix
check_credentials
prints
✗ <exchange> IP not whitelisted
API key bound to a different IP than your current outbound IPAdd your outbound IP (or proxy IP) to the exchange API key whitelist
check_credentials
prints
✗ <exchange> connection refused
/ HTTP 451
Geo-block (e.g. US IP → Binance)Set a proxy:
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
check_credentials
prints
✗ <exchange> invalid signature
Wrong
api_secret
, or wrong key type (HMAC vs Ed25519)
Re-check credentials; Binance testnet uses Ed25519, not HMAC
Ticket stays
NEW
for >30s
Exchange not in
ready_exchanges
(executor still warming up, or failed init)
Check
bf.status()
ready_exchanges
; check
blockfill logs
for init error
Ticket
cancel_reason: min_notional
Order size × price < exchange minimum notionalIncrease quantity or use a larger notional
Ticket
cancel_reason: insufficient_margin
Not enough margin for the positionReduce quantity or add margin
Ticket
cancel_reason: rejected
Exchange rejected the order (symbol suspended, invalid params)Check symbol with
bf.instruments(substring)
; verify symbol format
status
shows
ready_exchanges: []
after >90s
Daemon failed to init one or more exchangesRun
blockfill stop && blockfill start
; check logs for error
NAV = 0 for Binance spot (testnet)Testnet does not support
getUserAsset
endpoint
Expected — testnet NAV uses market-ticker routing instead
For persistent issues, see GitLab Issues or Telegram support. See
docs/troubleshooting.md
for the full knowledge base.

出现故障时,请按以下顺序诊断:凭证 → 代理 → 环境 → 交易对 → 保证金
症状可能原因解决方法
check_credentials
输出
✗ <exchange> IP not whitelisted
API密钥绑定的IP与当前出口IP不一致将出口IP(或代理IP)添加至交易所API密钥白名单
check_credentials
输出
✗ <exchange> connection refused
/ HTTP 451
地理限制(例如美国IP访问Binance)设置代理:
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
check_credentials
输出
✗ <exchange> invalid signature
api_secret
错误,或密钥类型错误(HMAC vs Ed25519)
重新核对凭证;Binance测试网使用Ed25519,而非HMAC
工单保持
NEW
状态超过30秒
交易所不在
ready_exchanges
中(执行器仍在预热,或初始化失败)
查看
bf.status()
ready_exchanges
;查看
blockfill logs
中的初始化错误
工单
cancel_reason: min_notional
订单规模×价格 < 交易所最低名义价值增加数量或使用更大名义价值的订单
工单
cancel_reason: insufficient_margin
保证金不足以支撑仓位减少数量或追加保证金
工单
cancel_reason: rejected
交易所拒绝订单(交易对暂停、参数无效)使用
bf.instruments(substring)
检查交易对;验证交易对格式
status
显示
ready_exchanges: []
超过90秒
守护进程初始化一个或多个交易所失败运行
blockfill stop && blockfill start
;查看日志中的错误
Binance现货(测试网)的NAV=0测试网不支持
getUserAsset
端点
正常现象——测试网NAV使用市场行情路由计算
若问题持续,请查看GitLab IssuesTelegram支持群。完整知识库请查看
docs/troubleshooting.md

Payment — x402 Quota

支付——x402配额

Quota is tracked per (account, exchange) pair. Every pair starts with a free tier; quota is charged when each ticket's TCA finalizes. When the free tier runs out, buy more by paying USDC on Base via x402 — gasless EIP-3009
transferWithAuthorization
. The daemon holds the wallet key and signs locally; only the signature leaves the machine, never the key.
python
bf.set_payment("0x<64-hex private key>")     # store EVM wallet key
bf.topup("binance-futures", usdc=1.0)        # → {exchange, usdc, quota_balance, tx_hash}
CEX exchanges (Binance, OKX, Bybit, Bitget, Gate.io, KuCoin, Kraken, Deribit) use quota. DEX (Hyperliquid, Aster, Orderly) pay builder-code execution fees directly — no quota.
The blockfill-server only ever sees the signature and a de-identified (SHA-256 hashed) account id — never your exchange API key or wallet key.

配额按**(账户,交易所)对跟踪。每对初始享有免费额度**;当工单的TCA完成时扣除配额。免费额度用完后,可通过x402协议在Base链上支付USDC购买更多配额——采用无Gas的EIP-3009
transferWithAuthorization
。守护进程存储钱包密钥并在本地签名;仅签名会离开设备,密钥绝不会外传。
python
bf.set_payment("0x<64位十六进制私钥>")     # 存储EVM钱包密钥
bf.topup("binance-futures", usdc=1.0)        # → {exchange, usdc, quota_balance, tx_hash}
CEX交易所(Binance、OKX、Bybit、Bitget、Gate.io、KuCoin、Kraken、Deribit)使用配额。DEX(Hyperliquid、Aster、Orderly)直接支付builder-code执行费——无配额限制。
blockfill-server仅会看到签名和去标识化(SHA-256哈希)的账户ID——绝不会获取您的交易所API密钥或钱包密钥。

Typical Agent Flow

典型Agent工作流

python
from blockfill import Blockfill
import os

bf = Blockfill()
python
from blockfill import Blockfill
import os

bf = Blockfill()

(Optional) configure proxy first if in a geo-blocked region

(可选)若处于地理限制区域,先配置代理

Set creds — SDK automatically verifies via signed REST

设置凭证——SDK会自动通过带签名的REST请求验证

bf.set_credentials( "binance-futures", api_key=os.environ["BINANCE_API_KEY"], api_secret=os.environ["BINANCE_API_SECRET"], testnet=True, # always confirm testnet vs mainnet with user )
bf.set_credentials( "binance-futures", api_key=os.environ["BINANCE_API_KEY"], api_secret=os.environ["BINANCE_API_SECRET"], testnet=True, # 始终与用户确认测试网/主网 )

Start daemon

启动守护进程

bf.start() # auto-waits ~50s for warmup
bf.start() # 自动等待约50秒预热

Place ticket

创建工单

ticket = bf.place( exchange="binance-futures", symbol="btcusdt", target_position=0.1, # +0.1 BTC long strategy="maker", time_constraint_ms=300_000, )
ticket = bf.place( exchange="binance-futures", symbol="btcusdt", target_position=0.1, # 做多0.1 BTC strategy="maker", time_constraint_ms=300_000, )

Monitor

监控工单

import time while ticket.status in ("NEW", "OPEN"): time.sleep(5) ticket = bf.query(ticket_id=ticket.ticket_id)[0] print(f"filled: {ticket.executed_position} / {ticket.target_position}")
import time while ticket.status in ("NEW", "OPEN"): time.sleep(5) ticket = bf.query(ticket_id=ticket.ticket_id)[0] print(f"已成交: {ticket.executed_position} / {ticket.target_position}")

TCA

交易成本分析

tca = bf.tca(ticket_id=ticket.ticket_id) print(tca)
bf.stop()

---
tca = bf.tca(ticket_id=ticket.ticket_id) print(tca)
bf.stop()

---

Support

支持