Coverage for src/copytrading_engine/shared/symbols.py: 98%
33 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""What a symbol names: a US stock or ETF ("NVDA", "BRK.B"), or a coin's US dollar pair ("BTC/USD").
3One spelling per instrument runs through the engine. A coin is always its pair, as Alpaca takes it
4in orders and quotes; Alpaca writes a coin it holds without the slash ("BTCUSD"), and its adapter
5turns that back into the pair (ADR-0014).
6"""
8import re
9from typing import Final
11STOCK_PATTERN: Final = r"[A-Z]{1,5}(?:[.][A-Z])?"
12CRYPTO_PATTERN: Final = r"[A-Z]{2,10}/USD"
13SYMBOL_PATTERN: Final = rf"^(?:{STOCK_PATTERN}|{CRYPTO_PATTERN})$"
14QUOTE_CURRENCY: Final = "USD"
16# The coins Alpaca trades against the US dollar, and the names a post may call them by. Stablecoins
17# are left out: there is nothing to copy in a dollar bought with dollars.
18_COINS: Final[dict[str, tuple[str, ...]]] = {
19 "AAVE": ("aave",),
20 "ADA": ("cardano", "艾达币"),
21 "ARB": ("arbitrum",),
22 "AVAX": ("avalanche",),
23 "BAT": ("basic attention token",),
24 "BCH": ("bitcoin cash", "比特币现金"),
25 "BONK": ("bonk",),
26 "BTC": ("bitcoin", "比特币", "大饼"),
27 "CRV": ("curve dao",),
28 "DOGE": ("dogecoin", "狗狗币"),
29 "DOT": ("polkadot", "波卡"),
30 "ETH": ("ethereum", "ether", "以太坊", "以太币", "二饼"),
31 "FIL": ("filecoin",),
32 "GRT": ("the graph",),
33 "HYPE": ("hyperliquid",),
34 "LDO": ("lido dao",),
35 "LINK": ("chainlink",),
36 "LTC": ("litecoin", "莱特币"),
37 "ONDO": ("ondo",),
38 "PAXG": ("pax gold",),
39 "PEPE": ("pepe",),
40 "POL": ("polygon",),
41 "RENDER": ("render token",),
42 "SHIB": ("shiba inu", "柴犬币"),
43 "SKY": ("sky protocol",),
44 "SOL": ("solana", "索拉纳"),
45 "SUSHI": ("sushiswap",),
46 "TRUMP": ("trump coin", "川普币"),
47 "UNI": ("uniswap",),
48 "WIF": ("dogwifhat",),
49 "XRP": ("ripple", "瑞波币"),
50 "XTZ": ("tezos",),
51 "YFI": ("yearn finance",),
52}
53_NAMES: Final = {name.casefold(): coin for coin, names in _COINS.items() for name in names}
54# A coin written as a pair: BTC/USD, BTC-USD, BTCUSD, and the stablecoin quotes a guru may write.
55_PAIR: Final = re.compile(r"([A-Z]{2,10}?)[/-]?(?:USDT|USDC|USD)")
58def is_crypto(symbol: str) -> bool:
59 """Whether the symbol is a coin's pair rather than a stock."""
60 return "/" in symbol
63def coin(symbol: str) -> str:
64 """The coin a pair trades, "BTC" of "BTC/USD"."""
65 return symbol.split("/", 1)[0]
68def crypto_pair(words: str) -> str | None:
69 """The pair the post's words name, or None when they name no coin Alpaca trades: the coin's
70 ticker (BTC, $btc), its pair however written (BTC/USD, btc-usd, BTCUSD), or its name (bitcoin,
71 比特币)."""
72 text = words.strip().lstrip("$#").strip()
73 named = _NAMES.get(text.casefold())
74 if named is not None:
75 return f"{named}/{QUOTE_CURRENCY}"
76 upper = text.upper()
77 if upper in _COINS:
78 return f"{upper}/{QUOTE_CURRENCY}"
79 match = _PAIR.fullmatch(upper)
80 if match is not None and match.group(1) in _COINS:
81 return f"{match.group(1)}/{QUOTE_CURRENCY}"
82 return None
85def held_symbol(symbol: str, asset_class: str) -> str:
86 """The pair for a coin Alpaca lists as held ("BTCUSD" is "BTC/USD"); a stock is unchanged."""
87 if asset_class != "crypto" or is_crypto(symbol):
88 return symbol
89 if not symbol.endswith(QUOTE_CURRENCY) or len(symbol) <= len(QUOTE_CURRENCY):
90 return symbol
91 return f"{symbol[: -len(QUOTE_CURRENCY)]}/{QUOTE_CURRENCY}"
94def path_symbol(symbol: str) -> str:
95 """The symbol as an Alpaca URL path takes it: a pair without its slash."""
96 return symbol.replace("/", "")