File size: 13,318 Bytes
011960a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import pandas as pd
from datetime import datetime
from typing import Dict, List, Optional, Union, Any, Tuple

from langchain.tools import tool
from modules.api_client import ArbiscanClient, GeminiClient
from modules.data_processor import DataProcessor

# Tools for Arbiscan API
class ArbiscanTools:
    def __init__(self, arbiscan_client: ArbiscanClient):
        self.client = arbiscan_client
    
    @tool("get_token_transfers")
    def get_token_transfers(self, address: str, contract_address: Optional[str] = None) -> str:
        """
        Get ERC-20 token transfers for a specific address
        
        Args:
            address: Wallet address
            contract_address: Optional token contract address to filter by
            
        Returns:
            List of token transfers as JSON string
        """
        transfers = self.client.get_token_transfers(
            address=address,
            contract_address=contract_address
        )
        return json.dumps(transfers)
    
    @tool("get_token_balance")
    def get_token_balance(self, address: str, contract_address: str) -> str:
        """
        Get the current balance of a specific token for an address
        
        Args:
            address: Wallet address
            contract_address: Token contract address
            
        Returns:
            Token balance
        """
        balance = self.client.get_token_balance(
            address=address,
            contract_address=contract_address
        )
        return balance
    
    @tool("get_normal_transactions")
    def get_normal_transactions(self, address: str) -> str:
        """
        Get normal transactions (ETH/ARB transfers) for a specific address
        
        Args:
            address: Wallet address
            
        Returns:
            List of normal transactions as JSON string
        """
        transactions = self.client.get_normal_transactions(address=address)
        return json.dumps(transactions)
    
    @tool("get_internal_transactions")
    def get_internal_transactions(self, address: str) -> str:
        """
        Get internal transactions for a specific address
        
        Args:
            address: Wallet address
            
        Returns:
            List of internal transactions as JSON string
        """
        transactions = self.client.get_internal_transactions(address=address)
        return json.dumps(transactions)
    
    @tool("fetch_whale_transactions")
    def fetch_whale_transactions(self, 
                              addresses: List[str],
                              token_address: Optional[str] = None,
                              min_token_amount: Optional[float] = None,
                              min_usd_value: Optional[float] = None) -> str:
        """
        Fetch whale transactions for a list of addresses
        
        Args:
            addresses: List of wallet addresses
            token_address: Optional token contract address to filter by
            min_token_amount: Minimum token amount
            min_usd_value: Minimum USD value
            
        Returns:
            DataFrame of whale transactions as JSON string
        """
        transactions_df = self.client.fetch_whale_transactions(
            addresses=addresses,
            token_address=token_address,
            min_token_amount=min_token_amount,
            min_usd_value=min_usd_value
        )
        return transactions_df.to_json(orient="records")


# Tools for Gemini API
class GeminiTools:
    def __init__(self, gemini_client: GeminiClient):
        self.client = gemini_client
    
    @tool("get_current_price")
    def get_current_price(self, symbol: str) -> str:
        """
        Get the current price of a token
        
        Args:
            symbol: Token symbol (e.g., "ETHUSD")
            
        Returns:
            Current price
        """
        price = self.client.get_current_price(symbol=symbol)
        return str(price) if price is not None else "Price not found"
    
    @tool("get_historical_prices")
    def get_historical_prices(self, 
                             symbol: str, 
                             start_time: str, 
                             end_time: str) -> str:
        """
        Get historical prices for a token within a time range
        
        Args:
            symbol: Token symbol (e.g., "ETHUSD")
            start_time: Start datetime in ISO format
            end_time: End datetime in ISO format
            
        Returns:
            DataFrame of historical prices as JSON string
        """
        # Parse datetime strings
        start_time_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
        end_time_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
        
        prices_df = self.client.get_historical_prices(
            symbol=symbol,
            start_time=start_time_dt,
            end_time=end_time_dt
        )
        
        if prices_df is not None:
            return prices_df.to_json(orient="records")
        else:
            return "[]"
    
    @tool("get_price_impact")
    def get_price_impact(self, 
                        symbol: str, 
                        transaction_time: str,
                        lookback_minutes: int = 5,
                        lookahead_minutes: int = 5) -> str:
        """
        Analyze the price impact before and after a transaction
        
        Args:
            symbol: Token symbol (e.g., "ETHUSD")
            transaction_time: Transaction datetime in ISO format
            lookback_minutes: Minutes to look back before the transaction
            lookahead_minutes: Minutes to look ahead after the transaction
            
        Returns:
            Price impact data as JSON string
        """
        # Parse datetime string
        transaction_time_dt = datetime.fromisoformat(transaction_time.replace('Z', '+00:00'))
        
        impact_data = self.client.get_price_impact(
            symbol=symbol,
            transaction_time=transaction_time_dt,
            lookback_minutes=lookback_minutes,
            lookahead_minutes=lookahead_minutes
        )
        
        # Convert to JSON string
        result = {
            "pre_price": impact_data["pre_price"],
            "post_price": impact_data["post_price"],
            "impact_pct": impact_data["impact_pct"]
        }
        return json.dumps(result)


