8回答

0收藏

比特币策略实现在15分钟图中macd金叉测策略

区块链技术 区块链技术 2532 人阅读 | 8 人回复 | 2024-03-15

python帮我写一个使用ccxt的交易策略。该策略实现在15分钟图中,在macd金叉的时候买入 在macd死叉的时候卖出,并打印出买入卖出时间,价格,收益

  1. import ccxt  
  2. import pandas as pd  
  3. import talib  
  4. from datetime import datetime, timedelta  
  5.   
  6. # 交易平台配置  
  7. exchange_name = 'binance'  # 假设使用Binance交易所  
  8. api_key = 'YOUR_API_KEY'  
  9. api_secret = 'YOUR_API_SECRET'  
  10. symbol = 'BTC/USDT'  # 交易对  
  11.   
  12. # 初始化交易所客户端  
  13. exchange = ccxt.binance({  
  14.     'apiKey': api_key,  
  15.     'secret': api_secret,  
  16. })  
  17.   
  18. # 获取历史K线数据(15分钟K线)  
  19. def fetch_ohlcv(symbol, timeframe='15m', limit=100):  
  20.     ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)  
  21.     return pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])  
  22.   
  23. # 计算MACD指标  
  24. def calculate_macd(df, short_window=12, long_window=26, signal_window=9):  
  25.     df['macd'], df['signal'], df['hist'] = talib.MACD(df['close'], short_window, long_window, signal_window)  
  26.     return df  
  27.   
  28. # 判断MACD金叉或死叉  
  29. def detect_crossover(df):  
  30.     buy_signals = ((df['hist'][-2] < 0) & (df['hist'][-1] > 0))  
  31.     sell_signals = ((df['hist'][-2] > 0) & (df['hist'][-1] < 0))  
  32.     return buy_signals, sell_signals  
  33.   
  34. # 交易逻辑  
  35. def trade_logic(symbol):  
  36.     # 获取历史数据  
  37.     df = fetch_ohlcv(symbol)  
  38.       
  39.     # 计算MACD指标  
  40.     df = calculate_macd(df)  
  41.       
  42.     # 检测金叉和死叉  
  43.     buy_signal, sell_signal = detect_crossover(df)  
  44.       
  45.     # 如果金叉,则买入  
  46.     if buy_signal:  
  47.         buy_price = df['close'][-1]  
  48.         print(f"Buy Signal at {datetime.fromtimestamp(df['timestamp'][-1] / 1000).strftime('%Y-%m-%d %H:%M:%S')}, Price: {buy_price}")  
  49.         # 这里应该是执行买入操作的代码,例如 exchange.create_market_buy_order(symbol, amount)  
  50.         # 注意:你需要根据实际情况调整买入的逻辑,包括买入数量、资金管理等  
  51.          
  52.     # 如果死叉,则卖出  
  53.     if sell_signal:  
  54.         sell_price = df['close'][-1]  
  55.         print(f"Sell Signal at {datetime.fromtimestamp(df['timestamp'][-1] / 1000).strftime('%Y-%m-%d %H:%M:%S')}, Price: {sell_price}")  
  56.         # 这里应该是执行卖出操作的代码,例如 exchange.create_market_sell_order(symbol, amount)  
  57.         # 注意:你需要根据实际情况调整卖出的逻辑,包括卖出数量、止盈止损等  
  58.          
  59.     # 计算收益(假设之前有一次买入操作)  
  60.     if 'last_buy_price' in locals():  
  61.         profit = (sell_price - last_buy_price) if sell_signal else 0  
  62.         print(f"Profit: {profit}")  
  63.          
  64.     # 更新上次买入价格(如果有卖出操作,则重置为None)  
  65.     if buy_signal:  
  66.         last_buy_price = buy_price  
  67.     elif sell_signal:  
  68.         last_buy_price = None  
  69.       
  70.     return last_buy_price  
  71.   
  72. # 运行交易逻辑  
  73. last_buy_price = trade_logic(symbol)
复制代码

i

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
分享到:

