File size: 8,355 Bytes
b766b4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
HFT Integration Example β€” shows how to plug the crypto predictor
into a high-frequency trading application.

Demonstrates:
  1. Loading the trained model once at startup
  2. Fast inference on each new bar (sub-ms with LightGBM)
  3. Signal β†’ order decision logic with risk management
  4. Multi-asset support (train models for each ticker)

To adapt for your exchange:
  - Replace get_live_bar() with your WebSocket feed
  - Replace execute_order() with your broker API
  - Adjust risk parameters in the SignalProcessor class
"""
import sys, os
sys.path.insert(0, os.path.dirname(__file__))

import pandas as pd
import numpy as np
from datetime import datetime
import time
from predict import CryptoPredictor
from config import cfg
import warnings
warnings.filterwarnings('ignore')


class SignalProcessor:
    """Processes ML predictions into trading signals with risk management.

    This sits between the ML model and your order execution layer.
    """

    def __init__(self, ticker="BTC-USD", model_dir=None):
        """Load trained model once at startup."""
        self.predictor = CryptoPredictor(ticker=ticker, model_dir=model_dir)
        self.position = 0          # current position: 1=long, -1=short, 0=flat
        self.entry_price = 0.0
        self.max_position = 1.0    # max position size (units)
        self.stop_loss_pct = 0.03  # 3% stop loss
        self.take_profit_pct = 0.06  # 6% take profit
        self.min_confidence = 0.60  # minimum confidence to act
        self.min_signal_agreement = 3  # min horizons agreeing for consensus

    def process_bar(self, df: pd.DataFrame, use_lstm=False) -> dict:
        """Process a new bar and return trading decision.

        Args:
            df: DataFrame with OHLCV + features already built (min 250 rows)
                In HFT: this comes from your exchange WebSocket, then build_all_features()
            use_lstm: False for HFT (sub-ms), True for higher accuracy

        Returns:
            {
                'action': 'BUY'|'SELL'|'HOLD'|'CLOSE',
                'size': float,
                'price': float,
                'reason': str,
                'signals': dict,
                'latency_ms': float,
            }
        """
        t0 = time.perf_counter()

        # Get multi-horizon predictions from the passed DataFrame directly
        result = self.predictor.get_multi_horizon_from_df(df, use_lstm=use_lstm)
        latency = (time.perf_counter() - t0) * 1000

        current_price = result['current_price']
        consensus = result['consensus']
        consensus_conf = result['consensus_confidence']
        signals = result['signals']

        # Count signal agreement
        buy_count = signals.count('BUY')
        sell_count = signals.count('SELL')

        decision = {
            'action': 'HOLD',
            'size': 0.0,
            'price': current_price,
            'reason': '',
            'signals': result['predictions'],
            'consensus': consensus,
            'consensus_confidence': consensus_conf,
            'latency_ms': latency,
        }

        # ─── Risk checks first: stop loss / take profit ───
        if self.position != 0 and self.entry_price > 0:
            pnl_pct = (current_price - self.entry_price) / self.entry_price * self.position

            if pnl_pct <= -self.stop_loss_pct:
                decision['action'] = 'CLOSE'
                decision['size'] = abs(self.position)
                decision['reason'] = f'Stop loss triggered: {pnl_pct:.2%}'
                self._reset_position()
                return decision

            if pnl_pct >= self.take_profit_pct:
                decision['action'] = 'CLOSE'
                decision['size'] = abs(self.position)
                decision['reason'] = f'Take profit triggered: {pnl_pct:.2%}'
                self._reset_position()
                return decision

        # ─── New position logic ───
        if self.position == 0:  # Only open new positions when flat
            if (consensus == 'BUY' and buy_count >= self.min_signal_agreement
                    and consensus_conf >= self.min_confidence):
                decision['action'] = 'BUY'
                decision['size'] = self.max_position
                decision['reason'] = f'{buy_count}/{len(signals)} horizons bullish, conf={consensus_conf:.0%}'
                self.position = 1
                self.entry_price = current_price

            elif (consensus == 'SELL' and sell_count >= self.min_signal_agreement
                    and consensus_conf >= self.min_confidence):
                decision['action'] = 'SELL'
                decision['size'] = self.max_position
                decision['reason'] = f'{sell_count}/{len(signals)} horizons bearish, conf={consensus_conf:.0%}'
                self.position = -1
                self.entry_price = current_price

        return decision

    def _reset_position(self):
        self.position = 0
        self.entry_price = 0.0

    def get_status(self) -> dict:
        return {
            'position': self.position,
            'entry_price': self.entry_price,
            'max_position': self.max_position,
            'stop_loss_pct': self.stop_loss_pct,
            'take_profit_pct': self.take_profit_pct,
        }


# ═══════════════════════════════════════════════════════════════
#  SIMULATED LIVE TRADING LOOP
# ═══════════════════════════════════════════════════════════════

def simulate_live_trading(ticker="BTC-USD", n_bars=10):
    """Simulate a live trading loop using historical data as 'live' feed.

    In production, replace this with your WebSocket event handler:
      websocket.on_message β†’ process_bar()
    """
    from data_loader import download
    from features import build_all_features

    print(f"\n{'#'*60}")
    print(f"# SIMULATED LIVE TRADING β€” {ticker}")
    print(f"{'#'*60}\n")

    # Initialize signal processor (loads models)
    processor = SignalProcessor(ticker=ticker)
    print(f"Position manager: {processor.get_status()}\n")

    # Get historical data to simulate live bars
    df_full = download(ticker, period="1y", interval="1d")
    df_full = build_all_features(df_full)

    print(f"Simulating {n_bars} bars...\n")
    print(f"{'Time':<12} {'Price':>10} {'Action':<8} {'Signal':<8} {'Conf':>6} {'Latency':>8} {'Reason'}")
    print(f"{'─'*80}")

    for i in range(n_bars):
        # Simulate receiving a new bar β€” feed last 250 rows up to bar i
        idx = len(df_full) - n_bars + i
        df_window = df_full.iloc[max(0, idx - 250):idx + 1]

        if len(df_window) < 250:
            continue

        # Process the bar (this is where your WebSocket handler calls)
        decision = processor.process_bar(df_window, use_lstm=False)

        bar_time = str(df_window.index[-1])[:10]
        print(f"{bar_time:<12} {decision['price']:>10,.2f} {decision['action']:<8} "
              f"{decision.get('consensus', ''):<8} {decision.get('consensus_confidence', 0):>5.0%} "
              f"{decision['latency_ms']:>6.1f}ms  {decision['reason']}")

        # In production: execute_order(decision) here
        # if decision['action'] == 'BUY':
        #     exchange.market_buy(ticker, decision['size'])
        # elif decision['action'] == 'SELL':
        #     exchange.market_sell(ticker, decision['size'])
        # elif decision['action'] == 'CLOSE':
        #     exchange.close_position(ticker)

    print(f"\n{'─'*80}")
    print(f"Final status: {processor.get_status()}")
    print(f"\nIn production:")
    print(f"  1. Replace simulate_live_trading() with your WebSocket feed")
    print(f"  2. Call processor.process_bar(df) on each new bar")
    print(f"  3. Execute orders based on decision['action']")


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="HFT Integration Example")
    parser.add_argument('--ticker', type=str, default='BTC-USD')
    parser.add_argument('--bars', type=int, default=10)
    args = parser.parse_args()
    simulate_live_trading(ticker=args.ticker, n_bars=args.bars)