Skip to content

Commit 482e839

Browse files
committed
Add strategy id generation utils
1 parent da19de7 commit 482e839

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import hashlib
2+
from typing import Dict
3+
import json
4+
5+
6+
def generate_strategy_id(params: Dict, post_fix=None, pre_fix=None) -> str:
7+
"""
8+
Generate a short, consistent unique id for the given params.
9+
The id will always be the same for the same params.
10+
11+
Args:
12+
params (Dict): Strategy parameters (must be JSON serializable).
13+
You can optionally pass 'length' to control ID length.
14+
post_fix (str, optional): String to append to the end of the ID.
15+
pre_fix (str, optional): String to prepend to the start of the ID.
16+
17+
Returns:
18+
str: A deterministic unique identifier for the strategy.
19+
"""
20+
length = params.get("length", 8)
21+
22+
# Remove "length" if present so it doesn't affect the hash
23+
clean_params = {k: v for k, v in params.items() if k != "length"}
24+
25+
# Create a canonical string representation (sorted keys)
26+
params_str = json.dumps(clean_params, sort_keys=True)
27+
28+
# Hash the params string
29+
hash_digest = hashlib.sha256(params_str.encode("utf-8")).hexdigest()
30+
31+
# Return shortened hash
32+
result = hash_digest[:length]
33+
34+
if post_fix:
35+
result = result + post_fix
36+
37+
if pre_fix:
38+
result = pre_fix + result
39+
40+
return result

0 commit comments

Comments
 (0)