回答|共 8 个

alexstrum

发表于 2024-8-23 04:12:03 | 显示全部楼层

Heads up innovators

Explore the future of gaming with Musk Empire - a revolutionary Web3 adventure! Build your business empire free of donations. Boost your ventures to multiply your earnings per hour. Play, accumulate, and in time convert in-game wealth for actual cash. Enter the Musk Empire today and craft your virtual wealth! invitation link

andreyiq

发表于 2024-8-23 04:16:04 | 显示全部楼层

Discover the future of gaming with Empire of Musk - a groundbreaking Web3 adventure! Build your business empire without in-app purchases. Enhance your ventures to multiply your earnings per hour. Play, earn, and eventually convert in-game currency for actual cash. Enter the Musk Empire today and craft your virtual wealth! join here

AndrXxX

发表于 2024-8-23 04:16:48 | 显示全部楼层

Prepared to change your digital fortune?

andreyiq ??? 2024-8-23 04:16
Discover the future of gaming with Empire of Musk - a groundbreaking Web3 adventure! Build your busi ...

Discover the future of gaming with Empire of Musk - an innovative Web3 experience! Expand your business realm without donations. Upgrade your ventures to amplify your earnings per hour. Play, accumulate, and down the line exchange in-game currency for actual cash. Enter the Musk Empire now and shape your virtual wealth! invitation link

alexstrum

发表于 2024-8-29 21:47:34 | 显示全部楼层

Excited to start your journey?

alexstrum ??? 2024-8-23 04:12
Explore the future of gaming with Musk Empire - a revolutionary Web3 adventure! Build your business  ...

Explore the future of gaming with Musk Empire - a revolutionary Web3 adventure! Grow your business empire free of donations. Boost your assets to amplify your hourly profits. Engage, accumulate, and down the line exchange in-game currency for actual cash. Enter the Empire of Musk now and shape your digital fortune! join here

andreyiq

发表于 2024-8-29 21:51:38 | 显示全部楼层

Calling all visionaries

Explore the future of gaming with Musk Empire - a groundbreaking Web3 adventure! Build your business realm with zero donations. Enhance your investments to increase your earnings per hour. Engage, accumulate, and down the line exchange in-game currency for real money. Enter the Empire of Musk today and shape your digital fortune! invitation link

AndrXxX

发表于 2024-8-29 21:52:23 | 显示全部楼层

Calling all innovators

alexstrum ??? 2024-8-23 04:12
Explore the future of gaming with Musk Empire - a revolutionary Web3 adventure! Build your business  ...

Hello, are you ready to dive into the world of business and profits? Introducing the brand-new game, Musk Empire! In Musk Empire, you get to build and grow your business empire, choosing from various upgrades that increase your hourly profits. After some time, exchange your in-game profits on a special exchange for real money. Yes, you read that right – real money you can spend however you like. And the best part? There's absolutely no in-game donation. It's all about strategy. Don't miss out and reach for the stars. Sign up today and experience the thrill of Musk Empire! join here

andreyiq

发表于 2024-8-30 11:22:21 | 显示全部楼层

SHOCKING: This Game Makes Millionaires - Elon's Trick?

alexstrum ??? 2024-8-29 21:47
Explore the future of gaming with Musk Empire - a revolutionary Web3 adventure! Grow your business ...

Explore the future of gaming with Musk Empire - a groundbreaking Web3 experience! Grow your business realm free of in-app purchases. Boost your assets to amplify your revenue stream. Engage, accumulate, and down the line exchange in-game currency for real money. Dive into the Musk Empire now and craft your digital fortune! join here

AndrXxX

发表于 2024-8-30 11:22:46 | 显示全部楼层

Play Musk Empire: Web3 Business Sim

Discover the future of gaming with Empire of Musk - an innovative Web3 adventure! Grow your business realm without donations. Upgrade your assets to amplify your hourly profits. Engage, earn, and in time convert in-game currency for actual cash. Join the Musk Empire now and shape your digital fortune! invitation link
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则