React前端结合tRPC后端,如何通过WebSocket发送消息对接币安下单?
可行,方案如下
你的设想完全可以实现——tRPC的wsLink支持双向通信,不仅能接收后端推送的订阅数据,也能发送RPC请求(比如下单指令)给后端,再由后端转发给币安完成下单操作。
具体实现步骤:
1. 后端定义下单处理的RPC方法
在你的AppRouter中新增一个mutation类型的procedure,用于接收前端的订单参数,调用币安API完成下单:
// 后端 @api/app.ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; // 假设你已初始化币安客户端 import { binanceClient } from './your-binance-client'; const t = initTRPC.create(); export const appRouter = t.router({ binance: t.router({ // 你现有的市场数据订阅 marketDataStream: t.procedure .input(z.object({ symbol: z.string() })) .subscription(async ({ input }) => { // 原有订阅逻辑 }), // 新增下单方法 createOrder: t.procedure .input(z.object({ symbol: z.string(), side: z.enum(['BUY', 'SELL']), type: z.enum(['LIMIT', 'MARKET']), quantity: z.number(), price: z.number().optional() // 市价单不需要价格 })) .mutation(async ({ input }) => { try { // 调用币安API下单 const orderResponse = await binanceClient.createOrder(input); return { success: true, orderId: orderResponse.orderId, status: orderResponse.status }; } catch (err) { throw new Error(`下单失败: ${err.message}`); } }) }) }); export type AppRouter = typeof appRouter;
2. 前端通过tRPC客户端调用下单方法
你可以直接在React组件中调用这个mutation方法,不需要依赖现有订阅的回调:
// React组件内 const handlePlaceOrder = async () => { const orderParams = { symbol: 'BTCUSDT', side: 'BUY', type: 'MARKET', quantity: 0.001 }; try { const result = await client.binance.createOrder.mutate(orderParams); console.log('下单成功:', result); // 这里可以添加下单成功后的UI逻辑,比如更新订单状态 } catch (error) { console.error('下单失败:', error.message); } }; // 在按钮或交互中触发 <button onClick={handlePlaceOrder}>市价买入BTC</button>
3. 可选:让下单请求走WebSocket链接
你当前的splitLink配置是订阅走ws,其他请求走http,如果想让下单请求也通过WebSocket传输,只需调整condition规则:
// 前端客户端配置修改 splitLink({ // 让订阅和mutation都走wsLink condition: (op) => op.type === 'subscription' || op.type === 'mutation', true: wsLink({ client: createWSClient({ url: `ws://localhost:7000`, }), transformer: superjson, }), false: httpLink({ url: `http://localhost:7000`, fetch(url, options) { return fetch(url, { ...options, credentials: 'include', cache: 'no-store', }); }, transformer: superjson, }), }),
关键说明
- tRPC的WebSocket链接是全双工的,支持双向数据传输,所以发送下单指令和接收市场数据可以共用同一个ws连接。
- 后端处理下单时,注意做好参数校验、错误捕获和日志记录,避免因币安API异常导致的问题扩散到前端。
内容的提问来源于stack exchange,提问作者seven
相关产品推荐
相关产品推荐

