blockfill-agent-execution
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWhat 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: binary — human and agent interface to the daemon
blockfill - Python SDK: — programmatic interface for agents
from blockfill import Blockfill
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:二进制文件——人与Agent和守护进程交互的接口
blockfill - Python SDK:——供Agent调用的程序化接口
from blockfill import Blockfill
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 orderplace a tradeexecute ordersubmit order下單掛單執行訂單下合約Strategy keywords:
, , , , , , , , , ,
makerTWAPtwaptakerpost-onlylimit ordertime-weightedslice order拆單掛單策略時間加權Cost / slippage:
, , , , , , , ,
reduce slippageminimize costexecution costTCAtransaction cost analysisslippage reduction降滑點成本分析執行成本Exchange / futures context:
, , , , , , , , , , , , , , , , ,
perpetualperpfuturesbinance futuresokx swapbybithyperliquidbitgetgate.iogateiokucoinkrakenderibitasterorderly合約永續合約期貨Cancel / query:
, , , , , , ,
cancel ordercancel ticketquery ticketcheck order status取消訂單查詢訂單查單取消掛單Setup:
, , , , , ,
set credentialsset api keyconfigure exchangeset proxyblockfill設定 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 orderplace a tradeexecute ordersubmit order下单挂单执行订单下合约策略关键词:
, , , , , , , , , ,
makerTWAPtwaptakerpost-onlylimit ordertime-weightedslice order拆单挂单策略时间加权成本 / 滑点:
, , , , , , , ,
reduce slippageminimize costexecution costTCAtransaction cost analysisslippage reduction降滑点成本分析执行成本交易所 / 合约场景:
, , , , , , , , , , , , , , , , ,
perpetualperpfuturesbinance futuresokx swapbybithyperliquidbitgetgate.iogateiokucoinkrakenderibitasterorderly合约永续合约期货取消 / 查询:
, , , , , , ,
cancel ordercancel ticketquery ticketcheck order status取消订单查询订单查单取消挂单设置:
, , , , , ,
set credentialsset api keyconfigure exchangeset proxyblockfill設定 API設定代理请勿调用的场景:
- 用户询问投资建议、买卖推荐或价格预测
- 用户询问投资组合管理或再平衡决策
- 用户要求在不支持的交易所进行现货交易
- 用户提及的交易不在下方支持列表内
Capabilities
核心能力
BlockFill Agent Execution exposes six core capabilities. Each does exactly one thing.
| Capability | SDK method | What it does |
|---|---|---|
| | 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. |
| | Returns the current status, filled quantity, and progress of a ticket by |
| | Cancels an active ticket ( |
| | Retrieves transaction cost analysis for completed tickets — execution cost vs benchmark (L1/mid/TWAP/VWAP), bps saved, maker/taker breakdown. |
| | Writes exchange API credentials to local config ( |
| | 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方法 | 功能描述 |
|---|---|---|
| | 为指定交易所+交易对+目标仓位+时间窗口创建执行工单(挂单方或TWAP策略)。不决定方向或规模——这些信息由用户提供。 |
| | 通过 |
| | 通过 |
| | 获取已完成工单的交易成本分析——执行成本与基准(L1/mid/TWAP/VWAP)对比、节省的基点、挂单方/吃单方占比。 |
| | 将交易所API凭证写入本地配置文件( |
| | 为所有交易所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 vs
mainnet— default to testnet and ask before trading livetestnet
请勿在以下场景使用BlockFill Agent Execution:
- 用户未指定交易所、交易对、方向或数量——先询问用户,不要自行假设方向、规模或环境的默认值
- 用户询问买卖推荐或价格目标——BlockFill Agent Execution不提供投资建议;引导用户使用合适的研究工具
- 目标市场为不支持交易所的现货交易——请核对支持交易所列表
- 用户希望交易股票、外汇或非加密资产——超出服务范围
- 环境未配置完成(无API凭证、受地理限制主机未设置代理)——先完成设置,再进行交易
- 用户请求的仓位超出其声明的风险承受能力——执行前请与用户确认
- 用户未确认(主网)与
mainnet(测试网)——默认使用测试网,主网交易前需确认testnet
Before Placing an Order — Agent Checklist
下单前——Agent检查清单
Before calling , confirm you have all required information. If any is missing, ask the user — do not assume defaults for direction, size, or environment.
place_order| Item | Required | If missing |
|---|---|---|
| Exchange | ✅ | Ask: "Which exchange? (e.g. binance-futures, okx-swap)" |
| Symbol | ✅ | Ask: "Which symbol? Use native format (e.g. btcusdt for Binance)" |
| Side (long / short / close) | ✅ | Ask: "Buy or sell? What target position?" |
| Quantity / target position | ✅ | Ask: "How much? In base asset units." |
| Environment (testnet / mainnet) | ✅ | Default to testnet. Confirm before mainnet. |
| Strategy | ✗ | Default: |
| Time window | ✗ | Default: 300,000 ms (5 min). Inform user. |
| Proxy (if geo-blocked) | ✗ | Warn if Binance + non-whitelisted region. Offer |
调用前,请确认已获取所有必要信息。若有缺失,询问用户——不要自行假设方向、规模或环境的默认值。
place_order| 项目 | 是否必填 | 缺失时处理 |
|---|---|---|
| 交易所 | ✅ | 询问:"请问是哪个交易所?(例如binance-futures、okx-swap)" |
| 交易对 | ✅ | 询问:"请问是哪个交易对?请使用交易所原生格式(例如Binance的btcusdt)" |
| 方向(做多/做空/平仓) | ✅ | 询问:"买入还是卖出?目标仓位是多少?" |
| 数量 / 目标仓位 | ✅ | 询问:"数量是多少?以基础资产单位计算。" |
| 环境(测试网/主网) | ✅ | 默认使用测试网。主网交易前需确认。 |
| 策略 | ✗ | 默认: |
| 时间窗口 | ✗ | 默认:300,000毫秒(5分钟)。告知用户。 |
| 代理(若受地理限制) | ✗ | 若为Binance+非白名单地区,发出警告。提供 |
Binance TradFi symbols
Binance TradFi交易对
binance-futurestslausdtnvdausdtskhynixusdtxauusdtxagusdtclusdtopenaiusdtanthropicusdt-4411set_credentialscheck_credentials"tradfi_perps": "signed"check_credentials()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 ). Binance provides no API to revoke it.
btcusdtNote / are not TradFi — ordinary gold-backed tokens,
contract type , no agreement needed.
paxgusdtxautusdtPERPETUALbinance-futurestslausdtnvdausdtskhynixusdtxauusdtxagusdtclusdtopenaiusdtanthropicusdt-4411set_credentialscheck_credentials"tradfi_perps": "signed"check_credentials()请告知用户代为签署的协议内容:与Binance受ADGM监管实体的绑定协议,涵盖现金市场外的7×24小时交易,不持有底层资产所有权,资金费率最高±2.00%(对比的±0.30%)。Binance未提供撤销该协议的API。
btcusdt注意 / 不属于TradFi——它们是普通的黄金代币,合约类型为,无需签署协议。
paxgusdtxautusdtPERPETUALHyperliquid / Aster builder-fee approval
Hyperliquid / Aster builder-fee授权
Both DEX venues reject any order carrying an unapproved builder code —
Hyperliquid with — and the ticket then sits
at 0% filled until its window expires. The user must approve once, on-chain,
signed by their MAIN wallet:
Builder fee has not been approved| Venue | Builder address | Approve at |
|---|---|---|
| Hyperliquid (perp + spot) | | ≥ 0.015% (1.5 bp) |
| Aster (perp only) | | ≥ 0.015% (1.5 bp) |
BlockFill signs this for the user. These venues take the account owner's
wallet (not a delegated agent key) precisely so it can:
reads the current approval and signs /
when ours is missing or below rate, reporting
. Only if signing fails does the
check fail. Aster spot needs nothing; Aster Code is perp-only.
private_keycheck_credentials()approveBuilderFeeapproveBuilder"builder_fee": "approved just now at 0.015%"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
for the exhaustive signable-action
list.
docs/security/trade-only-permissions.md⚠️ 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
before placing.
check_credentials()这两个DEX平台会拒绝携带未授权builder代码的订单——Hyperliquid会返回,工单会保持0%成交直至时间窗口过期。用户必须通过链上操作,使用主钱包签署一次授权:
Builder fee has not been approved| 平台 | Builder地址 | 授权费率要求 |
|---|---|---|
| Hyperliquid(永续合约+现货) | | ≥0.015%(1.5基点) |
| Aster(仅永续合约) | | ≥0.015%(1.5基点) |
BlockFill会代为用户签署授权。这些平台要求用户提供账户钱包的(而非委托代理密钥),以便:会读取当前授权状态,若未授权或费率不足,则签署 / ,并返回。仅当签署失败时,检查才会失败。Aster现货无需授权;Aster代码仅适用于永续合约。
private_keycheck_credentials()approveBuilderFeeapproveBuilder"builder_fee": "approved just now at 0.015%"请告知用户该密钥的权限:可签署订单和此次费用授权,也可能提取资金——交易所不再阻止该操作,仅引擎中无提取代码。详情请查看中的可签署操作列表。
docs/security/trade-only-permissions.md⚠️ 测试网不绑定builder代码,因此不会出现此问题。测试网运行完全正常,但首次主网订单仍可能失败。当用户从测试网切换至这些平台的主网时,下单前请重新运行。
check_credentials()Install
安装
bash
pip install blockfill # latest
pip install -U blockfill # upgradeThe wheel ships with the executor binary bundled inside (no separate download). PyPI publishes only platform-specific wheels. Currently supported: (Linux x86_64).
manylinux2014_x86_64The 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仅发布平台特定安装包。当前支持:(Linux x86_64)。
manylinux2014_x86_64blockfill-server端点和API密钥在发布时已硬编码到二进制文件中——用户无需设置。
Supported Exchanges
支持的交易所
Every venue runs perp/futures + spot from one daemon. Exchange id is (e.g. , , , ).
<venue>-<product>binance-futuresokx-swapbybit-perp<venue>-spot| Exchange | Exchange id (perp/futures · spot) | Credentials | Class |
|---|---|---|---|
| Binance | | | CEX |
| OKX | | | CEX |
| Bybit | | | CEX |
| Bitget | | | CEX |
| Gate.io | | | CEX |
| KuCoin | | | CEX |
| Kraken | | | CEX |
| Deribit | | | CEX |
| Hyperliquid | | | DEX |
| Aster | | | DEX |
| Orderly | | | 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 = the Ed25519 API Key id, = the PEM private key. The daemon auto-detects and signs with Ed25519.
api_keyapi_secretpython
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-futuresokx-swapbybit-perp<venue>-spot| 交易所 | 交易所ID(永续合约/期货 · 现货) | 凭证要求 | 类型 |
|---|---|---|---|
| Binance | | | CEX |
| OKX | | | CEX |
| Bybit | | | CEX |
| Bitget | | | CEX |
| Gate.io | | | CEX |
| KuCoin | | | CEX |
| Kraken | | | CEX |
| Deribit | | | CEX |
| Hyperliquid | | | DEX |
| Aster | | | DEX |
| Orderly | | | 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密钥)。传入 = Ed25519 API密钥ID, = PEM私钥。守护进程会自动检测并使用Ed25519签名。
api_keyapi_secretpython
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.
| Exchange | Format | Examples |
|---|---|---|
| Lowercase, concatenated | |
| Dash-separated + SWAP suffix | |
| UPPERCASE, concatenated | |
| UPPERCASE, concatenated | |
| Underscore-separated | |
| Contract code | |
| PF_ prefix + base/quote | |
| Dash-separated + PERPETUAL suffix | |
| Coin only | |
| UPPERCASE, concatenated | |
| Exchange-specific via broker | Use |
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每个交易所使用其原生交易对格式。
| 交易所 | 格式 | 示例 |
|---|---|---|
| 小写拼接 | |
| 短横线分隔+SWAP后缀 | |
| 大写拼接 | |
| 大写拼接 | |
| 下划线分隔 | |
| 合约代码 | |
| PF_前缀+基础/计价资产 | |
| 短横线分隔+PERPETUAL后缀 | |
| 仅币种名称 | |
| 大写拼接 | |
| 经纪商指定格式 | 使用 |
请使用目标交易所要求的精确格式——BlockFill Agent Execution不提供跨格式转换。查询任意平台的精确交易对字符串:
bash
blockfill check instrument --symbol btcExecution Strategies
执行策略
| Strategy | Behavior | When to use |
|---|---|---|
| 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. |
| 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| 策略 | 行为 | 适用场景 |
|---|---|---|
| 提交PostOnly限价单;赚取挂单方返佣。时间窗口结束时,未成交部分自动切换为IOC订单。 | 默认策略。当成交速度非关键时,成本最优。 |
| 在整个时间窗口内按TWAP计划提交IOC订单——始终跨越买卖价差。 | 需要保证完成订单且接受吃单方成本时使用。 |
默认策略:。
makerTicket Parameters
工单参数
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| string | ✅ | — | Supported exchange id, e.g. |
| string | ✅ | — | Exchange-native format, e.g. |
| float | ✅ | — | Target position in base asset. Positive = long, negative = short (perp). For spot: absolute base-asset holding to end up with. |
| string | | | |
| int | | 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 automatically cancels existing and tickets for that pair.
exchange+symbolNEWOPENSpot vs perp : perp = net directional position (positive = long, negative = short). Spot = absolute base-asset holding to end up with ( on a 1.0 BTC balance sells 0.999; to add, set ).
target_positiontarget=0.001target = current_holding + delta| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| string | ✅ | — | 支持的交易所ID,例如 |
| string | ✅ | — | 交易所原生格式的交易对,例如 |
| float | ✅ | — | 基础资产的目标仓位。正数=做多,负数=做空(永续合约)。现货交易:最终持有的基础资产绝对数量。 |
| string | | | |
| int | | 执行窗口(毫秒)。范围:60,000–86,400,000(1分钟至24小时)。窗口结束时,未成交部分自动切换为吃单方成交。 |
自动替换:为同一提交新工单时,会自动取消该交易对下所有状态为和的现有工单。
exchange+symbolNEWOPEN现货与永续合约的区别:永续合约=净方向仓位(正数=做多,负数=做空)。现货=最终持有的基础资产绝对数量(当前持有1.0 BTC,设置会卖出0.999 BTC;若要加仓,设置)。
target_positiontarget=0.001target = 当前持有量 + 增量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
}| Field | Type | Description |
|---|---|---|
| string | |
| string | |
| string | Exchange id used |
| string | Native symbol format |
| string | |
| float | Requested net position |
| float | null | Position at activation (null while NEW) |
| float | Net delta filled so far |
| int | Execution window in ms |
| int | null | Set when executor activates (NEW → OPEN) |
| int | null | Refreshed on every state change |
| bool | True when window elapsed; status stays OPEN until cancelled |
| string | null | |
Note: The ticket has nooravg_pricefield. For execution cost, opportunity cost, and benchmark comparisons, callcost(compare_tca) — it returnsbf.tca(...),execution_cost_usd, and benchmarks (l1/mid/twap/vwap) per ticket.opportunity_cost_usd
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
}| 字段 | 类型 | 描述 |
|---|---|---|
| string | |
| string | |
| string | 使用的交易所ID |
| string | 原生格式交易对 |
| string | |
| float | 请求的净仓位 |
| float | null | 工单激活时的仓位(状态为NEW时为null) |
| float | 已成交的净仓位变化量 |
| int | 执行窗口(毫秒) |
| int | null | 执行器激活时设置(状态从NEW变为OPEN) |
| int | null | 每次状态变更时刷新 |
| bool | 窗口过期时为true;状态保持OPEN直至被取消 |
| string | null | |
注意:工单无或avg_price字段。如需执行成本、机会成本及基准对比,请调用cost(compare_tca)——它会返回每个工单的bf.tca(...)、execution_cost_usd及基准值(l1/mid/twap/vwap)。opportunity_cost_usd
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() -> Nonepython
bf.check_credentials() -> NoneHits 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 skill, 18 countries, 500 GB/month:
sc-vpnpython
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-Pacific | Europe | Americas |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|
Any HTTP CONNECT proxy also works:
python
bf.set_proxy("http://user:pass@proxy.example.com:8080")set_proxyVerify 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用户——免费技能,覆盖18个国家,每月500 GB流量:
sc-vpnpython
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() # 清除代理| 亚太地区 | 欧洲 | 美洲 |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|
任何HTTP CONNECT代理均可使用:
python
bf.set_proxy("http://user:pass@proxy.example.com:8080")set_proxy实盘交易前请验证连通性:
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.
| Symptom | Likely cause | Fix |
|---|---|---|
| API key bound to a different IP than your current outbound IP | Add your outbound IP (or proxy IP) to the exchange API key whitelist |
| Geo-block (e.g. US IP → Binance) | Set a proxy: |
| Wrong | Re-check credentials; Binance testnet uses Ed25519, not HMAC |
Ticket stays | Exchange not in | Check |
Ticket | Order size × price < exchange minimum notional | Increase quantity or use a larger notional |
Ticket | Not enough margin for the position | Reduce quantity or add margin |
Ticket | Exchange rejected the order (symbol suspended, invalid params) | Check symbol with |
| Daemon failed to init one or more exchanges | Run |
| NAV = 0 for Binance spot (testnet) | Testnet does not support | Expected — testnet NAV uses market-ticker routing instead |
For persistent issues, see GitLab Issues or Telegram support. See for the full knowledge base.
docs/troubleshooting.md出现故障时,请按以下顺序诊断:凭证 → 代理 → 环境 → 交易对 → 保证金。
| 症状 | 可能原因 | 解决方法 |
|---|---|---|
| API密钥绑定的IP与当前出口IP不一致 | 将出口IP(或代理IP)添加至交易所API密钥白名单 |
| 地理限制(例如美国IP访问Binance) | 设置代理: |
| | 重新核对凭证;Binance测试网使用Ed25519,而非HMAC |
工单保持 | 交易所不在 | 查看 |
工单 | 订单规模×价格 < 交易所最低名义价值 | 增加数量或使用更大名义价值的订单 |
工单 | 保证金不足以支撑仓位 | 减少数量或追加保证金 |
工单 | 交易所拒绝订单(交易对暂停、参数无效) | 使用 |
| 守护进程初始化一个或多个交易所失败 | 运行 |
| Binance现货(测试网)的NAV=0 | 测试网不支持 | 正常现象——测试网NAV使用市场行情路由计算 |
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 . The daemon holds the wallet key and signs locally; only the signature leaves the machine, never the key.
transferWithAuthorizationpython
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 。守护进程存储钱包密钥并在本地签名;仅签名会离开设备,密钥绝不会外传。
transferWithAuthorizationpython
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
(可选)若处于地理限制区域,先配置代理
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
bf.set_proxy("http://jp:x@sc-vpn.internal:8080")
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
支持
- GitLab Issues: https://gitlab.com/quantech-services-group/blockfill-agent-execution/-/issues
- Telegram: @blockfill_support
- GitLab Issues: https://gitlab.com/quantech-services-group/blockfill-agent-execution/-/issues
- Telegram: @blockfill_support