Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(alpaca): normalize enum side so the sign applies on the direct-SDK path

Haozhe Wu5e394a31c95e
diff --git a/agent/src/trading/connectors/alpaca/sdk.py b/agent/src/trading/connectors/alpaca/sdk.py
index 81ec40502..d3e7120bb 100644
--- a/agent/src/trading/connectors/alpaca/sdk.py
+++ b/agent/src/trading/connectors/alpaca/sdk.py
@@ -847,7 +847,11 @@ def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
def _position_to_dict(item: Any) -> dict[str, Any]:
- side = str(_obj_get(item, "side", ""))
+ # alpaca-py's Position.side is a (str, Enum) member whose str() is
+ # "PositionSide.SHORT", not "short" — read .value so the direct-SDK path
+ # emits the same lowercase token the TAP JSON path does.
+ side_raw = _obj_get(item, "side", "")
+ side = str(getattr(side_raw, "value", side_raw)).strip().lower()
quantity = _obj_get(item, "qty")
if side == "short" and quantity is not None:
# Alpaca reports qty as an absolute magnitude and carries direction in
diff --git a/agent/tests/test_alpaca_position_sign.py b/agent/tests/test_alpaca_position_sign.py
index 7c2c4a288..c4e813a0f 100644
--- a/agent/tests/test_alpaca_position_sign.py
+++ b/agent/tests/test_alpaca_position_sign.py
@@ -9,6 +9,7 @@ exposure toward zero. The connector now negates qty for short positions.
from __future__ import annotations
+from enum import Enum
from types import SimpleNamespace
import pytest
@@ -44,3 +45,16 @@ def test_object_positions_get_the_same_sign() -> None:
def test_gate_reads_alpaca_short_as_negative_exposure() -> None:
row = _position_to_dict({"symbol": "AAPL", "side": "short", "qty": "400", "market_value": "-50000"})
assert _position_signed_market_value(row) == -50000.0
+
+
+def test_sdk_enum_side_is_normalized_and_signed() -> None:
+ # The direct-SDK path yields alpaca-py Position objects whose side is a
+ # (str, Enum) member; str() of such a member is "PositionSide.SHORT".
+ class PositionSide(str, Enum):
+ SHORT = "short"
+
+ item = SimpleNamespace(symbol="AAPL", side=PositionSide.SHORT, qty="400", market_value="-50000")
+ row = _position_to_dict(item)
+ assert row["side"] == "short"
+ assert row["quantity"] == -400.0
+ assert _position_signed_market_value(row) == -50000.0