允许卖出回款减少策略账本负现金

This commit is contained in:
baobao 2026-11-23 09:52:36 +08:00
parent 1fd640bffb
commit 6a7ca9687a
3 changed files with 49 additions and 1 deletions

View File

@ -70,7 +70,7 @@ def fill(account, book, side, amount, fee_amount, key, *, verified_late_buy=Fals
if book not in BOOKS or side not in ('buy', 'sell') or amount <= 0 or fee_amount < 0:
raise ValueError('成交资金参数非法')
change = (amount if side == 'sell' else -amount)-fee_amount
if account['cash'][book]+change < -1e-6 and not (verified_late_buy and side == 'buy'):
if change < 0 and account['cash'][book]+change < -1e-6 and not (verified_late_buy and side == 'buy'):
raise ValueError('策略现金不足,不能跨账本透支')
account['cash'][book] += change
account['fees'][book] += fee_amount

View File

@ -13,6 +13,22 @@ from app.core import rotation_account as core, strategy_book as books
from app.services import rotation_accounting as accounting, rotation_service as rotation
class SaleCashTests(unittest.TestCase):
def test_net_sell_receipt_reduces_debt_but_buy_and_net_debit_still_fail(self):
capital = core.seed(10000, {})
capital['cash']['micro30'] = -3000.
for side, fees in (('buy', 3.), ('sell', 1001.)):
with self.subTest(side=side):
before = copy.deepcopy(capital)
with self.assertRaisesRegex(ValueError, '策略现金不足'):
core.fill(capital, 'micro30', side, 1000., fees, 'sale')
self.assertEqual(capital, before)
self.assertTrue(core.fill(capital, 'micro30', 'sell', 1000., 3., 'sale'))
self.assertFalse(core.fill(capital, 'micro30', 'sell', 1000., 3., 'sale'))
self.assertEqual(capital['cash'], {'original': 10000., 'micro30': -2003.})
self.assertEqual(capital['fees']['micro30'], 3.)
def held(code='002979.SZ', book='original', qty=100, cost=48.296):
return {'book_id': book, 'ts_code': code, 'total_qty': qty, 'avg_cost': cost}

View File

@ -86,6 +86,38 @@ class BookingTests(unittest.TestCase):
self.assertFalse(rotation_execution.book_trade(self.act, [], 1))
self.assertEqual(self.state(), before)
def test_ws_sale_books_cash_and_position_even_if_strategy_stays_negative(self):
with self.engine.begin() as conn:
conn.execute(text('ALTER TABLE pms_instruction ADD COLUMN action TEXT'))
conn.execute(text("UPDATE pms_instruction SET book_id='micro30',side='sell',action='EXIT',status='DISPATCHED'"))
conn.execute(text("INSERT INTO pms_position(book_id,ts_code,status,total_qty,avail_qty) "
"VALUES('micro30','600000.SH','HOLDING',100,100)"))
conn.execute(text("INSERT INTO pms_lot(book_id,ts_code,lot_type,qty,open_price,open_date,closed_qty,realized_pnl,status) "
"VALUES('micro30','600000.SH','BASE',100,12,'2026-11-19',0,0,'OPEN')"))
with rotation_repo.locked('capital:live', 'capital', {}) as capital:
capital['cash']['micro30'] = -3000.
payload = dict(self.act['source_payload'], ts_code='600000.SH', side='sell', amount=1000.)
event = {'msg_type': 'trade', 'seq': 1, 'payload': payload}
channel = ledger_service.qmt_repo
with (patch.object(channel, 'inbox_pending', return_value=[event]),
patch.object(channel, 'get_order', return_value={'parent_id': 'P'})):
report = json.loads(json.dumps(ledger_service.consume_ws_trades()))
self.assertTrue(report['ok'], report)
self.assertEqual((report['trades'], report['actions']), (1, 1))
booked = self.state()
duplicate = ledger_service.consume_ws_trades()
self.assertTrue(duplicate['ok'], duplicate)
self.assertEqual(duplicate['actions'], 0)
self.assertEqual(self.state(), booked)
self.assertEqual(booked['positions'][0]['total_qty'], 0)
self.assertEqual((booked['lots'][0]['qty'], booked['lots'][0]['closed_qty']), (0, 100))
self.assertEqual((booked['parents'][0]['status'], booked['parents'][0]['exec_qty']), ('CONFIRMED', 100))
self.assertEqual(booked['inbox'][0]['processed'], 1)
capital, _ = rotation_repo.get('capital:live')
self.assertEqual(capital['cash'], {'original': 10000., 'micro30': -2000.})
self.assertEqual(capital['fills']['1'], {'book': 'micro30', 'side': 'sell', 'amount': 1000., 'fee': 0.})
self.assertEqual(capital['transfers'], {})
def test_verified_overfill_preserves_approval_and_rolls_back_failed_audit(self):
with self.engine.begin() as conn:
conn.execute(text("UPDATE pms_instruction SET book_id='micro30',status='CONFIRMED',exec_qty=qty"))