# Tools for Data Processor
class DataProcessorTools:
    def __init__(self, data_processor: DataProcessor):
        self.processor = data_processor
    
    @tool("aggregate_transactions")
    def aggregate_transactions(self, 
                              transactions_json: str, 
                              time_window: str = 'D') -> str:
        """
        Aggregate transactions by time window
        
        Args:
            transactions_json: JSON string of transactions
            time_window: Time window for aggregation (e.g., 'D' for day, 'H' for hour)
            
        Returns:
            Aggregated DataFrame as JSON string
        """
        # Convert JSON to DataFrame
        transactions_df = pd.read_json(transactions_json)
        
        # Process data
        agg_df = self.processor.aggregate_transactions(
            transactions_df=transactions_df,
            time_window=time_window
        )
        
        # Convert result to JSON
        return agg_df.to_json(orient="records")
    
    @tool("identify_patterns")
    def identify_patterns(self, 
                         transactions_json: str, 
                         n_clusters: int = 3) -> str:
        """
        Identify trading patterns using clustering
        
        Args:
            transactions_json: JSON string of transactions
            n_clusters: Number of clusters for K-Means
            
        Returns:
            List of pattern dictionaries as JSON string
        """
        # Convert JSON to DataFrame
        transactions_df = pd.read_json(transactions_json)
        
        # Process data
        patterns = self.processor.identify_patterns(
            transactions_df=transactions_df,
            n_clusters=n_clusters
        )
        
        # Convert result to JSON
        result = []
        for pattern in patterns:
            # Convert non-serializable objects to serializable format
            pattern_json = {
                "name": pattern["name"],
                "description": pattern["description"],
                "cluster_id": pattern["cluster_id"],
                "occurrence_count": pattern["occurrence_count"],
                "confidence": pattern["confidence"],
                # Skip chart_data as it's not JSON serializable
                "examples": pattern["examples"].to_json(orient="records") if isinstance(pattern["examples"], pd.DataFrame) else []
            }
            result.append(pattern_json)
        
        return json.dumps(result)
    
    @tool("detect_anomalous_transactions")
    def detect_anomalous_transactions(self, 
                                     transactions_json: str, 
                                     sensitivity: str = "Medium") -> str:
        """
        Detect anomalous transactions using statistical methods
        
        Args:
            transactions_json: JSON string of transactions
            sensitivity: Detection sensitivity ("Low", "Medium", "High")
            
        Returns:
            DataFrame of anomalous transactions as JSON string
        """
        # Convert JSON to DataFrame
        transactions_df = pd.read_json(transactions_json)
        
        # Process data
        anomalies_df = self.processor.detect_anomalous_transactions(
            transactions_df=transactions_df,
            sensitivity=sensitivity
        )
        
        # Convert result to JSON
        return anomalies_df.to_json(orient="records")
    
    @tool("analyze_price_impact")
    def analyze_price_impact(self, 
                           transactions_json: str, 
                           price_data_json: str) -> str:
        """
        Analyze the price impact of transactions
        
        Args:
            transactions_json: JSON string of transactions
            price_data_json: JSON string of price impact data
            
        Returns:
            Price impact analysis as JSON string
        """
        # Convert JSON to DataFrame
        transactions_df = pd.read_json(transactions_json)
        
        # Convert price_data_json to dictionary
        price_data = json.loads(price_data_json)
        
        # Process data
        impact_analysis = self.processor.analyze_price_impact(
            transactions_df=transactions_df,
            price_data=price_data
        )
        
        # Convert result to JSON (excluding non-serializable objects)
        result = {
            "avg_impact_pct": impact_analysis.get("avg_impact_pct"),
            "max_impact_pct": impact_analysis.get("max_impact_pct"),
            "min_impact_pct": impact_analysis.get("min_impact_pct"),
            "significant_moves_count": impact_analysis.get("significant_moves_count"),
            "total_transactions": impact_analysis.get("total_transactions"),
            # Skip impact_chart as it's not JSON serializable
            "transactions_with_impact": impact_analysis.get("transactions_with_impact").to_json(orient="records") if "transactions_with_impact" in impact_analysis else []
        }
        
        return json.dumps(result)
    
    @tool("detect_wash_trading")
    def detect_wash_trading(self, 
                          transactions_json: str, 
                          addresses_json: str, 
                          sensitivity: str = "Medium") -> str:
        """
        Detect potential wash trading between addresses
        
        Args:
            transactions_json: JSON string of transactions
            addresses_json: JSON string of addresses to analyze
            sensitivity: Detection sensitivity ("Low", "Medium", "High")
            
        Returns:
            List of potential wash trading incidents as JSON string
        """
        # Convert JSON to DataFrame
        transactions_df = pd.read_json(transactions_json)
        
        # Convert addresses_json to list
        addresses = json.loads(addresses_json)
        
        # Process data
        wash_trades = self.processor.detect_wash_trading(
            transactions_df=transactions_df,
            addresses=addresses,
            sensitivity=sensitivity
        )
        
        # Convert result to JSON (excluding non-serializable objects)
        result = []
        for trade in wash_trades:
            trade_json = {
                "type": trade["type"],
                "addresses": trade["addresses"],
                "risk_level": trade["risk_level"],
                "description": trade["description"],
                "detection_time": trade["detection_time"],
                "title": trade["title"],
                "evidence": trade["evidence"].to_json(orient="records") if isinstance(trade["evidence"], pd.DataFrame) else []
                # Skip chart as it's not JSON serializable
            }
            result.append(trade_json)
        
        return json.dumps(result)