217 lines
14 KiB
Python
217 lines
14 KiB
Python
from re import L
|
|
from core import util
|
|
from core.strategy_db import TradeTarget
|
|
from core.util import is_trading_time, queryPendingOrder
|
|
|
|
from xtquant import xttrader, xtconstant
|
|
from xtquant.xttype import StockAccount, XtOrder, XtOrderResponse, XtTrade
|
|
import sfgrid_constants
|
|
import threading
|
|
|
|
|
|
class StockTradeController:
|
|
|
|
def __init__(self, tradeTarget: TradeTarget, xt_trader: xttrader.XtQuantTrader, account: StockAccount, enabled: bool = False):
|
|
self.tradeTarget:TradeTarget = tradeTarget
|
|
self.xt_trader: xttrader.XtQuantTrader = xt_trader
|
|
self.account:StockAccount = account
|
|
self.enabledTrading(enabled)
|
|
self.dataUpdateLock = threading.Lock()
|
|
|
|
def getName(self):
|
|
return "SFGRID"
|
|
|
|
|
|
def enabledTrading(self, enabled: bool):
|
|
self.tradeTarget.enabled = enabled # type: ignore
|
|
self.tradeTarget.save()
|
|
pendingOrders = queryPendingOrder(str(self.tradeTarget.stock_code),self.getName(), self.xt_trader,self.account)
|
|
|
|
if len(pendingOrders) > 0:
|
|
print(f' |- 已存在{len(pendingOrders)}订单,全部取消,按需要重下。')
|
|
for order in pendingOrders:
|
|
self.xt_trader.cancel_order_stock(self.account, order.order_id)
|
|
|
|
if enabled:
|
|
print(f" |- 标的{self.tradeTarget.targetName()}交易启动, position {self.tradeTarget.current_position}")
|
|
# 建仓状态检查
|
|
if int(self.tradeTarget.current_position) == 0 and int(self.tradeTarget.status) == 0: # type: ignore
|
|
self.tradeTarget.grid_index = 1 # type: ignore
|
|
self.tradeTarget.save()
|
|
self.init_stock_position()
|
|
print(f" |- 标的{self.tradeTarget.targetName()}建初始仓 买单已发出 InitBuyOrderId: {self.initBuyOrderId} Price: {sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)]} Volume: {sfgrid_constants.grid_volume}") # type: ignore
|
|
else:
|
|
# 交易阶段,检查仓位,检查现有订单
|
|
print(f" |- 标的{self.tradeTarget.targetName()}已有仓位或非初始状态 无需建初始仓 当前仓位: {self.tradeTarget.current_position} 状态: {self.tradeTarget.status}")
|
|
minRequirePosition:int = sfgrid_constants.grid_volume * int(self.tradeTarget.grid_index) # type: ignore
|
|
if minRequirePosition <= int(self.tradeTarget.current_position): # type: ignore
|
|
print(f' |- 仓位检查: 持仓需求充足, (gridVolume*gridIndex)={minRequirePosition}, 当前持仓:{self.tradeTarget.current_position}')
|
|
else:
|
|
print(f' |- 仓位检查: 持仓需求不足, (gridVolume*gridIndex)={minRequirePosition}, 当前持仓:{self.tradeTarget.current_position}')
|
|
|
|
|
|
def isEnabled(self) -> bool:
|
|
return bool(self.tradeTarget.enabled)
|
|
|
|
def onDataUpdate(self, data):
|
|
if not self.isEnabled():
|
|
return
|
|
self.dataUpdateLock.acquire()
|
|
index = self.tradeTarget.grid_index
|
|
price = sfgrid_constants.grid_price[int(index)] # pyright: ignore[reportArgumentType]
|
|
lowPrice = sfgrid_constants.grid_price[int(index) + 1] # pyright: ignore[reportArgumentType]
|
|
highPrice = sfgrid_constants.grid_price[int(index) - 1] # pyright: ignore[reportArgumentType]
|
|
|
|
lastPrice = float("{:.3f}".format(data[self.tradeTarget.stock_code]['lastPrice']))
|
|
print(f"标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 市价: {lastPrice}, 网格序号: {index}, 网格价格: {price}, 计划多单价: {lowPrice}, 计划空单价: {highPrice}")
|
|
|
|
if lastPrice <= lowPrice: # 下下方多单
|
|
orders = queryPendingOrder(str(self.tradeTarget.stock_code), self.getName(), self.xt_trader, self.account)
|
|
if len([order for order in orders if order.order_type == xtconstant.STOCK_BUY and order.price == lowPrice]) > 0:
|
|
# 已存在未交易的多单
|
|
print(f' |- 已存在未交易的多单,不重复下单')
|
|
else:
|
|
print(f' |- 下网格多单')
|
|
self.tradeTarget.current_buy_order_no = self.xt_trader.order_stock_async(
|
|
self.account,
|
|
str(self.tradeTarget.stock_code),
|
|
xtconstant.STOCK_BUY,
|
|
sfgrid_constants.grid_volume,
|
|
xtconstant.FIX_PRICE,
|
|
lowPrice,
|
|
self.getName(), # strategy_name
|
|
self.tradeTarget.stock_code # remark # type: ignore
|
|
)
|
|
self.tradeTarget.grid_index = int(index) + 1 # type: ignore
|
|
self.tradeTarget.current_buy_price = float(lowPrice) # type: ignore
|
|
print(f' |- 下网格多单号 {self.tradeTarget.current_buy_order_no}, 网格基准价 {price}, 下单价 {lowPrice}, 下单量 {sfgrid_constants.grid_volume}')
|
|
elif lastPrice == highPrice: # 下上方空单
|
|
orders = queryPendingOrder(str(self.tradeTarget.stock_code), self.getName(), self.xt_trader, self.account)
|
|
if len([order for order in orders if order.order_type == xtconstant.STOCK_SELL and order.price == highPrice]) > 0:
|
|
# 已存在未交易的空单
|
|
print(f' |- 已存在未交易的空单,不重复下单')
|
|
else:
|
|
print(f' |- 下网格空单')
|
|
self.tradeTarget.current_sell_order_no = self.xt_trader.order_stock_async(
|
|
self.account,
|
|
str(self.tradeTarget.stock_code),
|
|
xtconstant.STOCK_SELL,
|
|
sfgrid_constants.grid_volume,
|
|
xtconstant.FIX_PRICE,
|
|
highPrice,
|
|
self.getName(),
|
|
self.tradeTarget.stock_code) # type: ignore
|
|
self.tradeTarget.grid_index = int(index) - 1 # type: ignore
|
|
self.tradeTarget.current_sell_price = float(highPrice) # type: ignore
|
|
print(f' |- 下网格空单号 {self.tradeTarget.current_sell_order_no}, 网格基准价 {price}, 下单价 {highPrice}, 下单量 {sfgrid_constants.grid_volume}')
|
|
self.tradeTarget.save()
|
|
self.dataUpdateLock.release()
|
|
|
|
|
|
def onAsyncOrderResponse(self, order:XtOrderResponse):
|
|
self.dataUpdateLock.acquire()
|
|
stockCode = order.order_remark
|
|
orderSeq = order.seq
|
|
if self.tradeTarget.current_buy_order_no == order.seq:
|
|
self.tradeTarget.current_buy_order_no = order.order_id
|
|
elif self.tradeTarget.current_sell_order_no == order.seq:
|
|
self.tradeTarget.current_sell_order_no = order.order_id
|
|
else:
|
|
print(f' |- 委托回调: 委托单 {order.order_id} {stockCode} {orderSeq} 不在策略监控范围内')
|
|
return
|
|
rc = self.tradeTarget.save()
|
|
print(f' |- 委托回调: 委托单 {order.order_id} {stockCode} {orderSeq} 处理结果: {rc}')
|
|
self.dataUpdateLock.release()
|
|
|
|
def onOrderTrade(self, trade:XtTrade):
|
|
self.dataUpdateLock.acquire()
|
|
if int(self.tradeTarget.status) == 0 and trade.order_id == self.initBuyOrderId : # type: ignore
|
|
# 此时为建仓成交
|
|
self.tradeTarget.current_position = int(self.tradeTarget.current_position) + trade.traded_volume # 当前持仓数,账户原有持仓不在策略范围内 # type: ignore
|
|
self.tradeTarget.last_trade_price = float(trade.traded_price) # type: ignore
|
|
self.tradeTarget.grid_index = 1 # type: ignore
|
|
self.tradeTarget.status = 1 # type: ignore
|
|
self.tradeTarget.save()
|
|
print(f"|- 标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 建初始仓订单ID: {self.initBuyOrderId}已成交 ")
|
|
print(f' 成交价: {trade.traded_price} 成交量: {trade.traded_volume}')
|
|
print(f' 当前持仓: {self.tradeTarget.current_position}')
|
|
print(f' 网格坐标: {self.tradeTarget.grid_index}')
|
|
elif trade.order_id == self.tradeTarget.current_sell_order_no and int(self.tradeTarget.status) == 1: # type: ignore
|
|
# 上涨一格:此时空单成交
|
|
self.tradeTarget.current_position = int(self.tradeTarget.current_position) - trade.traded_volume # type: ignore
|
|
self.tradeTarget.last_trade_price = float(trade.traded_price) # type: ignore
|
|
self.tradeTarget.grid_index = int(self.tradeTarget.grid_index) - 1 # type: ignore
|
|
self.tradeTarget.save()
|
|
print(f"|- 标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 上涨 卖单已成交 订单ID: {self.tradeTarget.current_sell_order_no} Price: {sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)]} Volume: {sfgrid_constants.grid_volume} 手续费: {trade.commission}\n") # type: ignore
|
|
print(f' 成交价: {trade.traded_price} 成交量: {trade.traded_volume}')
|
|
print(f' 当前持仓: {self.tradeTarget.current_position}')
|
|
print(f' 网格坐标: {self.tradeTarget.grid_index}')
|
|
cancelResult = self.xt_trader.cancel_order_stock_async(self.account, self.tradeTarget.current_buy_order_no)
|
|
print(f' 上涨一格,空单成交,对侧买单已撤单 cancelResult: {cancelResult > 0}')
|
|
elif trade.order_id == self.tradeTarget.current_buy_order_no and int(self.tradeTarget.status) == 1: # type: ignore
|
|
# 下跌一格:此时多单成交
|
|
self.tradeTarget.current_position = int(self.tradeTarget.current_position) + trade.traded_volume # type: ignore
|
|
self.tradeTarget.last_trade_price = float(trade.traded_price) # type: ignore
|
|
self.tradeTarget.grid_index = int(self.tradeTarget.grid_index) + 1 # type: ignore
|
|
self.tradeTarget.save()
|
|
print(f"|- 标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 下跌 买单已成交 订单ID: {self.tradeTarget.current_buy_order_no} Price: {trade.traded_price} Volume: {sfgrid_constants.grid_volume} 手续费: {trade.commission}")
|
|
print(f' 成交价: {trade.traded_price} 成交量: {trade.traded_volume}')
|
|
print(f' 当前持仓: {self.tradeTarget.current_position}')
|
|
print(f' 网格坐标: {self.tradeTarget.grid_index}')
|
|
cancelResult = self.xt_trader.cancel_order_stock_async(self.account, self.tradeTarget.current_sell_order_no)
|
|
print(f' 下跌一格,多单成交,对侧卖单已撤单 cancelResult: {cancelResult > 0}')
|
|
else:
|
|
# 打印订单信息和订单状态
|
|
print(f'|- 非策略内部订单,或订单状态不满足监控条件 {trade.order_id} {trade.stock_code}-{trade.instrument_name} {trade.commission}')
|
|
|
|
self.dataUpdateLock.release()
|
|
|
|
|
|
# Description: 新标的,建基础仓
|
|
def init_stock_position(self):
|
|
self.initBuyOrderId = self.xt_trader.order_stock(
|
|
self.account,
|
|
str(self.tradeTarget.stock_code),
|
|
xtconstant.STOCK_BUY,
|
|
sfgrid_constants.grid_volume,
|
|
xtconstant.FIX_PRICE,
|
|
sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)], # type: ignore
|
|
'sf_grid', f'{self.tradeTarget.stock_code}_init_buy')
|
|
print(f"|- 标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 建初始仓 买单已发出 InitBuyOrderId: {self.initBuyOrderId} Price: {sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)]} Volume: {sfgrid_constants.grid_volume}\n") # type: ignore
|
|
|
|
|
|
# Description: 网格跳格,双向下单
|
|
# def two_way_order(self, buy, sell):
|
|
# print(f'|- 标的{self.tradeTarget.stock_code}-{self.tradeTarget.stock_name} 网格跳格,双向下单')
|
|
# print(f' |- 网格坐标: {self.tradeTarget.grid_index}, buy:{buy}, sell:{sell}')
|
|
# if buy and int(self.tradeTarget.grid_index)+1 < len(sfgrid_constants.grid_price): # 价格没有超过网格下边界,可以下多单 # type: ignore
|
|
# currentPrice = sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)] # type: ignore
|
|
# buyPrice = sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)+1] # type: ignore
|
|
# self.tradeTarget.current_buy_order_no = self.xt_trader.order_stock_async(
|
|
# self.account,
|
|
# str(self.tradeTarget.stock_code),
|
|
# xtconstant.STOCK_BUY,
|
|
# sfgrid_constants.grid_volume,
|
|
# xtconstant.FIX_PRICE,
|
|
# buyPrice,
|
|
# self.getName(), # strategy_name
|
|
# self.tradeTarget.stock_code # remark # type: ignore
|
|
# )
|
|
# self.tradeTarget.current_buy_price = float(buyPrice) # type: ignore
|
|
# print(f' |- 下网格多单 OrderId {self.tradeTarget.current_buy_order_no}, 网格基准价 {currentPrice}, 下单价 {buyPrice}, 下单量 {sfgrid_constants.grid_volume}')
|
|
|
|
# if sell and int(self.tradeTarget.grid_index)-1 >=0: # 价格没有超过网格上边界,可以下空单 # type: ignore
|
|
# currentPrice = sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)] # type: ignore
|
|
# sellPrice = sfgrid_constants.grid_price[int(self.tradeTarget.grid_index)-1] # type: ignore
|
|
# self.tradeTarget.current_sell_order_no = self.xt_trader.order_stock_async(
|
|
# self.account,
|
|
# str(self.tradeTarget.stock_code),
|
|
# xtconstant.STOCK_SELL,
|
|
# sfgrid_constants.grid_volume,
|
|
# xtconstant.FIX_PRICE,
|
|
# sellPrice,
|
|
# self.getName(),
|
|
# self.tradeTarget.stock_code) # type: ignore
|
|
# self.tradeTarget.current_sell_price = float(sellPrice) # type: ignore
|
|
# print(f' |- 下网格空单 OrderId {self.tradeTarget.current_sell_order_no}, 网格基准价 {currentPrice}, 下单价 {sellPrice}, 下单量 {sfgrid_constants.grid_volume}')
|
|
# self.tradeTarget.save() |