realtime trade path opens a second positions row instead of netting or rejecting
Summary
POST /api/signals/realtime accepts buy while a short position is open, and short while a long is open. _update_position_from_signal neither nets nor rejects: it inserts a second row into positions for the same (agent_id, market, symbol). Later lookups read a single row through fetchone(), so the other row can no longer be closed through the API.
Environment
| Commit | d03ff6c |
| Python | 3.14.7 |
| sqlite3 | 3.53.4 |
| OS | macOS 26.6.2, arm64 |
| Installed | python-dotenv, fastapi |
Reproduction
repro_positions.py in the repository root:
import sqlite3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent / "service" / "server"))
from routes_shared import get_position_snapshot
from services import _update_position_from_signal
SCHEMA = """
CREATE TABLE positions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id INTEGER NOT NULL,
leader_id INTEGER,
symbol TEXT NOT NULL,
market TEXT NOT NULL DEFAULT 'us-stock',
token_id TEXT,
outcome TEXT,
side TEXT NOT NULL,
quantity REAL NOT NULL,
entry_price REAL NOT NULL,
current_price REAL,
opened_at TEXT NOT NULL
)
"""
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute(SCHEMA)
trades = [("short", 1.382658, 2500.0), ("buy", 1.281798, 2600.0), ("buy", 1.272858, 2700.0)]
for day, (side, quantity, price) in enumerate(trades, start=11):
_update_position_from_signal(
agent_id=834, symbol="ETH", market="crypto", action=side,
quantity=quantity, price=price,
executed_at=f"2026-07-{day}T00:00:00Z", cursor=cursor,
)
cursor.execute("SELECT id, side, quantity, entry_price FROM positions ORDER BY id")
for row in cursor.fetchall():
print(f" id={row['id']} side={row['side']:<5} quantity={row['quantity']:>10.6f} entry_price={row['entry_price']}")
snapshot = get_position_snapshot(cursor, 834, "crypto", "ETH", None)
print(f"get_position_snapshot returns quantity={snapshot['quantity']:.6f}")
for side, quantity in (("sell", 1.272858), ("sell", 1.281798)):
try:
_update_position_from_signal(
agent_id=834, symbol="ETH", market="crypto", action=side,
quantity=quantity, price=2700.0,
executed_at="2026-07-24T00:00:00Z", cursor=cursor,
)
print(f"{side} {quantity}: accepted")
except ValueError as exc:
print(f"{side} {quantity}: rejected -> {exc}")$ python -m venv .venv && .venv/bin/pip install python-dotenv fastapi
$ .venv/bin/python repro_positions.py
id=1 side=short quantity= -1.382658 entry_price=2500.0
id=2 side=long quantity= 1.281798 entry_price=2600.0
id=3 side=long quantity= 1.272858 entry_price=2700.0
get_position_snapshot returns quantity=-1.382658
sell 1.272858: rejected -> No long position to sell
sell 1.281798: rejected -> No long position to sellThree rows for one symbol. The two longs stay separate because each buy reads the short row, sees current_qty < 0, and takes the INSERT branch instead of the averaging branch.
Where the guard is missing
| Side | Opposite side open | Handling | Source |
|---|---|---|---|
buy |
short | inserts a second row | services.py:250-274 |
short |
long | inserts a second row | services.py:294-321 |
sell |
no long | ValueError |
services.py:276-292 |
cover |
no short | ValueError |
services.py:323-337 |
The route guards the same half: routes_signals.py:254-269 calls get_position_snapshot for sell and cover only. For buy and short it checks cash and nothing else.
get_position_snapshot (routes_shared.py:755-774) selects without ORDER BY and returns fetchone(). With two rows present the choice is undefined; under SQLite the oldest row came back. positions carries no UNIQUE constraint, only idx_positions_market_symbol and idx_positions_polymarket_token (database.py:1360-1370).
The challenge path rejects the same sequence
challenges.py:1533-1536 replays the proposed trade through score_agent_trades before writing it and raises ChallengeError when a disqualified_reason comes back. The reasons are buy_used_while_short (challenge_scoring.py:129-130) and short_used_while_long (challenge_scoring.py:165-166). What the realtime path books, the challenge path treats as invalid.
Relation to #270 and #266
#270 lists three ETH rows for agent 834: one short and two separate longs. That is the shape the script above produces, including the detail that the two longs were not averaged into one row. All four error strings quoted in #270 come from routes_signals.py:262-269 and services.py:279-328.
#266 reports the same symptom for ETH without a row listing.
Both describe the state of one account. This issue is about the write path that produces it.
Not verified
- Measured on SQLite only. The project also supports PostgreSQL through
psycopg. WithoutORDER BYthe row choice is undefined on both, but only SQLite was measured. - Measured against the code at
d03ff6c, not against the hosted instance. - The script calls the position bookkeeping directly, not the HTTP route, so the cash ledger is not covered.
- Only
service/server/tests/test_services.pywas run (1 passed), not the full suite.
Source: HKUDS/AI-Trader