TOPIC量化交流
精品

【测试】网格交易策略,一个常见的自动交易策略。

import json
from datetime import datetime, timedelta

import numpy as np
import requests
from pydantic import BaseModel, Field

#########################################################

#########################################################
# 初始化变量
class Params(BaseModel, validate_assignment=True):
# 多单还是空单网格
grid_type: dict = Field(default={"options": ["多单网格", "空单网格"], "value": "多单网格"}, title="网格方向")

# * 网格起始点
start_price: float = Field(default=10000, title="网格起始位置(多:最大值 空:最小值)")

max_volume: int = Field(default=300, title="总网格数") # * 最大持仓手数

volume: int = Field(default=1, title="每格开单数量")

# 开仓步长和平仓步长方式选择:主要在于计算网格价格

open_step_type: dict = Field(default={"options": ["等差", "等比"], "value": "等差"}, title="开仓逻辑")
open_step_size: float = Field(default=10, title="开仓步长基值")
open_step_ratio: float = Field(default=2, title="开仓等比步长倍数")
# todo
# close_step_type: int = Field(default=0, title='平仓逻辑(上个开仓价)')
# close_step_type: int = Field(default=0, title='平仓逻辑(0:上个开仓价 1:等差 2:等比)')
# close_step_size: int = Field(default=5, title='平仓步长基值')
# close_step_ratio: float = Field(default=1.2, title='平仓等比步长倍数')
# todo
day_close_sig: dict = Field(default={"options": ["启用", "关闭"], "value": "关闭"}, title="是否启用日内清仓")
# 平移网格相关参数
shift_border: int = Field(
default=10, title="连续多少根K线破网则平移网格"
) # 价格单边连续破界shift_border次,就平移网格
shift_len: float = Field(default=10, title="网格平移多少跳")

# 扩大网格相关参数
enlarge_border: int = Field(default=10, title="连续多少根K线扩大或缩小")
enlarge_len: float = Field(default=1, title="步长变化值")

# 移动网格相关参数
if_translate: dict = Field(
default={"options": ["启用", "关闭"], "value": "关闭"}, title="空仓且价格脱离网格区间时移动网格"
)
translate_len: float = Field(default=100, title="脱离多少跳启动移动网格")

# * 累计止盈止损参数
# * 累计收益:所有持仓 + 已平仓的部分的总收益,其中持仓收益是指(当前市场价格−持仓平均买入价)×持仓数量
tp_sl_sig: dict = Field(default={"options": ["启用", "关闭"], "value": "启用"}, title="止盈止损启止信号")
tp_value: float = Field(default=1000000, title="止盈金额") # 止盈金额
sl_value: float = Field(default=100000, title="止损金额") # 止损金额

def on_init(context):
put_log("进阶版网格策略(版本2025_08_01 11:30)启动", level="ERROR")
put_log(
f"参数输出:{context.grid_type['value']},{context.start_price},{context.max_volume},{context.volume},{context.open_step_type['value']},{context.open_step_size},{context.open_step_ratio},{context.day_close_sig['value']},{context.shift_border},{context.shift_len},{context.enlarge_border},{context.enlarge_len},{context.if_translate['value']},{context.translate_len},{context.tp_sl_sig['value']},{context.tp_value},{context.sl_value}",
level="ERROR",
)
# 初始化任务队列
context.task_queue = []
# 初始化执行状态锁
context.processing = False

context.run_mode = BASE_MODE == "REAL" # 为True时,运行在任务上;为False时,运行在回测上

context.symbol = BASE_SETTING.get("Instrument") # 获取用户设置合约id
context.exchange_id = get_symbolinfo(str(context.symbol)).get("exchange_id") # 获取用户设置合约id对应的交易所
context.period = BASE_SETTING.get("bPeriod") # 获取用户设置周期
context.price_tick = get_symbolinfo(str(context.symbol)).get("price_tick") # 获取用户设置合约的一跳的距离
context.volume_multiple = get_symbolinfo(str(context.symbol)).get("volume_multiple") # 获取用户设置合约乘数
context.is_first_or_change = True # 是否第一次运行

context.open_step_size_p = round(context.price_tick * context.open_step_size, 2) # 开仓步长
context.shift_len_p = round(context.price_tick * context.shift_len, 2) # 平移步长
context.enlarge_len_p = round(context.price_tick * context.enlarge_len, 2) # 扩大步长
context.translate_len_p = round(context.price_tick * context.translate_len, 2) # 移动步长

