Skip to content

Commit 0e8fe60

Browse files
committed
fix: current_position.json保留所有data_name,无持仓时显示size=0/price=0
- 恢复 _write_current_position 保留所有数据源的仓位记录 - 无持仓的数据源显示 size=0, price=0.0 - 更新测试 - 全部 497 个测试通过
1 parent 48cfcfb commit 0e8fe60

2 files changed

Lines changed: 4 additions & 12 deletions

File tree

backtrader/observers/tradelogger.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -312,14 +312,12 @@ def _write_run_info(self):
312312
json.dump(run_info, f, indent=2, ensure_ascii=False, default=str)
313313

314314
def _write_current_position(self, positions):
315-
"""Overwrite current_position.json with latest non-zero positions only."""
315+
"""Overwrite current_position.json with latest positions for all data feeds."""
316316
if self._log_dir is None or not self.p.log_file_enabled:
317317
return
318318
path = os.path.join(self._log_dir, "current_position.json")
319319
serializable = []
320320
for p in positions:
321-
if p.get("size", 0) == 0:
322-
continue
323321
row = {}
324322
for k, v in p.items():
325323
row[k] = self._format_value(v) if isinstance(v, dt_module.datetime) else v

tests/add_tests/test_observer_tradelogger.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -372,9 +372,7 @@ def test_file_output_log_format():
372372
with open(pos_path, "r") as f:
373373
positions = json.load(f)
374374
assert isinstance(positions, list)
375-
# Only non-zero positions should be in the file
376-
for p in positions:
377-
assert p["size"] != 0
375+
assert len(positions) >= 1
378376
finally:
379377
shutil.rmtree(tmp_dir, ignore_errors=True)
380378

@@ -409,7 +407,7 @@ def test_file_output_csv_format():
409407

410408

411409
def test_current_position_json():
412-
"""Verify current_position.json only contains non-zero positions."""
410+
"""Verify current_position.json contains all data feeds with valid structure."""
413411
tmp_dir = tempfile.mkdtemp()
414412
try:
415413
cerebro, strat = _create_cerebro(observer_kwargs=dict(
@@ -425,15 +423,11 @@ def test_current_position_json():
425423
with open(pos_path, "r") as f:
426424
positions = json.load(f)
427425
assert isinstance(positions, list)
428-
# All entries in current_position.json must have non-zero size
426+
assert len(positions) >= 1
429427
for p in positions:
430428
assert "data_name" in p
431429
assert "size" in p
432430
assert "price" in p
433-
assert p["size"] != 0, (
434-
f"current_position.json should only contain non-zero positions, "
435-
f"got size=0 for {p.get('data_name')}"
436-
)
437431
finally:
438432
shutil.rmtree(tmp_dir, ignore_errors=True)
439433

0 commit comments

Comments
 (0)