-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging_agent.py
More file actions
263 lines (236 loc) · 8.93 KB
/
Copy pathlogging_agent.py
File metadata and controls
263 lines (236 loc) · 8.93 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""
logging_agent.py
----------------
Structured logging for the Momentum Flip trading agent.
Logs the following event types as JSON lines:
- SIGNAL → every evaluated signal (LONG/SHORT/HOLD).
- ORDER → every order placement attempt and result.
- TRADE → completed trade with entry, exit, PnL.
- RISK → risk check results and daily stats.
- SYSTEM → agent start/stop, errors, status changes.
Uses loguru for rich console output and rotating file logs.
"""
import json
import sys
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, Any
from loguru import logger as loguru_logger
from config import Config
from strategy_flip import SignalResult, Direction
from risk import RiskCheckResult
class AgentLogger:
"""
Dual-output logger:
- Console: human-readable colored output via loguru.
- File: structured JSON lines for analysis and audit.
"""
def __init__(self, config: Config):
self.config = config
self._log_path = Path(config.LOG_FILE_PATH)
self._log_path.parent.mkdir(parents=True, exist_ok=True)
self._json_log_path = self._log_path.with_suffix(".jsonl")
self._setup_loguru()
def _setup_loguru(self) -> None:
"""Configure loguru sinks: console + rotating file."""
loguru_logger.remove() # Remove default sink
# Console sink — colored, human-readable
loguru_logger.add(
sys.stdout,
level=self.config.LOG_LEVEL,
format=(
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{name}</cyan>:<cyan>{line}</cyan> — "
"<level>{message}</level>"
),
colorize=True,
)
# File sink — plain text, rotating
loguru_logger.add(
str(self._log_path),
level=self.config.LOG_LEVEL,
rotation=f"{self.config.LOG_MAX_SIZE_MB} MB",
retention=self.config.LOG_BACKUP_COUNT,
compression="zip",
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{line} — {message}",
)
loguru_logger.info(
f"[Logger] Initialized. Console + file logging active. "
f"Log path: {self._log_path}"
)
def _write_json_event(self, event_type: str, data: dict) -> None:
"""Append a JSON event line to the structured log file."""
event = {
"ts": datetime.now(timezone.utc).isoformat(),
"type": event_type,
**data,
}
try:
with open(self._json_log_path, "a") as f:
f.write(json.dumps(event) + "\n")
except OSError as e:
loguru_logger.error(f"[Logger] Failed to write JSON event: {e}")
# ------------------------------------------------------------------
# Event Loggers
# ------------------------------------------------------------------
def log_signal(self, signal: SignalResult) -> None:
"""Log a strategy signal evaluation result."""
msg = (
f"[SIGNAL] {signal.direction.value} | "
f"Entry={signal.entry_price} SL={signal.stop_loss_price} TP={signal.take_profit_price} | "
f"Confidence={signal.confidence} TrendAligned={signal.trend_aligned} | "
f"{signal.notes}"
)
if signal.direction == Direction.HOLD:
loguru_logger.debug(msg)
else:
loguru_logger.info(msg)
self._write_json_event("SIGNAL", {
"direction": signal.direction.value,
"entry_price": signal.entry_price,
"stop_loss": signal.stop_loss_price,
"take_profit": signal.take_profit_price,
"confidence": signal.confidence,
"rsi": signal.rsi_value,
"macd_histogram": signal.macd_histogram,
"macd_prev_histogram": signal.macd_prev_histogram,
"trend_aligned": signal.trend_aligned,
"timeframe": signal.timeframe,
"notes": signal.notes,
"signal_ts": signal.timestamp.isoformat() if signal.timestamp else None,
})
def log_risk_check(self, result: RiskCheckResult, signal: SignalResult) -> None:
"""Log a risk check result."""
status = "✅ APPROVED" if result.approved else "❌ REJECTED"
msg = (
f"[RISK] {status} | {result.reason} | "
f"Size=${result.position_size_usd:.2f} ({result.position_size_contracts:.6f} contracts)"
)
if result.approved:
loguru_logger.info(msg)
else:
loguru_logger.warning(msg)
self._write_json_event("RISK", {
"approved": result.approved,
"reason": result.reason,
"position_size_usd": result.position_size_usd,
"position_size_contracts": result.position_size_contracts,
"signal_direction": signal.direction.value,
"signal_confidence": signal.confidence,
})
def log_order(
self,
order_type: str,
direction: str,
size: float,
price: Optional[float],
success: bool,
order_id: Optional[str],
error: Optional[str] = None,
) -> None:
"""Log an order placement attempt."""
status = "✅" if success else "❌"
msg = (
f"[ORDER] {status} {order_type} {direction} | "
f"Size={size:.6f} Price={price} | "
f"OID={order_id} | Error={error}"
)
if success:
loguru_logger.info(msg)
else:
loguru_logger.error(msg)
self._write_json_event("ORDER", {
"order_type": order_type,
"direction": direction,
"size": size,
"price": price,
"success": success,
"order_id": order_id,
"error": error,
})
def log_trade_open(
self,
trade_id: str,
direction: str,
symbol: str,
entry_price: float,
size: float,
sl: float,
tp: float,
) -> None:
"""Log a trade opening."""
loguru_logger.success(
f"[TRADE OPEN] {trade_id} | {direction} {symbol} | "
f"Entry=${entry_price:,.4f} Size={size:.6f} | "
f"SL=${sl:,.4f} TP=${tp:,.4f}"
)
self._write_json_event("TRADE_OPEN", {
"trade_id": trade_id,
"direction": direction,
"symbol": symbol,
"entry_price": entry_price,
"size": size,
"stop_loss": sl,
"take_profit": tp,
})
def log_trade_close(
self,
trade_id: str,
direction: str,
symbol: str,
entry_price: float,
exit_price: float,
size: float,
pnl: float,
close_reason: str,
) -> None:
"""Log a trade closing with PnL."""
emoji = "🟢" if pnl > 0 else "🔴"
loguru_logger.success(
f"[TRADE CLOSE] {emoji} {trade_id} | {direction} {symbol} | "
f"Entry=${entry_price:,.4f} Exit=${exit_price:,.4f} | "
f"PnL=${pnl:,.2f} | Reason={close_reason}"
)
self._write_json_event("TRADE_CLOSE", {
"trade_id": trade_id,
"direction": direction,
"symbol": symbol,
"entry_price": entry_price,
"exit_price": exit_price,
"size": size,
"pnl": pnl,
"close_reason": close_reason,
})
def log_system(self, event: str, details: Optional[dict] = None) -> None:
"""Log a system-level event (start, stop, error, status)."""
loguru_logger.info(f"[SYSTEM] {event} | {details or {}}")
self._write_json_event("SYSTEM", {
"event": event,
"details": details or {},
})
def log_error(self, context: str, error: Exception) -> None:
"""Log an exception with context."""
loguru_logger.exception(f"[ERROR] {context}: {error}")
self._write_json_event("ERROR", {
"context": context,
"error_type": type(error).__name__,
"error_msg": str(error),
})
def log_daily_stats(self, stats: dict) -> None:
"""Log end-of-day or periodic performance stats."""
loguru_logger.info(
f"[STATS] Daily PnL=${stats.get('daily_pnl', 0):.2f} | "
f"Trades={stats.get('daily_trades', 0)} | "
f"Win Rate={stats.get('win_rate', 0):.1%} | "
f"Cap Remaining=${stats.get('cap_remaining', 0):.2f}"
)
self._write_json_event("DAILY_STATS", stats)
# ------------------------------------------------------------------
# Convenience accessor for standard Python logging integration
# ------------------------------------------------------------------
@staticmethod
def get_logger(name: str):
"""Return a loguru-compatible logger bound to a module name."""
return loguru_logger.bind(name=name)