context.trading_time = get_trading_time(context.symbol) # 获取交易时间
# context.trading_time = {'day': [['09:00:01', '10:14:59'], ['10:30:01', '11:29:59'], ['13:30:01', '14:59:40']], 'night': [['21:00:01', '02:29:59']]}
# context.trading_time = {
# "day": [["09:00:01", "14:35:10"], ["14:38:01", "22:29:59"]],
# "night": [["23:20:30", "00:59:59"]],
# }

put_log(f"交易时间:{context.trading_time}", level="ERROR")

context.order_management = {} # 订单管理字典
context.order_management[context.symbol] = {
"order": {"buy": {"open": {}, "close": {}}, "sell": {"open": {}, "close": {}}}, # 只保存当前的挂单
"trade": {"buy": {"vol": 0}, "sell": {"vol": 0}}, # 只保存当前的持仓
"save": {
"buy": {"open": {}, "close": {}},
"sell": {"open": {}, "close": {}},
}, # 保存之前的已成交单,方便计算盈利情况
}
context.open_close_reqID = {} # 开仓平仓reqID字典
context.open_levels = [] # 开仓价格
context.close_levels = [] # 平仓价格
context.close_open = {} # 平仓对应开仓
context.save_close_price = {} # 保存不在涨跌停范围内的平仓价格 结构:{当前id:价格,当前id:价格,...}

context.restart_close_order_list = [] # 重启平仓列表

context.tp_sl_flag = False # 止盈止损是否启动标志
context.day_close_flag = False # 用于判断是否已经发出过日内平仓
context.time_remove_flag = False # 用于判断是否已经发出过间隔时间撤单

context.counter = 0

grid_price_init(context)

#########################################################

#########################################################
# 以下为确定开仓序列的功能函数
def grid_price_init(context):
remove_open_orders(context, context.symbol)
wait_time(1)
if context.open_step_type.get("value") == "等差": # 等差步长计算方式
same_step_array_init(context)
else: # 等比步长计算方式
Proportional_array_init(context)

def init_ordersys_id(context):
"""初始化/恢复订单ID列表"""
if context.is_first_or_change:
reqID = [0] * (context.max_volume + 1) # 明确初始化长度
context.is_first_or_change = False
else:
reqID = [data["req_id"] for data in context.open_close_reqID.values()]
return reqID

# 计算等差网格
def same_step_array_init(context):
open_levels = []
close_levels = []
reqID = []
if context.grid_type.get("value") == "多单网格": # 做多网格
open_levels = [
round(context.start_price - (i + 1) * context.open_step_size_p, 2) for i in range(context.max_volume)
]
close_levels = [round(context.start_price - i * context.open_step_size_p, 2) for i in range(context.max_volume)]
else: # 做空网格
open_levels = [
round(context.start_price + (i + 1) * context.open_step_size_p, 2) for i in range(context.max_volume)
]
close_levels = [round(context.start_price + i * context.open_step_size_p, 2) for i in range(context.max_volume)]

context.open_levels = open_levels
context.close_levels = close_levels

# 新增:检查所有开仓/平仓价格是否为负
has_negative = any(price < 0 for price in context.open_levels + context.close_levels)
if has_negative:
put_log("等差网格生成负价格,策略终止!请调整起始价格或步长参数", level="ERROR")
remove() # 直接终止策略避免无效报单

reqID = init_ordersys_id(context)

context.open_close_reqID = {
open: {"close": close, "req_id": reqID}
for open, close, reqID in zip(context.open_levels, context.close_levels, reqID)
}

context.close_open = {close: open for close, open in zip(context.close_levels, context.open_levels)}

# 计算等比网格价格
def multiple(context, i):
diff = 0
diff += pow(context.open_step_ratio, (i + 1))
return diff

def Proportional_array_init(context):
open_levels = []
close_levels = []
reqID = []

if context.grid_type.get("value") == "多单网格": # 做多网格
open_levels = [round(context.start_price - multiple(context, i + 1), 2) for i in range(context.max_volume)]
close_levels = [round(context.start_price - multiple(context, i), 2) for i in range(context.max_volume)]
else: # 做空网格
open_levels = [round(context.start_price + multiple(context, i + 1), 2) for i in range(context.max_volume)]
close_levels = [round(context.start_price + multiple(context, i), 2) for i in range(context.max_volume)]

context.open_levels = open_levels
context.close_levels = close_levels
# 新增:检查所有开仓/平仓价格是否为负(原仅检查首尾)
has_negative = any(price < 0 for price in context.open_levels + context.close_levels)
if has_negative:
put_log("等比网格生成负价格,策略终止!请调整起始价格或步长参数", level="ERROR")
remove() # 直接终止策略避免无效报单

