Skip to content

Commit 8e45148

Browse files
committed
Add is_valid check to OrderDetail
Can be used by the user to check the validity of an order, which is currently defined as any order with a valid price and quantity, or in cancelled state. Signed-off-by: cwasicki <[email protected]>
1 parent 63b4d20 commit 8e45148

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/frequenz/client/electricity_trading/_types.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1331,6 +1331,23 @@ def from_pb(cls, order_detail: electricity_trading_pb2.OrderDetail) -> Self:
13311331

13321332
return od
13331333

1334+
@property
1335+
def is_valid(self) -> bool:
1336+
"""Check if the order detail is valid.
1337+
1338+
Returns:
1339+
True if the order detail is valid, False otherwise.
1340+
"""
1341+
# Only cancelled orders are allowed to have missing price or quantity
1342+
if self.state_detail.state == OrderState.CANCELED:
1343+
return True
1344+
1345+
return not (
1346+
self.order.price.amount.is_nan()
1347+
or self.order.price.currency == Currency.UNSPECIFIED
1348+
or self.order.quantity.mw.is_nan()
1349+
)
1350+
13341351
def to_pb(self) -> electricity_trading_pb2.OrderDetail:
13351352
"""Convert an OrderDetail object to protobuf OrderDetail.
13361353

tests/test_types.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,19 +556,27 @@ def test_order_detail_from_pb_missing_fields() -> None:
556556
od_pb1 = electricity_trading_pb2.OrderDetail()
557557
od_pb1.CopyFrom(ORDER_DETAIL_PB)
558558
OrderDetail.from_pb(od_pb1)
559+
assert OrderDetail.from_pb(od_pb1).is_valid
559560
od_pb1.order.ClearField("price")
560561
OrderDetail.from_pb(od_pb1)
562+
# Not allowed for active orders
563+
assert not OrderDetail.from_pb(od_pb1).is_valid
561564
od_pb1.state_detail.state = electricity_trading_pb2.OrderState.ORDER_STATE_CANCELED
562565
OrderDetail.from_pb(od_pb1)
566+
# But allowed for canceled orders
567+
assert OrderDetail.from_pb(od_pb1).is_valid
563568

564569
# Missing quantity (same logic as above)
565570
od_pb2 = electricity_trading_pb2.OrderDetail()
566571
od_pb2.CopyFrom(ORDER_DETAIL_PB)
567572
OrderDetail.from_pb(od_pb2)
573+
assert OrderDetail.from_pb(od_pb2).is_valid
568574
od_pb2.order.ClearField("quantity")
569575
OrderDetail.from_pb(od_pb2)
576+
assert not OrderDetail.from_pb(od_pb2).is_valid
570577
od_pb2.state_detail.state = electricity_trading_pb2.OrderState.ORDER_STATE_CANCELED
571578
OrderDetail.from_pb(od_pb2)
579+
assert OrderDetail.from_pb(od_pb2).is_valid
572580

573581

574582
def test_order_detail_no_timezone_error() -> None:

0 commit comments

Comments
 (0)