提交代码
This commit is contained in:
10
polymarket/test.py
Normal file
10
polymarket/test.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from py_clob_client.clob_types import AssetType
|
||||
import inspect
|
||||
|
||||
print("AssetType:", AssetType)
|
||||
print("dir:", [x for x in dir(AssetType) if x.isupper()])
|
||||
print("members:", getattr(AssetType, "__members__", None))
|
||||
if hasattr(AssetType, "__members__"):
|
||||
print("values:", {k: v.value for k, v in AssetType.__members__.items()})
|
||||
|
||||
print("source:", inspect.getsource(AssetType))
|
||||
@@ -172,34 +172,48 @@ class PolymarketTrader:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
def get_orders(self):
|
||||
def get_orders(self, status="ALL"):
|
||||
"""
|
||||
获取订单历史
|
||||
status 可选: "ALL", "OPEN", "FILLED", "CANCELLED"
|
||||
"""
|
||||
if not self.client:
|
||||
self.init_client()
|
||||
|
||||
print(f"\n📜 获取历史订单...")
|
||||
print(f"\n📜 正在获取地址 {self.address} 的订单历史...")
|
||||
|
||||
try:
|
||||
# 获取用户的所有订单
|
||||
orders = self.client.get_orders()
|
||||
print(orders)
|
||||
# 使用 get_orders 时可以传入各种参数进行过滤
|
||||
# 注意:py-clob-client 的 API 返回格式可能随版本变化
|
||||
resp = self.client.get_orders()
|
||||
|
||||
# 如果 resp 是字典且包含订单列表
|
||||
orders = []
|
||||
if isinstance(resp, list):
|
||||
orders = resp
|
||||
elif isinstance(resp, dict):
|
||||
orders = resp.get('data', [])
|
||||
|
||||
if not orders:
|
||||
print("❌ 未找到任何历史订单")
|
||||
print("📭 未找到匹配的订单记录")
|
||||
return
|
||||
|
||||
print(f"📊 共 {len(orders)} 个订单")
|
||||
print(f"📊 找到 {len(orders)} 条记录:")
|
||||
print(f"{'时间':<20} | {'方向':<5} | {'价格':<6} | {'数量':<8} | {'状态':<10}")
|
||||
print("-" * 60)
|
||||
|
||||
for order in orders:
|
||||
print(f"📝 订单ID: {order['orderID']}")
|
||||
print(f" 状态: {order['status']}")
|
||||
print(f" 方向: {order['side']}")
|
||||
print(f" 价格: {order['price']}")
|
||||
print(f" 数量: {order['size']}")
|
||||
print(f" 创建时间: {order['createdAt']}")
|
||||
print("--------")
|
||||
# 提取关键信息,处理可能的 Key 差异
|
||||
side = order.get('side', 'N/A')
|
||||
price = order.get('price', '0')
|
||||
size = order.get('size', '0')
|
||||
status = order.get('status', 'UNKNOWN')
|
||||
created = order.get('createdAt', '')[:19].replace('T', ' ')
|
||||
|
||||
print(f"{created:<20} | {side:<5} | {price:<6} | {size:<8} | {status:<10}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 获取订单时出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"❌ 获取订单失败: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -207,14 +221,14 @@ if __name__ == "__main__":
|
||||
MNEMONIC = "material vapor okay save company news village license head slogan sadness wire"
|
||||
|
||||
# 目标 URL
|
||||
TARGET_URL = "https://polymarket.com/event/eth-updown-15m-1767457800?tid=1767458315299"
|
||||
TARGET_URL = "https://polymarket.com/event/eth-updown-15m-1767464100?tid=1767464758584"
|
||||
|
||||
# # 金额 (输入 1 即可)
|
||||
# AMOUNT = 1
|
||||
# 金额 (输入 1 即可)
|
||||
AMOUNT = 1
|
||||
|
||||
# # 方向+
|
||||
# DIRECTION = "Down"
|
||||
# 方向+
|
||||
DIRECTION = "Down"
|
||||
|
||||
trader = PolymarketTrader(MNEMONIC)
|
||||
print(trader.get_orders())
|
||||
# trader.buy(TARGET_URL, AMOUNT, DIRECTION)
|
||||
# print(trader.get_orders())
|
||||
trader.buy(TARGET_URL, AMOUNT, DIRECTION)
|
||||
|
||||
@@ -1,131 +1,33 @@
|
||||
import sys
|
||||
import json
|
||||
import requests
|
||||
from urllib.parse import urlparse
|
||||
from eth_account import Account
|
||||
from py_clob_client import OrderArgs, OrderType, BalanceAllowanceParams, AssetType
|
||||
from py_clob_client.client import ClobClient
|
||||
from py_clob_client.clob_types import MarketOrderArgs
|
||||
|
||||
# 启用助记词功能
|
||||
Account.enable_unaudited_hdwallet_features()
|
||||
|
||||
# --- 配置区域 ---
|
||||
GAMMA_API = "https://gamma-api.polymarket.com"
|
||||
HOST = "https://clob.polymarket.com"
|
||||
CHAIN_ID = 137
|
||||
|
||||
|
||||
def parse_jsonish_list(v):
|
||||
if v is None: return []
|
||||
if isinstance(v, list): return v
|
||||
if isinstance(v, str):
|
||||
s = v.strip()
|
||||
if s.startswith("[") and s.endswith("]"):
|
||||
try:
|
||||
return json.loads(s)
|
||||
except:
|
||||
pass
|
||||
return [x.strip() for x in s.split(",") if x.strip()]
|
||||
return []
|
||||
# 使用代理钱包
|
||||
client = ClobClient(
|
||||
host="https://clob.polymarket.com",
|
||||
key="0x78517b3a088e693e558177c19466c7fdad0458752618c306afcca8e440964a8a", # 你的主钱包私钥
|
||||
chain_id=137,
|
||||
signature_type=1, # Magic/Email 登录使用 1
|
||||
funder="0xc859c04b0978Af007AcFD7178121E1666C8eB646" # 你的代理钱包地址
|
||||
)
|
||||
|
||||
# 设置 API 凭据
|
||||
client.set_api_creds(client.create_or_derive_api_creds())
|
||||
|
||||
params = BalanceAllowanceParams(
|
||||
asset_type=AssetType.COLLATERAL,
|
||||
signature_type=1,
|
||||
)
|
||||
print(client.get_balance_allowance(params))
|
||||
|
||||
|
||||
class PolymarketTrader:
|
||||
def __init__(self, mnemonic):
|
||||
try:
|
||||
self.acct = Account.from_mnemonic(mnemonic)
|
||||
self.private_key = self.acct.key.hex()
|
||||
self.address = self.acct.address
|
||||
print(f"✅ 钱包已加载: {self.address}")
|
||||
except Exception as e:
|
||||
print(f"❌ 助记词错误: {e}")
|
||||
sys.exit(1)
|
||||
self.client = None
|
||||
# # 获取所有活跃市场
|
||||
# markets = client.get_markets()
|
||||
|
||||
def init_client(self):
|
||||
try:
|
||||
self.client = ClobClient(host=HOST, key=self.private_key, chain_id=CHAIN_ID)
|
||||
self.client.set_api_creds(self.client.create_or_derive_api_creds())
|
||||
print("✅ Polymarket API 登录成功")
|
||||
except Exception as e:
|
||||
print(f"❌ 登录失败: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
def resolve_market(self, url, direction):
|
||||
parsed_url = urlparse(url)
|
||||
try:
|
||||
slug = parsed_url.path.split("event/")[-1].split("?")[0].strip("/")
|
||||
except:
|
||||
raise ValueError("无效 URL")
|
||||
|
||||
print(f"🔍 解析 Slug: {slug}")
|
||||
resp = requests.get(f"{GAMMA_API}/events", params={"slug": slug})
|
||||
data = resp.json()
|
||||
if not data: raise ValueError("未找到市场")
|
||||
|
||||
target_market = data[0].get('markets', [])[0]
|
||||
for m in data[0].get('markets', []):
|
||||
if m.get('active'):
|
||||
target_market = m
|
||||
break
|
||||
|
||||
outcomes = [str(x) for x in parse_jsonish_list(target_market.get("outcomes"))]
|
||||
token_ids = [str(x) for x in parse_jsonish_list(target_market.get("clobTokenIds"))]
|
||||
token_map = dict(zip(outcomes, token_ids))
|
||||
|
||||
target_token_id = token_map.get(direction)
|
||||
if not target_token_id:
|
||||
alt = {"Up": "Yes", "Down": "No", "Yes": "Up", "No": "Down"}
|
||||
target_token_id = token_map.get(alt.get(direction))
|
||||
|
||||
return {"token_id": target_token_id, "question": target_market.get('question')}
|
||||
|
||||
def buy(self, url, amount_usd, direction):
|
||||
if not self.client: self.init_client()
|
||||
|
||||
try:
|
||||
market_data = self.resolve_market(url, direction)
|
||||
token_id = market_data['token_id']
|
||||
|
||||
# 获取当前卖一价,作为参考,设置一个合理的滑点保护价
|
||||
orderbook = self.client.get_order_book(token_id)
|
||||
if not orderbook.asks:
|
||||
print("❌ 市场无卖单")
|
||||
return
|
||||
best_ask = float(orderbook.asks[0].price)
|
||||
|
||||
# 对于市价单,price 参数通常充当 Limit Price (最高愿意支付的价格)
|
||||
# 设置为比卖一高 5%,但不超过 0.99
|
||||
limit_price = min(round(best_ask * 1.05, 2), 0.99)
|
||||
|
||||
print(f"🎯 目标: {market_data['question']}")
|
||||
print(f"💰 投入金额: ${amount_usd} | 最高接受价格: {limit_price}")
|
||||
|
||||
# --- 根据你提供的类定义进行匹配 ---
|
||||
order_args = MarketOrderArgs(
|
||||
token_id=token_id,
|
||||
amount=float(amount_usd), # BUY 订单这里填美元金额
|
||||
side="BUY",
|
||||
price=limit_price # 设置滑点保护价
|
||||
)
|
||||
|
||||
print("📡 发送市价买入订单...")
|
||||
resp = self.client.create_and_post_order(order_args)
|
||||
|
||||
if resp and resp.get("success"):
|
||||
print("✅ 购买成功!")
|
||||
print(f"🆔 Order ID: {resp.get('orderID')}")
|
||||
else:
|
||||
print(f"⚠️ 下单响应: {resp}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 执行失败: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
MNEMONIC = "material vapor okay save company news village license head slogan sadness wire"
|
||||
TARGET_URL = "https://polymarket.com/event/eth-updown-15m-1767457800?tid=1767458315299"
|
||||
AMOUNT_USD = 1.05 # 建议略高于1,防止因手续费导致不满1元报错
|
||||
DIRECTION = "Up"
|
||||
|
||||
trader = PolymarketTrader(MNEMONIC)
|
||||
trader.buy(TARGET_URL, AMOUNT_USD, DIRECTION)
|
||||
# # 搜索特定主题
|
||||
# for market in markets["data"]:
|
||||
# print(market)
|
||||
# if "Trump" in market['question']:
|
||||
# print(f"市场:{market['question']}")
|
||||
# print(f"Token ID (Yes): {market['tokens'][0]['token_id']}")
|
||||
# print(f"Token ID (No): {market['tokens'][1]['token_id']}")
|
||||
|
||||
Reference in New Issue
Block a user