reqID = init_ordersys_id(context)

context.open_close_reqID = {
open: {"close": close, "req_id": reqID}
for open, close, reqID in zip(context.open_levels, context.close_levels, reqID)
}

context.close_open = {close: open for close, open in zip(context.close_levels, context.open_levels)}

def find_nearest_open(context, open_prices, target_price):
"""
在 open 列表中找到最接近 price 的两个 open 值

参数:
sorted_open_list (list): 从大到小排序的 open 列表
price (float): 目标价格

返回:
tuple: (left_open, right_open)
- left_open: 第一个 ≤ price 的 open
- right_open: 最后一个 ≥ price 的 open
如果 price 超出范围,返回边界值
"""
if context.grid_type.get("value") == "空单网格":
open_prices = open_prices[::-1]
left_open = None # 第一个 ≤ price 的 open
right_open = None # 最后一个 ≥ price 的 open

for open_val in open_prices:
if open_val >= target_price:
right_open = open_val
else:
left_open = open_val
break # 由于列表降序,后续的 open 更小,无需继续

# 处理边界情况
if left_open is None: # price 比所有 open 都大
left_open = right_open
if right_open is None: # price 比所有 open 都小
right_open = left_open

return right_open if context.grid_type.get("value") == "空单网格" else left_open

#########################################################
# tick模块
def tick_open(context, last_price):
if context.run_mode: # 运行在任务上
if not is_in_trading_time(context.trading_time):
return
nearest_open = find_nearest_open(context, context.open_levels, last_price)
if (
float(get_tick(context.symbol).get("LowerLimitPrice"))
< nearest_open
< float(get_tick(context.symbol).get("UpperLimitPrice"))
):
if context.run_mode: # 运行在任务上
if context.open_close_reqID[nearest_open]["req_id"] == 0 and is_in_trading_time(context.trading_time):
res = send_open(context, nearest_open)
req_id = res["data"]["result"]["data"]["req_id"]
if res["code"] == 0:
put_log(f"开仓报单,价格{nearest_open},req_id{req_id}", level="USER_LOG")
context.open_close_reqID[nearest_open]["req_id"] = req_id
else:
put_log(f"开仓报单失败,价格{nearest_open},req_id{req_id}", level="ERROR")
else: # 运行在回测上
if context.open_close_reqID[nearest_open]["req_id"] == 0:
res = send_open(context, nearest_open)
req_id = res["data"]["result"]["data"]["req_id"]
context.open_close_reqID[nearest_open]["req_id"] = req_id
else:
put_log(f"现价{last_price}距离最近的网格点位{nearest_open}大于一个网格宽度,不开仓,等待调整", level="ERROR")

def on_tick(context):
last_price = float(BASE_SYMBOL_TICK.get("LastPrice")) # 目前的最新价格

context.counter += 1
if context.counter >= 301:
if context.run_mode: # 运行在任务上
context.task_queue.append(lambda ctx=context, sy=context.symbol: periodic_cancel_orders(ctx, sy))
# nearest_open = find_nearest_open(context, context.open_levels, last_price)
# lower_limit = round(float(get_tick(context.symbol).get("LowerLimitPrice")), 2)
# upper_limit = round(float(get_tick(context.symbol).get("UpperLimitPrice")), 2)
# put_log(f"当前最近开仓点: {nearest_open}, 涨跌停范围: [{lower_limit}, {upper_limit}]", level='ERROR')
# put_log(f"该点位req_id: {context.open_close_reqID.get(nearest_open, {}).get('req_id', '未找到')}", level='ERROR')
context.counter = 0

if context.counter % 9 == 0:
# 计算当前挂开仓单和平仓单数量
if context.grid_type["value"] == "多单网格":
open_orders = len(context.order_management[context.symbol]["order"]["buy"]["open"])
close_orders = len(context.order_management[context.symbol]["order"]["sell"]["close"])
elif context.grid_type["value"] == "空单网格":
open_orders = len(context.order_management[context.symbol]["order"]["sell"]["open"])
close_orders = len(context.order_management[context.symbol]["order"]["buy"]["close"])
put_log(
f"持仓数量:{context.order_management[context.symbol]['trade']['buy']['vol'] + context.order_management[context.symbol]['trade']['sell']['vol']},多仓数量{context.order_management[context.symbol]['trade']['buy']['vol']},空仓数量{context.order_management[context.symbol]['trade']['sell']['vol']},挂单总数{open_orders + close_orders},挂开仓单数量{open_orders},挂平仓单数量{close_orders},可用平仓数量{context.order_management[context.symbol]['trade']['buy']['vol'] + context.order_management[context.symbol]['trade']['sell']['vol'] - close_orders}",
level="ERROR",
)
# todo
# if (
# context.order_management[context.symbol]["trade"]["buy"]["vol"]
# + context.order_management[context.symbol]["trade"]["sell"]["vol"]
# - close_orders
# > 0
# ):
# put_log("当前可用平仓数量大于0,补平仓", level="ERROR")

