
等级: 新手上路
- 注册:
- 2024-6-15
- 曾用名:
|

楼主 |
发表于 2025-2-5 09:48
|
显示全部楼层
好的,谢谢老师,主要是针对避免在震荡行情中频繁触发止损,就想通过动态调整止损位置来减少不必要的交易。以下是假期期间通过deepseek帮忙写的代码,麻烦帮忙看看,好像金字塔运行不了,不知道什么地方出错了。
策略需求:在交易过程中逐渐拉高止损位置,例如从1小时级别的MA20均线调整为2小时级别的MA20均线,在过去10个收盘价中如果触发一次1小时周期的MA20均线止损的情形,那么下次止损就要对应到2小时周期的MA20均线止损了
以下为deepseek给出的公式,虽然看懂了,但实操回测没反应:
### **策略代码**
#### 公式A(开仓条件)
```pel
// 公式A:计算1小时周期的MA20均线
cond11: cross(close, ma(close, 20)); // 价格上穿MA20
cond22: cross(ma(close, 20), close); // 价格下穿MA20
```
#### 公式B(平仓条件与动态止损)
```pel
// 公式B:动态止损逻辑
vars:
stoplosslevel(0), // 动态止损位置
stopcount(0), // 记录止损触发次数
dynamicstop(false); // 是否启用动态止损
// 初始化止损触发次数
if barstatus = 2 then // 每个K线结束时
begin
if stopcount > 0 then
stopcount = stopcount - 1; // 每根K线减少止损计数
end;
// 调用1小时周期的cond11(开仓条件)
if stkindi('', 'A.cond11', 0, 5, -1) then
begin
buy(1, 1, marketr); // 买入1手
stoplosslevel = ma(close, 20); // 初始止损为1小时MA20
stopcount = 10; // 重置止损计数
dynamicstop = false; // 初始不启用动态止损
end;
// 动态调整止损位置
if position > 0 then // 如果当前持有多头
begin
// 如果在过去10根K线中触发过止损,则启用动态止损
if stopcount < 10 and stopcount > 0 then
begin
dynamicstop = true;
end;
// 如果启用动态止损,则使用2小时MA20
if dynamicstop then
begin
stoplosslevel = max(stoplosslevel, stkindi('', 'ma(close, 20)', 0, 6, -1)); // 6表示2小时周期
end
else
begin
stoplosslevel = ma(close, 20); // 否则使用1小时MA20
end;
end;
// 平仓条件
// 1. 价格跌破1小时MA20
// 2. 价格跌破动态止损位置
if stkindi('', 'A.cond22', 0, 5, -1) or close < stoplosslevel then
begin
sell(1, 0, marketr); // 卖出平仓
if close < stoplosslevel then
stopcount = 10; // 如果触发止损,重置止损计数
end;
```
---
### **代码逻辑说明**
1. **开仓条件**:
- 当价格突破1小时MA20均线时(`cond11`),执行买入操作。
- 初始止损位置为1小时MA20。
2. **平仓条件**:
- 如果价格跌破1小时MA20均线(`cond22`),则卖出。
- 如果价格跌破动态止损位置(`stoplosslevel`),则卖出。
3. **动态止损**:
- 如果在过去10根K线中触发过止损,则启用动态止损。
- 动态止损时,止损位置从1小时MA20调整为2小时MA20。
4. **止损触发记录**:
- 每根K线结束时,`stopcount`减1。
- 如果触发止损,`stopcount`重置为10。 |
|