|
python帮我写一个使用ccxt的交易策略。该策略实现在15分钟图中,在macd金叉的时候买入 在macd死叉的时候卖出,并打印出买入卖出时间,价格,收益
- import ccxt
- import pandas as pd
- import talib
- from datetime import datetime, timedelta
-
- # 交易平台配置
- exchange_name = 'binance' # 假设使用Binance交易所
- api_key = 'YOUR_API_KEY'
- api_secret = 'YOUR_API_SECRET'
- symbol = 'BTC/USDT' # 交易对
-
- # 初始化交易所客户端
- exchange = ccxt.binance({
- 'apiKey': api_key,
- 'secret': api_secret,
- })
-
- # 获取历史K线数据(15分钟K线)
- def fetch_ohlcv(symbol, timeframe='15m', limit=100):
- ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
- return pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
-
- # 计算MACD指标
- def calculate_macd(df, short_window=12, long_window=26, signal_window=9):
- df['macd'], df['signal'], df['hist'] = talib.MACD(df['close'], short_window, long_window, signal_window)
- return df
-
- # 判断MACD金叉或死叉
- def detect_crossover(df):
- buy_signals = ((df['hist'][-2] < 0) & (df['hist'][-1] > 0))
- sell_signals = ((df['hist'][-2] > 0) & (df['hist'][-1] < 0))
- return buy_signals, sell_signals
-
- # 交易逻辑
- def trade_logic(symbol):
- # 获取历史数据
- df = fetch_ohlcv(symbol)
-
- # 计算MACD指标
- df = calculate_macd(df)
-
- # 检测金叉和死叉
- buy_signal, sell_signal = detect_crossover(df)
-
- # 如果金叉,则买入
- if buy_signal:
- buy_price = df['close'][-1]
- print(f"Buy Signal at {datetime.fromtimestamp(df['timestamp'][-1] / 1000).strftime('%Y-%m-%d %H:%M:%S')}, Price: {buy_price}")
- # 这里应该是执行买入操作的代码,例如 exchange.create_market_buy_order(symbol, amount)
- # 注意:你需要根据实际情况调整买入的逻辑,包括买入数量、资金管理等
-
- # 如果死叉,则卖出
- if sell_signal:
- sell_price = df['close'][-1]
- print(f"Sell Signal at {datetime.fromtimestamp(df['timestamp'][-1] / 1000).strftime('%Y-%m-%d %H:%M:%S')}, Price: {sell_price}")
- # 这里应该是执行卖出操作的代码,例如 exchange.create_market_sell_order(symbol, amount)
- # 注意:你需要根据实际情况调整卖出的逻辑,包括卖出数量、止盈止损等
-
- # 计算收益(假设之前有一次买入操作)
- if 'last_buy_price' in locals():
- profit = (sell_price - last_buy_price) if sell_signal else 0
- print(f"Profit: {profit}")
-
- # 更新上次买入价格(如果有卖出操作,则重置为None)
- if buy_signal:
- last_buy_price = buy_price
- elif sell_signal:
- last_buy_price = None
-
- return last_buy_price
-
- # 运行交易逻辑
- last_buy_price = trade_logic(symbol)
复制代码
i
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|