-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21_advanced_oop.py
More file actions
61 lines (49 loc) · 1.88 KB
/
Copy path21_advanced_oop.py
File metadata and controls
61 lines (49 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
21_advanced_oop.py
------------------
Concept: Advanced OOP (Inheritance, Polymorphism, Abstraction)
Context: Unified Exchange Interface (Polymorphism).
We want to write one strategy that works on BOTH Binance and Kraken
without changing the strategy code.
"""
from abc import ABC, abstractmethod
# 1. Abstract Base Class (The Blueprint)
class Exchange(ABC):
def __init__(self, api_key):
self.api_key = api_key
@abstractmethod
def connect(self):
pass
@abstractmethod
def place_order(self, symbol, qty):
pass
# 2. Concrete Implementation: Binance
class Binance(Exchange):
def connect(self):
print(f"[Binance] Connected with key {self.api_key[:4]}***")
def place_order(self, symbol, qty):
# Specific Binance API logic
print(f"[Binance] API POST /v3/order -> Buy {qty} {symbol}")
return "binance_id_123"
# 3. Concrete Implementation: Kraken
class Kraken(Exchange):
def connect(self):
print(f"[Kraken] Connected to websocket feed.")
def place_order(self, symbol, qty):
# Kraken might utilize a different parameter structure
print(f"[Kraken] API ADD_ORDER payload -> Buy {qty} {symbol}")
return "kraken_kref_999"
# 4. The Strategy Logic (Agnostic / Polymorphic)
# This function doesn't care if it's Binance or Kraken, as long as it inherits Exchange
def execute_arbitrage(exchange_obj, symbol):
print(f"\n--- Output via {type(exchange_obj).__name__} ---")
exchange_obj.connect()
order_id = exchange_obj.place_order(symbol, 1.0)
print(f"Strategy Result: Order Placed ID {order_id}")
# --- Runtime ---
if __name__ == "__main__":
b = Binance("BINANCE_KEY_XYZ")
k = Kraken("KRAKEN_KEY_ABC")
# Polymorphism in action
execute_arbitrage(b, "BTC/USDT")
execute_arbitrage(k, "BTC/usdt") # Note Kraken might allow lowercase, handled internally