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 = '{}×tamp={}&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检查什么时候水上金叉和水下死叉
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...