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
| from typing import List, Dict, Optional
from datetime import datetime
import ccxt
import pandas as pd
import numpy as np
class DeFiTradingAgent:
"""DeFi交易Agent"""
def __init__(
self,
initial_capital: float,
exchanges: List[str],
llm_model: str = "gpt-4"
):
self.capital = initial_capital
self.portfolio = {} # {token: amount}
self.exchanges = {}
self.trade_history = []
# 初始化交易所连接
for exchange_name in exchanges:
if exchange_name == "uniswap":
exchange = ccxt.uniswap({
"enableRateLimit": True
})
elif exchange_name == "pancakeswap":
exchange = ccxt.pancakeswap({
"enableRateLimit": True
})
else:
exchange = ccxt.binance({
"enableRateLimit": True
})
self.exchanges[exchange_name] = exchange
# 初始化LLM
self.llm = self._init_llm(llm_model)
def _init_llm(self, model_name: str):
"""初始化LLM"""
# 实际应用中,这里应该连接到真实的LLM API
# 或运行本地模型
from transformers import AutoTokenizer, AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
return {
"model": model,
"tokenizer": tokenizer
}
def analyze_market(
self,
tokens: List[str],
timeframe: str = "1h"
) -> Dict:
"""分析市场"""
# 获取市场数据
market_data = self._fetch_market_data(tokens, timeframe)
# 技术分析
ta_analysis = self._technical_analysis(market_data)
# 使用LLM生成市场洞察
market_insight = self._generate_market_insight(
market_data,
ta_analysis
)
return {
"market_data": market_data,
"technical_analysis": ta_analysis,
"insight": market_insight
}
def _fetch_market_data(
self,
tokens: List[str],
timeframe: str
) -> Dict:
"""获取市场数据"""
data = {}
for token in tokens:
# 从各个交易所获取数据
for exchange_name, exchange in self.exchanges.items():
try:
ohlcv = exchange.fetch_ohlcv(
f"{token}/USDT",
timeframe,
limit=100
)
if token not in data:
data[token] = []
# 转换为DataFrame
df = pd.DataFrame(
ohlcv,
columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']
)
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
data[token].append(df)
break # 使用第一个成功的数据源
except Exception as e:
print(f"Error fetching data for {token}: {e}")
return data
def _technical_analysis(self, market_data: Dict) -> Dict:
"""技术分析"""
analysis = {}
for token, dfs in market_data.items():
if not dfs:
continue
df = dfs[0] # 使用第一个数据源
# 计算技术指标
df['sma_20'] = df['close'].rolling(window=20).mean()
df['sma_50'] = df['close'].rolling(window=50).mean()
df['rsi'] = self._calculate_rsi(df['close'], 14)
df['macd'] = self._calculate_macd(df['close'])
# 趋势分析
latest_close = df['close'].iloc[-1]
sma_20 = df['sma_20'].iloc[-1]
sma_50 = df['sma_50'].iloc[-1]
trend = "bullish" if latest_close > sma_20 > sma_50 else "bearish"
analysis[token] = {
"current_price": latest_close,
"sma_20": sma_20,
"sma_50": sma_50,
"rsi": df['rsi'].iloc[-1],
"trend": trend,
"support_levels": self._find_support_levels(df),
"resistance_levels": self._find_resistance_levels(df)
}
return analysis
def _calculate_rsi(self, prices: pd.Series, period: int = 14) -> pd.Series:
"""计算RSI"""
delta = prices.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def _calculate_macd(self, prices: pd.Series) -> Dict:
"""计算MACD"""
exp1 = prices.ewm(span=12, adjust=False).mean()
exp2 = prices.ewm(span=26, adjust=False).mean()
macd = exp1 - exp2
signal = macd.ewm(span=9, adjust=False).mean()
histogram = macd - signal
return {
"macd": macd.iloc[-1],
"signal": signal.iloc[-1],
"histogram": histogram.iloc[-1]
}
def _find_support_levels(self, df: pd.DataFrame) -> List[float]:
"""寻找支撑位"""
# 简化实现:使用局部最小值
from scipy.signal import argrelextrema
prices = df['close'].values
local_min = argrelextrema(prices, np.less, order=20)
support_levels = sorted(prices[local_min])
return support_levels[-5:] # 返回最近的5个支撑位
def _find_resistance_levels(self, df: pd.DataFrame) -> List[float]:
"""寻找阻力位"""
from scipy.signal import argrelextrema
prices = df['close'].values
local_max = argrelextrema(prices, np.greater, order=20)
resistance_levels = sorted(prices[local_max], reverse=True)
return resistance_levels[-5:] # 返回最近的5个阻力位
def _generate_market_insight(
self,
market_data: Dict,
ta_analysis: Dict
) -> str:
"""生成市场洞察"""
# 准备prompt
prompt = f"""
Analyze the following cryptocurrency market data and provide trading insights:
Technical Analysis:
{json.dumps(ta_analysis, indent=2)}
Based on this analysis, provide:
1. Market trend analysis
2. Key support and resistance levels
3. Trading recommendations
4. Risk factors to consider
5. Optimal entry and exit points
Be specific and actionable.
"""
# 调用LLM
response = self._generate(prompt)
return response
def execute_trade(
self,
exchange: str,
symbol: str,
side: str,
amount: float,
price: Optional[float] = None
) -> Dict:
"""执行交易"""
exchange_obj = self.exchanges[exchange]
try:
if side == "buy":
# 限价买单
if price:
order = exchange_obj.create_limit_buy_order(
symbol,
amount,
price
)
else:
# 市价买单
order = exchange_obj.create_market_buy_order(
symbol,
amount
)
else:
# 卖单
if price:
order = exchange_obj.create_limit_sell_order(
symbol,
amount,
price
)
else:
order = exchange_obj.create_market_sell_order(
symbol,
amount
)
# 记录交易
trade_record = {
"exchange": exchange,
"symbol": symbol,
"side": side,
"amount": amount,
"price": price,
"timestamp": datetime.now().isoformat(),
"status": "executed"
}
self.trade_history.append(trade_record)
return trade_record
except Exception as e:
print(f"Trade execution failed: {e}")
return {
"status": "failed",
"error": str(e)
}
def run_strategy(
self,
strategy_config: Dict
) -> List[Dict]:
"""运行交易策略"""
# 1. 分析市场
market_analysis = self.analyze_market(
strategy_config["tokens"],
strategy_config.get("timeframe", "1h")
)
# 2. 生成交易信号
signals = self._generate_trading_signals(
market_analysis,
strategy_config
)
# 3. 执行交易
executed_trades = []
for signal in signals:
if signal["action"] == "hold":
continue
trade = self.execute_trade(
exchange=signal["exchange"],
symbol=signal["symbol"],
side=signal["side"],
amount=signal["amount"],
price=signal.get("price")
)
if trade.get("status") == "executed":
executed_trades.append(trade)
return executed_trades
def _generate_trading_signals(
self,
market_analysis: Dict,
strategy_config: Dict
) -> List[Dict]:
"""生成交易信号"""
signals = []
ta_analysis = market_analysis["technical_analysis"]
for token, analysis in ta_analysis.items():
# 简单的移动平均策略
if (analysis["trend"] == "bullish" and
analysis["rsi"] < 70 and
analysis["current_price"] > analysis["sma_20"]):
signals.append({
"action": "buy",
"exchange": "uniswap",
"symbol": f"{token}/USDT",
"side": "buy",
"amount": strategy_config.get("trade_size", 100),
"reason": "Bullish trend with RSI below overbought"
})
elif (analysis["trend"] == "bearish" and
analysis["rsi"] > 30):
signals.append({
"action": "sell",
"exchange": "uniswap",
"symbol": f"{token}/USDT",
"side": "sell",
"amount": strategy_config.get("trade_size", 100),
"reason": "Bearish trend detected"
})
return signals
|