发送钉钉有效的穿越事件

2024-09-01  本文已影响0人  Leoguo小哥
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
import numpy as np
import pandas as pd
from datetime import datetime

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 read_events_from_file(filename="events.txt"):
    try:
        with open(filename, "r") as file:
            return [line.strip() for line in file.readlines()]
    except FileNotFoundError:
        return []

def save_events_to_file(events, filename="events.txt"):
    with open(filename, "w") as file:
        for event in events:
            file.write(str(event) + "\n")

def get_klines(symbol, interval, limit=100):
    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_ema(prices, period):
    return pd.Series(prices).ewm(span=period, adjust=False).mean().tolist()

def calculate_macd(prices, fast_period, slow_period, signal_period):
    ema_fast = calculate_ema(prices, fast_period)
    ema_slow = calculate_ema(prices, slow_period)
    macd = np.subtract(ema_fast[-len(ema_slow):], ema_slow)
    signal = calculate_ema(macd, signal_period)
    return macd, signal

def find_crossovers(macd, signal, times, prices, ema5, ema30):
    crosses = []
    min_length = min(len(macd), len(signal))
    last_valid_time = datetime.min
    for i in range(1, min_length):
        closing_price = prices[i]
        ema5_price = ema5[i]
        ema30_price = ema30[i]
        current_time = times[i]
        cross_time = datetime.utcfromtimestamp(current_time / 1000 + 8*3600)
        time_diff = (cross_time - last_valid_time).total_seconds() / 60
        confidence_msg = ""
        if macd[i-1] < signal[i-1] and macd[i] > signal[i] and closing_price > ema5_price:
            if time_diff >= 30 or last_valid_time == datetime.min:
                if closing_price > ema5_price and closing_price > ema30_price:
                    confidence_msg = "放心做吧"
                crosses.append((i, 'Gold', cross_time.strftime('%Y-%m-%d %H:%M:%S'), '有效', confidence_msg))
                last_valid_time = cross_time
            else:
                crosses.append((i, 'Gold', cross_time.strftime('%Y-%m-%d %H:%M:%S'), '无效', ""))
        elif macd[i-1] > signal[i-1] and macd[i] < signal[i] and closing_price < ema5_price:
            if time_diff >= 30 or last_valid_time == datetime.min:
                if closing_price < ema5_price and closing_price < ema30_price:
                    confidence_msg = "放心做吧"
                crosses.append((i, 'Dead', cross_time.strftime('%Y-%m-%d %H:%M:%S'), '有效', confidence_msg))
                last_valid_time = cross_time
            else:
                crosses.append((i, 'Dead', cross_time.strftime('%Y-%m-%d %H:%M:%S'), '无效', ""))
    return crosses

def main():
    symbol = 'BTCUSDT'
    interval = '5m'
    limit = 500

    klines = get_klines(symbol, interval, limit)
    prices = [float(kline[4]) for kline in klines]
    times = [int(kline[0]) for kline in klines]

    ema5 = calculate_ema(prices, 5)
    ema30 = calculate_ema(prices, 30)

    macd, signal = calculate_macd(prices, 6, 7, 4)
    crossovers = find_crossovers(macd, signal, times, prices, ema5, ema30)

    # 这一段是新增的,用来处理事件的存储和钉钉消息发送
    existing_events = read_events_from_file("events.txt")
    new_events = [event for event in crossovers if str(event) not in existing_events]
    webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=8a6ddcf98d3b47c63333580bfe9d0bad55b17272eea05cc9c0af7f7be4de070d"
    secret = "你的秘钥"
    if new_events:
        save_events_to_file(crossovers, "events.txt")  # 保存所有当前识别的事件,而不仅仅是新事件
        for event in new_events:
            message = " 穿越".join(map(str, event))
            send_dingtalk_message(webhook_url, secret, message)  # 确保替换 YOUR_WEBHOOK_URL 和 YOUR_SECRET

if __name__ == '__main__':
    while True:
        main()
        time.sleep(5)

上一篇 下一篇

猜你喜欢

热点阅读