加密货币策略测试代码索引递增逻辑错误及开仓漏检K线问题排查
问题根因与错误定位
你的代码里共有3处逻辑错误共同导致了开仓后K线被跳过的问题:
- 错误1:open_position函数内的止损止盈判断顺序错误,无端跳过K线
open_position进入循环后,先判断做多方向的止损止盈,无论是否触发平仓,都会立刻执行一次index +=1,之后才判断做空方向的条件。如果你的开仓方向是做空,开仓后的第一根K线直接被加1跳过,不会参与止损止盈校验;就算是做多单,判断完第一根未平仓后也会直接跳转到下一根,平白多跳1根K线。 - 错误2:open_position内每次循环重复执行index +=1
做多判断后执行一次index +=1,做空判断后又执行一次index +=1,等于每轮循环index会增加2,天然跳过1根K线。 - 错误3:run_strategy的index重复累加
open_position执行结束返回当前的index值后,run_strategy末尾会再执行一次index +=1,导致平仓所在的K线直接被跳过,不会参与下一轮的开仓条件校验。
修复方案
你可以参考如下逻辑修改代码:
- 调整open_position内的循环逻辑,先校验当前index对应K线的止损止盈,再统一执行index自增,不要分开在多空判断后各加一次
- run_strategy中,如果已经执行过open_position并更新了index,就不要重复执行末尾的
index +=1,可以用标记位控制
修改后的核心代码示例
def run_strategy(datetime, math, time, csv, file_name, symbol, candlesticks, candlesticks_len, close_prices, rr_ratio, xbar, ema, macd, signal, rsi, upper, lower): index = 0 while index < candlesticks_len: has_opened = False direction = get_direction("rsi", index, close_prices, ema, macd, signal, rsi) if index == 0: clear_file(file_name) check_allowed = is_allowed(direction, index, close_prices, candlesticks, macd, signal, rsi, upper, lower) if (direction == "buy" or direction == "sell") and check_allowed == True: index = open_position(datetime, math, time, csv, file_name, symbol, direction, index, candlesticks, close_prices, rr_ratio, xbar) has_opened = True # 只有没开仓的时候才自增,避免重复累加 if not has_opened: index += 1 def open_position(datetime, math, time, csv, file_name, symbol, direction, index, candlesticks, close_prices, rr_ratio, xbar): ts = int(candlesticks[index][0]) dt_obj = datetime.fromtimestamp(ts / 1000) stop_loss = calc_stop_loss("xbar", direction, float(close_prices[index]), index, candlesticks, xbar) take_profit = calc_take_profit(direction, float(close_prices[index]), stop_loss, rr_ratio) leverage = calc_leverage(math, time, direction, float(close_prices[index]), stop_loss) save_position(csv, file_name, symbol, candlesticks[index][0], dt_obj, index, direction, leverage, close_prices[index], take_profit, stop_loss, "e") # 开仓后从下一根K线开始检查止损止盈 index += 1 while index < len(candlesticks): try: close_flag = False if direction == "buy": if float(candlesticks[index][3]) <= stop_loss: pos_result = "LOST" close_flag = True elif float(candlesticks[index][2]) >= take_profit: pos_result = "WON" close_flag = True else: # sell if float(candlesticks[index][2]) >= stop_loss: pos_result = "LOST" close_flag = True elif float(candlesticks[index][3]) <= take_profit: pos_result = "WON" close_flag = True if close_flag: save_result(csv, file_name, pos_result) return index # 未平仓才跳转到下一根K线 index +=1 except Exception as e: return index return index
内容的提问来源于stack exchange,提问作者yunusus
相关产品推荐
相关产品推荐

