-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
410 lines (345 loc) · 14.3 KB
/
Copy pathcontroller.py
File metadata and controls
410 lines (345 loc) · 14.3 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
"""
controller.py
-------------
Main agent loop for the Momentum Flip trading strategy.
Orchestrates:
1. DataFeed → live candle data.
2. Strategy → momentum flip signal evaluation.
3. Risk → pre-trade risk gate.
4. Execution → order placement.
5. Logger → structured event logging.
Lifecycle:
- start() → seeds data, starts WebSocket, enters main loop.
- stop() → gracefully shuts down all components.
- The loop runs every POLL_INTERVAL_SECONDS seconds.
"""
import time
import signal
import uuid
import logging
from datetime import datetime, timezone
from typing import Optional
from config import Config
from data_feed import DataFeed
from strategy_flip import MomentumFlipStrategy, Direction, SignalResult
from risk import RiskManager
from execution import ExecutionEngine
from logging_agent import AgentLogger
logger = logging.getLogger(__name__)
class ActiveTrade:
"""Tracks a single open trade's lifecycle."""
def __init__(
self,
trade_id: str,
direction: Direction,
entry_price: float,
size_contracts: float,
sl_price: float,
tp_price: float,
):
self.trade_id = trade_id
self.direction = direction
self.entry_price = entry_price
self.size_contracts = size_contracts
self.sl_price = sl_price
self.tp_price = tp_price
self.opened_at = datetime.now(timezone.utc)
self.sl_order_id: Optional[str] = None
self.tp_order_id: Optional[str] = None
class MomentumFlipController:
"""
Main controller for the Momentum Flip agent.
Runs the strategy loop and manages trade lifecycle.
"""
def __init__(self, config: Config):
self.config = config
self.agent_logger = AgentLogger(config)
self.data_feed = DataFeed(config)
self.strategy = MomentumFlipStrategy(config)
self.risk = RiskManager(config)
self.execution = ExecutionEngine(config, data_feed=self.data_feed)
self._running = False
self._active_trades: dict[str, ActiveTrade] = {}
self._loop_count = 0
# Register OS signal handlers for graceful shutdown
signal.signal(signal.SIGINT, self._handle_shutdown)
signal.signal(signal.SIGTERM, self._handle_shutdown)
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
def start(self) -> None:
"""Start the agent: initialize components and enter main loop."""
self.agent_logger.log_system("AGENT_START", {
"symbol": self.config.SYMBOL,
"dry_run": self.config.DRY_RUN,
"primary_tf": self.config.PRIMARY_TF,
"filter_tf": self.config.FILTER_TF,
"entry_tf": self.config.ENTRY_TF,
})
logger.info("=" * 60)
logger.info(" Momentum Flip Agent — Starting")
logger.info(f" Symbol: {self.config.SYMBOL}")
logger.info(f" Mode: {'DRY RUN' if self.config.DRY_RUN else 'LIVE'}")
logger.info(f" TFs: {self.config.ENTRY_TF}m / {self.config.PRIMARY_TF}m / {self.config.FILTER_TF}m")
logger.info("=" * 60)
# Set leverage
self.execution.set_leverage(self.config.LEVERAGE)
# Start data feed (REST seed + WebSocket)
self.data_feed.start()
# Wait for buffers to populate
logger.info("[Controller] Waiting 3s for candle buffers to populate...")
time.sleep(3)
self._running = True
self._main_loop()
def stop(self) -> None:
"""Gracefully stop the agent."""
logger.info("[Controller] Stopping agent...")
self._running = False
self.data_feed.stop()
self.agent_logger.log_system("AGENT_STOP", {
"active_trades": len(self._active_trades),
"loop_count": self._loop_count,
})
logger.info("[Controller] Agent stopped.")
def _handle_shutdown(self, signum, frame) -> None:
"""Handle SIGINT/SIGTERM for graceful shutdown."""
logger.warning(f"[Controller] Received signal {signum} — initiating graceful shutdown.")
self.stop()
# ------------------------------------------------------------------
# Main Loop
# ------------------------------------------------------------------
def _main_loop(self) -> None:
"""
Core agent loop. Runs every POLL_INTERVAL_SECONDS.
Each iteration:
1. Fetch current candles.
2. Evaluate strategy signal.
3. Check risk.
4. Execute trade if approved.
5. Monitor active trades.
"""
logger.info("[Controller] Main loop started.")
while self._running:
loop_start = time.time()
self._loop_count += 1
try:
self._tick()
except Exception as e:
self.agent_logger.log_error("Main loop tick", e)
logger.error(f"[Controller] Unhandled error in tick #{self._loop_count}: {e}")
# Sleep for remainder of poll interval
elapsed = time.time() - loop_start
sleep_time = max(0, self.config.POLL_INTERVAL_SECONDS - elapsed)
time.sleep(sleep_time)
logger.info("[Controller] Main loop exited.")
def _tick(self) -> None:
"""Single iteration of the main loop."""
# 1. Get candle data for all timeframes
primary_df = self.data_feed.get_candles(self.config.PRIMARY_TF)
filter_df = self.data_feed.get_candles(self.config.FILTER_TF)
entry_df = self.data_feed.get_candles(self.config.ENTRY_TF)
if primary_df.empty or filter_df.empty:
logger.debug(f"[Controller] Tick #{self._loop_count}: Candle data not ready yet.")
return
# 2. Evaluate strategy signal
signal = self.strategy.evaluate(primary_df, filter_df, entry_df)
self.agent_logger.log_signal(signal)
# Heartbeat: show current state every tick so terminal isn't silent
current_price = self.data_feed.get_latest_price()
logger.info(
f"[Tick #{self._loop_count}] "
f"BTC=${current_price:,.2f} | "
f"Signal={signal.direction.value} | "
f"RSI={signal.rsi_value:.1f} | "
f"MACD_H={signal.macd_histogram:.4f} | "
f"Confidence={signal.confidence}"
)
# 3. Update risk manager with current position count
open_count = self.execution.get_open_position_count()
self.risk.set_open_positions(open_count)
# 4. If signal is actionable, run risk check and execute
if signal.is_actionable():
account_equity = self.execution.get_account_equity()
risk_result = self.risk.check(signal, account_equity)
self.agent_logger.log_risk_check(risk_result, signal)
if risk_result.approved:
self._execute_trade(signal, risk_result)
# 5. Monitor active trades for SL/TP hits
self._monitor_active_trades()
# 6. Log periodic stats every 60 ticks
if self._loop_count % 60 == 0:
self.agent_logger.log_daily_stats(self.risk.get_status())
# ------------------------------------------------------------------
# Trade Monitoring
# ------------------------------------------------------------------
def _monitor_active_trades(self) -> None:
"""
Check each active trade against the current market price.
Close the trade if SL or TP has been breached.
Called every tick so exits are detected promptly.
"""
if not self._active_trades:
return
current_price = self.data_feed.get_latest_price()
if current_price is None:
return
closed_ids = []
for trade_id, trade in self._active_trades.items():
reason = None
if trade.direction == Direction.LONG:
if current_price <= trade.sl_price:
reason = "STOP_LOSS"
elif current_price >= trade.tp_price:
reason = "TAKE_PROFIT"
else: # SHORT
if current_price >= trade.sl_price:
reason = "STOP_LOSS"
elif current_price <= trade.tp_price:
reason = "TAKE_PROFIT"
if reason:
logger.info(
f"[Controller] {reason} hit for {trade_id} "
f"@ ${current_price:,.4f} (SL={trade.sl_price} TP={trade.tp_price})"
)
closed_ids.append((trade_id, current_price, reason))
for trade_id, exit_price, reason in closed_ids:
self.close_trade(trade_id, exit_price, reason)
# ------------------------------------------------------------------
# Trade Execution
# ------------------------------------------------------------------
def _execute_trade(self, signal: SignalResult, risk_result) -> None:
"""
Execute a full trade: market entry + SL + TP orders.
"""
trade_id = f"MF-{uuid.uuid4().hex[:8].upper()}"
logger.info(f"[Controller] Executing trade {trade_id}: {signal.direction.value}")
# 1. Place market entry order
entry_result = self.execution.place_market_order(
direction=signal.direction,
size_contracts=risk_result.position_size_contracts,
)
self.agent_logger.log_order(
order_type="MARKET_ENTRY",
direction=signal.direction.value,
size=risk_result.position_size_contracts,
price=entry_result.filled_price,
success=entry_result.success,
order_id=entry_result.order_id,
error=entry_result.error,
)
if not entry_result.success:
logger.error(f"[Controller] Entry order failed for {trade_id}: {entry_result.error}")
return
actual_entry = entry_result.filled_price or signal.entry_price
# 2. Place stop-loss
sl_result = self.execution.place_stop_loss(
direction=signal.direction,
size_contracts=risk_result.position_size_contracts,
stop_price=risk_result.adjusted_sl,
)
self.agent_logger.log_order(
order_type="STOP_LOSS",
direction=signal.direction.value,
size=risk_result.position_size_contracts,
price=risk_result.adjusted_sl,
success=sl_result.success,
order_id=sl_result.order_id,
error=sl_result.error,
)
# 3. Place take-profit
tp_result = self.execution.place_take_profit(
direction=signal.direction,
size_contracts=risk_result.position_size_contracts,
tp_price=risk_result.adjusted_tp,
)
self.agent_logger.log_order(
order_type="TAKE_PROFIT",
direction=signal.direction.value,
size=risk_result.position_size_contracts,
price=risk_result.adjusted_tp,
success=tp_result.success,
order_id=tp_result.order_id,
error=tp_result.error,
)
# 4. Register active trade
trade = ActiveTrade(
trade_id=trade_id,
direction=signal.direction,
entry_price=actual_entry,
size_contracts=risk_result.position_size_contracts,
sl_price=risk_result.adjusted_sl,
tp_price=risk_result.adjusted_tp,
)
trade.sl_order_id = sl_result.order_id
trade.tp_order_id = tp_result.order_id
self._active_trades[trade_id] = trade
self.agent_logger.log_trade_open(
trade_id=trade_id,
direction=signal.direction.value,
symbol=self.config.SYMBOL,
entry_price=actual_entry,
size=risk_result.position_size_contracts,
sl=risk_result.adjusted_sl,
tp=risk_result.adjusted_tp,
)
def close_trade(self, trade_id: str, exit_price: float, reason: str) -> None:
"""
Close a tracked trade and record PnL.
Called externally (e.g., from MCP server or monitoring loop).
"""
trade = self._active_trades.get(trade_id)
if not trade:
logger.warning(f"[Controller] Trade {trade_id} not found in active trades.")
return
# Calculate PnL
if trade.direction == Direction.LONG:
pnl = (exit_price - trade.entry_price) * trade.size_contracts
else:
pnl = (trade.entry_price - exit_price) * trade.size_contracts
self.risk.record_trade_result(pnl)
self.agent_logger.log_trade_close(
trade_id=trade_id,
direction=trade.direction.value,
symbol=self.config.SYMBOL,
entry_price=trade.entry_price,
exit_price=exit_price,
size=trade.size_contracts,
pnl=pnl,
close_reason=reason,
)
del self._active_trades[trade_id]
# ------------------------------------------------------------------
# Status
# ------------------------------------------------------------------
def get_status(self) -> dict:
"""Return current agent status for MCP server queries."""
return {
"running": self._running,
"symbol": self.config.SYMBOL,
"dry_run": self.config.DRY_RUN,
"loop_count": self._loop_count,
"active_trades": len(self._active_trades),
"active_trade_ids": list(self._active_trades.keys()),
"risk": self.risk.get_status(),
"last_signal": (
{
"direction": self.strategy.get_last_signal().direction.value,
"confidence": self.strategy.get_last_signal().confidence,
"timestamp": str(self.strategy.get_last_signal().timestamp),
}
if self.strategy.get_last_signal()
else None
),
}
# ------------------------------------------------------------------
# Entry Point
# ------------------------------------------------------------------
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.INFO)
config = Config.from_env()
controller = MomentumFlipController(config)
try:
controller.start()
except KeyboardInterrupt:
controller.stop()