還沒有帳號?點擊這裡註冊 Polymarket 並完成入金,才能用錢包私鑰為訂單籤名、實際成交。
法律合規提醒:在使用 Polymarket 服務或 API 前,請確認您所在地區的法律規定。Polymarket 目前不支援比利時、法國、新加坡、泰國、中國大陸等地區,政策可能隨時變化。
安裝
Python
Copy
pip install py-clob-client
TypeScript/JavaScript
Copy
npm install @polymarket/clob-client ethers
基本設置
Python 設置
Copy
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL
# CLOB API 主機
host = "https://clob.polymarket.com"
# 您的私鑰
private_key = "YOUR_PRIVATE_KEY"
# Polygon 主網
chain_id = 137
# 您的代理錢包地址
proxy_address = "YOUR_PROXY_ADDRESS"
# 創建客戶端
# signature_type=1: Magic/Email 登錄
# signature_type=2: 瀏覽器錢包(MetaMask 等)
# 不指定 funder: EOA(外部擁有帳戶)
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
signature_type=1, # 根據您的登錄方式調整
funder=proxy_address
)
# 設置 API 憑據
client.set_api_creds(client.create_or_derive_api_creds())
TypeScript 設置
Copy
import { ClobClient } from '@polymarket/clob-client';
import { ethers } from 'ethers';
// CLOB API 主機
const host = 'https://clob.polymarket.com';
// 您的私鑰
const privateKey = 'YOUR_PRIVATE_KEY';
// Polygon 主網
const chainId = 137;
// 您的代理錢包地址
const proxyAddress = 'YOUR_PROXY_ADDRESS';
// 創建錢包
const wallet = new ethers.Wallet(privateKey);
// 創建客戶端
// signatureType=1: Magic/Email 登錄
// signatureType=2: 瀏覽器錢包(MetaMask 等)
// 不指定 funder: EOA(外部擁有帳戶)
const client = new ClobClient(
host,
chainId,
wallet,
1, // 根據您的登錄方式調整
proxyAddress
);
// 設置 API 憑據
await client.setApiCreds(client.createOrDeriveApiCreds());
獲取市場數據
列出所有市場
Copy
# Python
markets = client.get_markets()
for market in markets[:5]: # 顯示前5個市場
print(f"問題: {market['question']}")
print(f"Token ID (Yes): {market['tokens'][0]['token_id']}")
print(f"Token ID (No): {market['tokens'][1]['token_id']}")
print("---")
Copy
// TypeScript
const markets = await client.getMarkets();
markets.slice(0, 5).forEach(market => {
console.log(`問題: ${market.question}`);
console.log(`Token ID (Yes): ${market.tokens[0].token_id}`);
console.log(`Token ID (No): ${market.tokens[1].token_id}`);
console.log('---');
});
獲取訂單簿
Copy
# Python
token_id = "YOUR_TOKEN_ID"
book = client.get_order_book(token_id)
print("買單 (Bids):")
for bid in book['bids'][:5]:
print(f"價格: {bid['price']}, 數量: {bid['size']}")
print("\n賣單 (Asks):")
for ask in book['asks'][:5]:
print(f"價格: {ask['price']}, 數量: {ask['size']}")
Copy
// TypeScript
const tokenId = 'YOUR_TOKEN_ID';
const book = await client.getOrderBook(tokenId);
console.log('買單 (Bids):');
book.bids.slice(0, 5).forEach(bid => {
console.log(`價格: ${bid.price}, 數量: ${bid.size}`);
});
console.log('\n賣單 (Asks):');
book.asks.slice(0, 5).forEach(ask => {
console.log(`價格: ${ask.price}, 數量: ${ask.size}`);
});
獲取當前價格
Copy
# Python
token_id = "YOUR_TOKEN_ID"
# 中間價
midpoint = client.get_midpoint(token_id)
print(f"中間價: {midpoint}")
# 最佳買賣價
book = client.get_order_book(token_id)
best_bid = book['bids'][0]['price'] if book['bids'] else None
best_ask = book['asks'][0]['price'] if book['asks'] else None
spread = float(best_ask) - float(best_bid) if best_ask and best_bid else None
print(f"最佳買價: {best_bid}")
print(f"最佳賣價: {best_ask}")
print(f"價差: {spread}")
Copy
// TypeScript
const tokenId = 'YOUR_TOKEN_ID';
// 中間價
const midpoint = await client.getMidpoint(tokenId);
console.log(`中間價: ${midpoint}`);
// 最佳買賣價
const book = await client.getOrderBook(tokenId);
const bestBid = book.bids.length > 0 ? book.bids[0].price : null;
const bestAsk = book.asks.length > 0 ? book.asks[0].price : null;
const spread = bestAsk && bestBid ? parseFloat(bestAsk) - parseFloat(bestBid) : null;
console.log(`最佳買價: ${bestBid}`);
console.log(`最佳賣價: ${bestAsk}`);
console.log(`價差: ${spread}`);
創建和提交訂單
買入訂單
Copy
# Python
from py_clob_client.order_builder.constants import BUY
# 創建買入訂單
order_args = OrderArgs(
price=0.55, # 願意支付的價格
size=100.0, # 購買數量
side=BUY, # 買入
token_id="YOUR_TOKEN_ID" # 代幣 ID
)
# 籤署訂單
signed_order = client.create_order(order_args)
# 提交 GTC 訂單
response = client.post_order(signed_order, OrderType.GTC)
print(f"訂單已創建,ID: {response['orderID']}")
Copy
// TypeScript
import { Side, OrderType } from '@polymarket/clob-client';
// 創建買入訂單
const orderArgs = {
tokenID: 'YOUR_TOKEN_ID', // 代幣 ID
price: 0.55, // 願意支付的價格
size: 100, // 購買數量
side: Side.BUY, // 買入
};
// 籤署訂單
const signedOrder = await client.createOrder(orderArgs);
// 提交 GTC 訂單
const response = await client.postOrder(signedOrder, OrderType.GTC);
console.log(`訂單已創建,ID: ${response.orderID}`);
賣出訂單
Copy
# Python
from py_clob_client.order_builder.constants import SELL
# 創建賣出訂單
order_args = OrderArgs(
price=0.60, # 願意接受的價格
size=50.0, # 出售數量
side=SELL, # 賣出
token_id="YOUR_TOKEN_ID" # 代幣 ID
)
# 籤署並提交
signed_order = client.create_order(order_args)
response = client.post_order(signed_order, OrderType.GTC)
print(f"訂單已創建,ID: {response['orderID']}")
Copy
// TypeScript
// 創建賣出訂單
const orderArgs = {
tokenID: 'YOUR_TOKEN_ID',
price: 0.60,
size: 50,
side: Side.SELL,
};
// 籤署並提交
const signedOrder = await client.createOrder(orderArgs);
const response = await client.postOrder(signedOrder, OrderType.GTC);
console.log(`訂單已創建,ID: ${response.orderID}`);
管理訂單
查詢訂單
Copy
# Python
# 獲取所有活躍訂單
orders = client.get_orders()
for order in orders:
print(f"訂單 ID: {order['id']}")
print(f"價格: {order['price']}, 數量: {order['size']}")
print(f"狀態: {order['status']}")
print("---")
# 獲取特定訂單
order_id = "YOUR_ORDER_ID"
order = client.get_order(order_id)
print(f"訂單詳情: {order}")
Copy
// TypeScript
// 獲取所有活躍訂單
const orders = await client.getOrders();
orders.forEach(order => {
console.log(`訂單 ID: ${order.id}`);
console.log(`價格: ${order.price}, 數量: ${order.size}`);
console.log(`狀態: ${order.status}`);
console.log('---');
});
// 獲取特定訂單
const orderId = 'YOUR_ORDER_ID';
const order = await client.getOrder(orderId);
console.log(`訂單詳情:`, order);
取消訂單
Copy
# Python
# 取消單個訂單
order_id = "YOUR_ORDER_ID"
response = client.cancel_order(order_id)
print(f"訂單已取消: {response}")
# 取消多個訂單
order_ids = ["ORDER_ID_1", "ORDER_ID_2"]
response = client.cancel_orders(order_ids)
print(f"已取消 {len(response)} 個訂單")
# 取消特定市場的所有訂單
token_id = "YOUR_TOKEN_ID"
response = client.cancel_market_orders(token_id)
print(f"已取消市場的所有訂單")
# 取消所有訂單
response = client.cancel_all()
print("已取消所有訂單")
Copy
// TypeScript
// 取消單個訂單
const orderId = 'YOUR_ORDER_ID';
const response = await client.cancelOrder(orderId);
console.log('訂單已取消:', response);
// 取消多個訂單
const orderIds = ['ORDER_ID_1', 'ORDER_ID_2'];
const cancelResponse = await client.cancelOrders(orderIds);
console.log(`已取消 ${cancelResponse.length} 個訂單`);
// 取消特定市場的所有訂單
const tokenId = 'YOUR_TOKEN_ID';
await client.cancelMarketOrders(tokenId);
console.log('已取消市場的所有訂單');
// 取消所有訂單
await client.cancelAll();
console.log('已取消所有訂單');
查詢帳戶信息
檢查餘額
Copy
# Python
# 獲取帳戶餘額
balance = client.get_balance()
print(f"可用餘額: {balance['available']} USDC")
print(f"總餘額: {balance['total']} USDC")
# 獲取持倉
positions = client.get_positions()
for position in positions:
print(f"市場: {position['market']}")
print(f"數量: {position['size']}")
print(f"價值: {position['value']} USDC")
print("---")
Copy
// TypeScript
// 獲取帳戶餘額
const balance = await client.getBalance();
console.log(`可用餘額: ${balance.available} USDC`);
console.log(`總餘額: ${balance.total} USDC`);
// 獲取持倉
const positions = await client.getPositions();
positions.forEach(position => {
console.log(`市場: ${position.market}`);
console.log(`數量: ${position.size}`);
console.log(`價值: ${position.value} USDC`);
console.log('---');
});
查詢交易歷史
Copy
# Python
# 獲取交易歷史
trades = client.get_trades()
for trade in trades[:10]: # 顯示最近10筆交易
print(f"時間: {trade['timestamp']}")
print(f"價格: {trade['price']}, 數量: {trade['size']}")
print(f"方向: {trade['side']}")
print("---")
Copy
// TypeScript
// 獲取交易歷史
const trades = await client.getTrades();
trades.slice(0, 10).forEach(trade => {
console.log(`時間: ${trade.timestamp}`);
console.log(`價格: ${trade.price}, 數量: ${trade.size}`);
console.log(`方向: ${trade.side}`);
console.log('---');
});
完整示例:自動交易策略
Copy
# Python: 簡單的做市策略
import time
from py_clob_client.order_builder.constants import BUY, SELL
def market_making_strategy(client, token_id, spread=0.02):
"""
簡單的做市策略:在中間價上下掛買賣單
"""
while True:
try:
# 獲取當前中間價
midpoint = float(client.get_midpoint(token_id))
# 取消所有現有訂單
client.cancel_market_orders(token_id)
# 計算買賣價格
buy_price = round(midpoint - spread / 2, 2)
sell_price = round(midpoint + spread / 2, 2)
# 下買單
buy_order = OrderArgs(
price=buy_price,
size=10.0,
side=BUY,
token_id=token_id
)
signed_buy = client.create_order(buy_order)
client.post_order(signed_buy, OrderType.GTC)
print(f"買單已下: {buy_price}")
# 下賣單
sell_order = OrderArgs(
price=sell_price,
size=10.0,
side=SELL,
token_id=token_id
)
signed_sell = client.create_order(sell_order)
client.post_order(signed_sell, OrderType.GTC)
print(f"賣單已下: {sell_price}")
# 等待30秒後重新調整
time.sleep(30)
except Exception as e:
print(f"錯誤: {e}")
time.sleep(10)
# 使用策略
# market_making_strategy(client, "YOUR_TOKEN_ID")
錯誤處理
Copy
# Python
from py_clob_client.exceptions import PolyApiException
try:
order_args = OrderArgs(
price=0.55,
size=100.0,
side=BUY,
token_id="YOUR_TOKEN_ID"
)
signed_order = client.create_order(order_args)
response = client.post_order(signed_order, OrderType.GTC)
except PolyApiException as e:
print(f"API 錯誤: {e}")
# 處理特定錯誤
if "insufficient balance" in str(e).lower():
print("餘額不足")
elif "invalid signature" in str(e).lower():
print("籤名錯誤,檢查私鑰和代理地址")
except Exception as e:
print(f"未知錯誤: {e}")
Copy
// TypeScript
try {
const orderArgs = {
tokenID: 'YOUR_TOKEN_ID',
price: 0.55,
size: 100,
side: Side.BUY,
};
const signedOrder = await client.createOrder(orderArgs);
const response = await client.postOrder(signedOrder, OrderType.GTC);
} catch (error: any) {
console.error('錯誤:', error.message);
// 處理特定錯誤
if (error.message.includes('insufficient balance')) {
console.log('餘額不足');
} else if (error.message.includes('invalid signature')) {
console.log('籤名錯誤,檢查私鑰和代理地址');
}
}