File size: 6,173 Bytes
be62102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Takashi Kotegawa (BNF) Pure Mathematical Quant Strategy Engine
No LLM / No Paid API Keys required.
100% Deterministic Mathematical Mean-Reversion.

Core Logic:
1. 25-Period Moving Average Disparity Rate (Kairi Index):
   Disparity = ((Price - 25_SMA) / 25_SMA) * 100%
   - Severe Oversold (e.g. <= -4.0% to -10% in crypto): High-probability Mean Reversion BUY.
   - Severe Overbought (e.g. >= +4.0% to +10%): Mean Reversion SHORT / Take Profit.
2. Volume Capitulation (Climax Volume):
   Volume >= 2.0x 20-period Average Volume (Panic Selling Bottom).
3. RSI Over-extension:
   RSI < 25 (Extreme Dip) / RSI > 75 (Extreme Pump).
4. Bollinger Band Lower Touch & ATR Volatility normalization.
"""

import numpy as np

class TakashiKotegawaQuant:
    def __init__(self, ma_period=25, min_deviation_pct=3.8, volume_mult=1.8):
        self.ma_period = ma_period
        self.min_deviation_pct = min_deviation_pct
        self.volume_mult = volume_mult
        self.name = "TAKASHI_KOTEGAWA_BNF"

    def calculate_sma(self, data, period):
        if len(data) < period:
            return np.array([])
        return np.convolve(data, np.ones(period) / period, mode='valid')

    def calculate_rsi(self, closes, period=14):
        if len(closes) <= period:
            return 50.0
        closes = np.array(closes)
        deltas = np.diff(closes)
        gains = np.where(deltas > 0, deltas, 0)
        losses = np.where(deltas < 0, -deltas, 0)
        
        avg_gain = np.mean(gains[:period])
        avg_loss = np.mean(losses[:period])
        
        for i in range(period, len(deltas)):
            avg_gain = (avg_gain * (period - 1) + gains[i]) / period
            avg_loss = (avg_loss * (period - 1) + losses[i]) / period
            
        if avg_loss == 0:
            return 100.0
        rs = avg_gain / avg_loss
        return float(100 - (100 / (1 + rs)))

    def calculate_atr(self, candles, period=14):
        if len(candles) < period + 1:
            return 0.0
        trs = []
        for i in range(1, len(candles)):
            h = candles[i]['high']
            l = candles[i]['low']
            prev_c = candles[i-1]['close']
            tr = max(h - l, abs(h - prev_c), abs(l - prev_c))
            trs.append(tr)
        return float(np.mean(trs[-period:]))

    def analyze(self, candles):
        if not candles or len(candles) < self.ma_period + 10:
            return {
                "action": "HOLD",
                "confidence": 0,
                "reason": "Accumulating historical candle data...",
                "disparity_pct": 0,
                "sma25": 0,
                "rsi": 50,
                "volume_surge": 1.0
            }

        closes = [c['close'] for c in candles]
        volumes = [c['volume'] for c in candles]
        current_price = closes[-1]
        current_volume = volumes[-1]

        # 1. 25-SMA & Disparity Rate (Kairi)
        sma25_arr = self.calculate_sma(closes, self.ma_period)
        if len(sma25_arr) == 0:
            return {"action": "HOLD", "confidence": 0, "reason": "Insufficient SMA data"}
        current_sma25 = float(sma25_arr[-1])

        # Disparity Percentage: Negative means below 25 MA (Oversold), Positive means above (Overbought)
        disparity_pct = ((current_price - current_sma25) / current_sma25) * 100.0

        # 2. Volume Capitulation Check (20-period average volume)
        recent_volumes = volumes[-21:-1] if len(volumes) >= 21 else volumes[:-1]
        avg_volume = np.mean(recent_volumes) if len(recent_volumes) > 0 else current_volume
        volume_ratio = current_volume / avg_volume if avg_volume > 0 else 1.0

        # 3. RSI
        current_rsi = self.calculate_rsi(closes, 14)
        atr = self.calculate_atr(candles, 14)

        # 4. Takashi Kotegawa Decision Logic
        action = "HOLD"
        confidence = 0
        reasons = []

        # BNF DIVERGENCE LONG (Extreme dip below 25 MA)
        if disparity_pct <= -self.min_deviation_pct:
            confidence = 60
            reasons.append(f"Price is {abs(disparity_pct):.2f}% below 25-MA (Severe Oversold)")

            if volume_ratio >= self.volume_mult:
                confidence += 20
                reasons.append(f"Volume Capitulation detected ({volume_ratio:.1f}x avg)")

            if current_rsi < 30:
                confidence += 15
                reasons.append(f"RSI extreme oversold ({current_rsi:.1f})")

            # Check if reversal candle started forming (hammer / green tick)
            if closes[-1] > candles[-1]['open']:
                confidence += 5
                reasons.append("Bullish candle rebound initiated")

            if confidence >= 70:
                action = "BUY"

        # BNF DIVERGENCE SHORT (Extreme pump above 25 MA)
        elif disparity_pct >= self.min_deviation_pct:
            confidence = 60
            reasons.append(f"Price is +{disparity_pct:.2f}% above 25-MA (Severe Overbought)")

            if current_rsi > 70:
                confidence += 20
                reasons.append(f"RSI over-extended ({current_rsi:.1f})")

            if volume_ratio >= self.volume_mult:
                confidence += 10
                reasons.append("Blow-off top climax volume")

            if confidence >= 70:
                action = "SELL"
        else:
            reasons.append(f"Disparity ({disparity_pct:.2f}%) within normal bounds (Target: ±{self.min_deviation_pct}%)")

        target_tp = current_sma25  # BNF's primary target is mean reversion to 25 MA
        stop_loss = current_price - (atr * 1.5) if action == "BUY" else current_price + (atr * 1.5)

        return {
            "strategy": "TAKASHI_BNF_25MA",
            "action": action,
            "confidence": min(confidence, 98),
            "reason": " | ".join(reasons) if reasons else "Monitoring 25-MA Disparity",
            "disparity_pct": round(disparity_pct, 2),
            "sma25": round(current_sma25, 2),
            "rsi": round(current_rsi, 1),
            "volume_ratio": round(volume_ratio, 2),
            "target_tp": round(target_tp, 2),
            "suggested_sl": round(stop_loss, 2),
            "atr": round(atr, 2)
        }