引言
在量化交易領域,TradingView因其強大的技術分析工具和豐富的指標庫而廣受歡迎,但是其不支持國內期貨自動化交易,CTPBee則是一個優秀的國產Python期貨交易接口。本文將介紹如何將兩者結合,實現一個完整的自動化交易系統。
本文代碼庫已開源發布到GitHub上,訪問鏈接:https://github.com/sencloud/tradingview_ctp
系統架構
整個系統分為三個主要部分:
- TradingView策略和告警
- Flask后端API服務
- CTPBee交易執行器
1. TradingView策略設計
TradingView提供了強大的策略編寫功能,我們可以使用Pine Script編寫交易策略。以下是一個簡單的示例:
//@version=5
strategy("My Trading Strategy", overlay=true)// 定義策略參數
fastLength = input(9, "Fast Length")
slowLength = input(21, "Slow Length")// 計算指標
fastMA = ta.sma(close, fastLength)
slowMA = ta.sma(close, slowLength)// 定義交易信號
longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)// 設置告警條件
alertcondition(longCondition, "開多倉", "{{ticker}} 開多倉信號")
alertcondition(shortCondition, "開空倉", "{{ticker}} 開空倉信號")
2. TradingView告警設置
在TradingView中設置告警時,需要配置以下內容:
- 告警名稱:便于識別
- 告警條件:選擇策略中定義的alertcondition
- 告警消息:包含交易信息
- Webhook URL:指向我們的Flask API端點
告警消息格式示例:
{"symbol": "{{ticker}}","action": "BUY","price": {{close}},"strategy": "long","volume": 1
}
3. Flask后端實現
Flask后端負責接收TradingView的webhook請求,并將信號保存到數據庫:
from flask import Flask, request, jsonify
from database import DatabaseConnectionapp = Flask(__name__)
db = DatabaseConnection()@app.route('/webhook', methods=['POST'])
def webhook():data = request.jsontry:# 驗證數據required_fields = ['symbol', 'action', 'price', 'strategy', 'volume']if not all(field in data for field in required_fields):return jsonify({'error': '缺少必要字段'}), 400# 保存信號到數據庫with db.get_cursor() as c:c.execute('''INSERT INTO trading_signals (symbol, action, price, strategy, volume, status)VALUES (?, ?, ?, ?, ?, 'pending')''', (data['symbol'], data['action'], data['price'], data['strategy'], data['volume']))return jsonify({'message': '信號接收成功'}), 200except Exception as e:return jsonify({'error': str(e)}), 500
4. CTPBee交易執行器
CTPBee交易執行器負責監控數據庫中的交易信號,并執行相應的交易操作:
from ctpbee import CtpBee
from ctpbee.constant import OrderRequest, Direction, Offset, OrderTypeclass SignalMonitor:def __init__(self):self.app = CtpBee("signal_trader", __name__)self.load_config()def execute_order(self, symbol, price, volume, direction, signal_id):"""執行交易訂單"""try:# 創建訂單請求order_req = OrderRequest(symbol=symbol,exchange=self.get_exchange(symbol),price=price,volume=volume,direction=Direction.LONG if direction == "BUY" else Direction.SHORT,offset=Offset.OPEN,type=OrderType.LIMIT,order_id=f"ORDER_{signal_id}")# 發送訂單self.app.send_order(order_req)# 更新信號狀態self.update_signal_status(signal_id, "submitted")except Exception as e:logger.error(f"下單失敗: {str(e)}")self.update_signal_status(signal_id, "failed", str(e))
5. 風控管理
系統實現了基本的風控功能:
- 最大持倉限制
def check_position_limit(self, symbol):"""檢查持倉限制"""positions = self.app.center.positionscurrent_position = sum(p.volume for p in positions if p.symbol == symbol)return current_position < self.max_position
- 自動平倉功能
def close_positions(self, symbol, direction):"""平倉處理"""positions = self.app.center.positionsfor pos in positions:if pos.symbol == symbol and pos.direction == direction:close_req = OrderRequest(symbol=symbol,exchange=self.get_exchange(symbol),price=self.get_latest_price(symbol),volume=pos.volume,direction=Direction.SHORT if direction == Direction.LONG else Direction.LONG,offset=Offset.CLOSETODAY,type=OrderType.LIMIT)self.app.send_order(close_req)
數據可視化
使用Streamlit實現數據可視化,展示交易統計和賬戶信息:
import streamlit as st
import plotly.express as pxdef show_trading_dashboard():st.title("交易信號儀表板")# 賬戶信息col1, col2, col3 = st.columns(3)with col1:st.metric("賬戶余額", f"¥{account_info['balance']:,.2f}")with col2:st.metric("可用資金", f"¥{account_info['available']:,.2f}")with col3:st.metric("持倉盈虧", f"¥{account_info['position_profit']:,.2f}")# 交易信號統計signal_stats = get_signal_statistics()fig = px.pie(signal_stats, values='count', names='action')st.plotly_chart(fig)
部署注意事項
- 配置文件管理
- 使用
config_[sim|ctp].json
區分模擬盤和實盤配置 - 包含CTP連接信息、交易參數等
- 數據庫設計
- 使用SQLite存儲交易信號和賬戶信息
- 實現信號狀態追蹤和錯誤處理
- 性能優化
- 使用NumExpr優化計算性能
- 實現異步處理機制
- 添加日志記錄
- 安全考慮
- 實現API認證機制
- 加密敏感信息
- 添加請求頻率限制
總結
本文介紹了一個基于TradingView和CTPBee的自動化交易系統實現方案,究其設計原因是因為CTPBee是運行獨占式,無法接收外部API請求,故而另辟蹊徑,通過定時讀取sqlite數據庫里的交易信號來實現開平倉動作,而對外提供API接口來接收Tradingview的告警信號,并在收到后寫入sqlite數據,這種模式對實時性要求極差,適合于5分鐘線行情以上的交易策略。系統通過TradingView的策略和告警功能生成交易信號,通過Flask API接收和處理信號,最后使用CTPBee執行實際的交易操作。系統還實現了基本的風控功能和數據可視化,為交易決策提供支持。
參考資料
- TradingView Pine Script文檔
- CTPBee文檔
- Flask文檔
- Streamlit文檔