# 这里下方添加每个tick前序判断或执行任务
if (
context.tp_sl_sig.get("value") == "启用" and not context.tp_sl_flag and is_in_trading_time(context.trading_time)
): # 止盈止损信号
profit_loss = calculate_profit_loss(context) # 计算利润和损失
# put_log(f"利润:{profit}",level='ERROR')
if profit_loss >= context.tp_value: # 利润大于等于止盈金额
put_log(f"利润大于等于止盈金额{context.tp_value},触发止盈", level="ERROR")
context.tp_sl_flag = True
close_all_positions(context, context.symbol) # 平仓
remove() # 移除策略
if profit_loss <= -abs(context.sl_value): # 利润小于等于止损金额
put_log(f"利润小于等于止损金额{context.sl_value},触发止损", level="ERROR")
context.tp_sl_flag = True
close_all_positions(context, context.symbol) # 平仓
remove() # 移除策略

if context.run_mode: # 运行在任务上
if not is_in_trading_time(context.trading_time): # 非交易时间
if is_in_interval(context.trading_time): # 判断当前是否在间隔时段内
if context.day_close_sig.get("value") == "启用" and not context.day_close_flag: # 启动日内清仓功能
context.day_close_flag = True # 标记已经发出过日内清仓
put_log("到达日内清仓时间", level="ERROR")
close_all_positions(context, context.symbol) # 移除挂单,并清除仓位
elif (
context.day_close_sig.get("value") != "启用" and not context.time_remove_flag
): # 不启动日内清仓功能,先撤单下次开盘时再挂单
context.time_remove_flag = True
put_log("到达提前撤单时间", level="ERROR")
context.task_queue.append(lambda ctx=context, syb=context.symbol: remove_all_orders(ctx, syb))
else: # 交易时间
if context.time_remove_flag: # 是否需要重新挂单
put_log("添加重新挂单任务", level="ERROR")
context.task_queue.append(lambda ctx=context: restart_close_orders(ctx))
context.time_remove_flag = False
if context.day_close_flag: # 已经日内清仓
context.day_close_flag = False
else: # 运行在回测上
pass

# 这里下方添加每个tick需要对数据进行重赋值的判断或执行任务
# put_log(f"{context.processing},{len(context.task_queue)}",level='ERROR')
# put_log(f"交易时间{is_in_trading_time(context.trading_time)}", level='ERROR')
if not context.processing:
# 检测任务队列并执行队列中的首个任务
if len(context.task_queue) > 0:
context.processing = True
while len(context.task_queue) > 0:
current_task = context.task_queue.pop(0)
current_task() # 执行任务函数
context.processing = False

# 这里下方添加每个tick后续判断或执行任务
if len(context.task_queue) == 0 and not context.tp_sl_flag:
if context.run_mode: # 运行在任务上
if is_in_trading_time(context.trading_time) and (
float(get_tick(context.symbol).get("LowerLimitPrice"))
< last_price
< float(get_tick(context.symbol).get("UpperLimitPrice"))
):
context.task_queue.append(lambda ctx=context, lp=last_price: tick_open(ctx, lp))
context.task_queue.append(lambda ctx=context: change_grid_operation(ctx)) # 网格平移,移动,扩大操作
context.task_queue.append(lambda ctx=context: restart_close_price(ctx)) # 检查是否需要重新挂平仓单
else: # 运行在回测上
if (
float(get_tick(context.symbol).get("LowerLimitPrice"))
< last_price
< float(get_tick(context.symbol).get("UpperLimitPrice"))
):
context.task_queue.append(lambda ctx=context, lp=last_price: tick_open(ctx, lp))
context.task_queue.append(lambda ctx=context: change_grid_operation(ctx)) # 网格平移,移动,扩大操作
context.task_queue.append(lambda ctx=context: restart_close_price(ctx)) # 检查是否需要重新挂平仓单


全部回复2 条

按楼层正序

登录后可回复主题。社区会话与官网账号体系共用。