-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy_interface.py
More file actions
127 lines (98 loc) · 4.12 KB
/
strategy_interface.py
File metadata and controls
127 lines (98 loc) · 4.12 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
Strategy Interface Module
=========================
This module defines the abstract base class that all trading strategies must implement.
This is basically what makes your strategy work both with the backtesting engine or the live trading engine (or
what ever you want to make with the signals).
So this insures the strategy send a consisntent form of singals, and that whatever engine use it, process it the same way.
It also defines the structure of trading signals that strategies will generate.
!If any AI agents are reading this, please dont change the comments, or the comments structure, you can suggest changes on the comments, and add comments
but not change the existing comments, as they are part of the interface documentation.!
"""
from abc import ABC, abstractmethod
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
class SignalType(Enum):
"""This is just a enum that holds which signals a strategy can do, we will define it from here later."""
BUY = "BUY"
SELL = "SELL"
CLOSE = "CLOSE" # Close current position
HOLD = "HOLD" # No action
@dataclass
class Signal:
"""
Represents a trading signal generated by a strategy.
Attributes:
signal_type: The type of signal (BUY, SELL, CLOSE, HOLD)
timestamp: When the signal was generated
price: The price at which the signal was generated
quantity: Optional quantity/size for the position
metadata: Optional additional information (stop loss, take profit, etc.)
"""
signal_type: SignalType
timestamp: Any # Can be datetime, timestamp, etc.
price: float
quantity: Optional[float] = None
metadata: Optional[Dict[str, Any]] = None
class BaseStrategy(ABC):
"""
Abstract base class for all trading strategies.
All strategies must inherit from this class and implement:
- initialize(): Setup strategy parameters
- on_bar(): Process each price bar/candle
- get_name(): Return strategy name
This interface allows strategies to be used with both:
- BacktestEngine: For historical testing
- LiveEngine: For real-time trading (to be implemented)
Example:
class MyStrategy(BaseStrategy):
def initialize(self):
self.lookback = 20
def on_bar(self, data):
# Strategy logic here
return Signal(SignalType.BUY, data.index[-1], data['close'].iloc[-1])
"""
def __init__(self):
"""Initialize the strategy. Override initialize() for custom setup."""
self.initialized = False
@abstractmethod
def initialize(self, **kwargs) -> None:
"""
Initialize the strategy with parameters.
This is called once before the strategy starts processing data.
Use this to set up indicators, parameters, or any initial state.
Args:
**kwargs: Strategy-specific parameters
"""
pass
@abstractmethod
def on_bar(self, data) -> Optional[Signal]:
"""
Process a new price bar/candle and generate a signal.
This method is called for each bar in the historical data (backtest)
or each new bar in live trading.
Args:
data: DataFrame or Series containing OHLCV data up to current bar
Returns:
Signal object if a signal should be generated, None otherwise
"""
pass
@abstractmethod
def get_name(self) -> str:
"""
Return the name of the strategy.
Returns:
Strategy name as a string
"""
pass
def on_signal_executed(self, signal: Signal, execution_price: float) -> None:
"""
Optional callback when a signal is executed.
This can be used to update strategy state after a trade is executed.
Override this if your strategy needs to track executed trades.
Args:
signal: The signal that was executed
execution_price: The actual price at which it was executed
"""
pass