美文网首页
15m检查什么时候水上金叉和水下死叉

15m检查什么时候水上金叉和水下死叉

作者: 郭欢小哥 | 来源:发表于2024-08-28 10:00 被阅读0次
    
    import requests
    import pandas as pd
    import time
    from datetime import datetime, timedelta
    import hmac
    import hashlib
    import base64
    import urllib.parse
    import json
    
    def send_dingtalk_message(webhook, secret, message):
        timestamp = str(round(time.time() * 1000))
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        webhook = '{}&timestamp={}&sign={}'.format(webhook, timestamp, sign)
        headers = {'Content-Type': 'application/json'}
        data = {"msgtype": "text", "text": {"content": message}}
        response = requests.post(url=webhook, headers=headers, data=json.dumps(data))
        print(response.text)
    
    def get_klines(symbol, interval, limit=500):
        url = "https://fapi.binance.com/fapi/v1/klines"
        params = {'symbol': symbol, 'interval': interval, 'limit': limit}
        response = requests.get(url, params=params)
        return response.json()
    
    
    def calculate_macd(df, short_window=6, long_window=7, signal_window=4):
        df['EMA_short'] = df['Close'].ewm(span=short_window, adjust=False).mean()
        df['EMA_long'] = df['Close'].ewm(span=long_window, adjust=False).mean()
        df['MACD'] = df['EMA_short'] - df['EMA_long']
        df['Signal'] = df['MACD'].ewm(span=signal_window, adjust=False).mean()
        df['DIF'] = df['MACD'] - df['Signal']
        return df
    
    
    def find_macd_crosses(df):
        crosses = []
        previous_dif = df.iloc[0]['DIF']
        for i, row in df.iterrows():
            current_dif = row['DIF']
            if previous_dif <= 0 and current_dif > 0:
                crosses.append((row['Time'], '金叉上涨', current_dif))
            elif previous_dif >= 0 and current_dif < 0:
                crosses.append((row['Time'], '死叉下跌', current_dif))
            previous_dif = current_dif
        return crosses
    
    
    def convert_utc_to_local(utc_dt, offset=8):
        return utc_dt + timedelta(hours=offset)
    
    
    last_cross_time = 0  # 初始化,记录上次交叉点的时间戳
    
    def print_crosses(crosses, webhook, secret):
        global last_cross_time
        for cross in crosses:
            cross_time = cross[0] / 1000  # 获取交叉点的时间戳(秒)
            if cross_time > last_cross_time:  # 仅处理新的交叉点
                local_time = convert_utc_to_local(datetime.utcfromtimestamp(cross_time))
                time_str = local_time.strftime('%Y-%m-%d %H:%M:%S')
                message = f"穿越Time (UTC+8): {time_str}, Type: {cross[1]}, DIF: {cross[2]:.6f} 产生金叉后,等待DIF>0 在买,产生死叉后,等待DIF<0再卖。更稳妥"
                print(message)
                send_dingtalk_message(webhook, secret, message)  # 发送钉钉消息
                last_cross_time = cross_time  # 更新记录的时间戳
            else:
                print(f"No new crosses found at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} (UTC+8).")
    
    def main():
        symbol = 'BTCUSDT'
        interval = '15m'
        webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=8a6ddcf98d3b47c63333580bfe9d0bad55b17272eea05cc9c0af7f7be4de070d"
        secret = "你的秘钥"
        print("开始循环查询...")
        while True:
            klines = get_klines(symbol, interval, limit=100)
            df = pd.DataFrame(klines,
                              columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume',
                                       'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume',
                                       'Ignore'])
            df['Close'] = pd.to_numeric(df['Close'])
    
            df = calculate_macd(df)
            crosses = find_macd_crosses(df)
            if crosses:
                print_crosses(crosses, webhook_url, secret)  # 将webhook和secret传递给print_crosses函数
            else:
                print(f"No crosses found at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} (UTC+8).")
    
            time.sleep(2)  # 每分钟查询一次
    
    
    if __name__ == "__main__":
        main()
    

    相关文章

      网友评论

          本文标题:15m检查什么时候水上金叉和水下死叉

          本文链接:https://www.haomeiwen.com/subject/gvqtljtx.html