Coverage for src/copytrading_engine/execution/domain/stops.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""The guru's stops, as the account keeps them (ADR-0015). 

2 

3Alpaca takes a stock's stop only for the day, so the order that protects a buy does not outlive 

4the session. What lasts is the stop itself: the price the guru posted and the buys it protects. 

5Each regular session places it again as a stop order for what those buys still hold, until its 

6shares are gone or a newer stop for the same buy replaces it. 

7""" 

8 

9import hashlib 

10 

11from pydantic import AwareDatetime, Field 

12 

13from copytrading_engine.execution.domain.values import Identifier, Positive, Value 

14 

15 

16class StopRule(Value): 

17 """A stop the account follows: sell what `entries` (buys in the lot `lot_id`) still hold when 

18 the price falls to `stop_price`. The post that set it is its source.""" 

19 

20 key: Identifier 

21 symbol: Identifier 

22 lot_id: Identifier 

23 entries: tuple[Identifier, ...] = Field(min_length=1) 

24 stop_price: Positive 

25 message_id: Identifier 

26 # Where the stop sits among the post's orders: after its instructions (ledger_state). 

27 order_index: int = Field(ge=0) 

28 set_at: AwareDatetime 

29 

30 

31def stop_rule_key(message_key: str, stop_index: int) -> str: 

32 """One stop per post and stop, so a post that is processed twice sets it once.""" 

33 return "stop-" + hashlib.sha256(f"{message_key}:{stop_index}".encode()).hexdigest()[:40] 

34 

35 

36def stop_client_id(rule_key: str, attempt: int) -> str: 

37 """The client order ID of a stop's `attempt`-th day order: the number is hashed in, so the ID 

38 stays inside Alpaca's 48 characters however many sessions the stop outlives.""" 

39 return "stp-" + hashlib.sha256(f"{rule_key}:{attempt}".encode()).hexdigest()[:40]