在数字时代的浪潮中,加密货币已经成为了许多人关注的焦点。无论是投资新手还是资深玩家,大家最关心的问题之一就是价格波动。今天,我就来给大家分享一个超实用的小工具——一个用Python编写的加密货币价格提醒系统。它能帮你实时监控加密货币的价格,并在价格达到你设定的阈值时发送邮件提醒。听起来是不是很贴心?别急,接下来我将带你一步步了解它的奥秘。
首先,我们来看看这个代码的核心部分。这个脚本主要通过调用Binance的API获取加密货币的实时价格,并根据用户设定的条件发送邮件提醒。
def send_mail():
server = smtplib.SMTP(mail_server, mail_port) # 创建SMTP服务器连接
server.ehlo() # 向服务器发送SMTP "ehlo" 命令
server.starttls() # 启用TLS加密
server.ehlo() # 再次发送 "ehlo" 命令
server.login(from_email, from_email_password) # 登录邮箱
subject = f"{spot_name.upper()} EXCHANGE RATE" # 邮件主题
if cpolarity == 1: # 根据用户选择的条件生成邮件内容
body = f"{spot_name.upper()} Exchange is now above ${trig_point}: Current Exchange Rate: ${lprice}."
else:
body = f"{spot_name.upper()} Exchange is now below ${trig_point}: Current Exchange Rate: ${lprice}."
msg = f'''Subject: {subject}\n
To: {"".join(to_email)}\n
{body}''' # 构造邮件内容
server.sendmail(from_email, to_email, msg.encode("utf8")) # 发送邮件
print("Alert! The E-mail has been sent!")
server.quit() # 关闭服务器连接
这段代码定义了一个send_mail
函数,用于发送邮件提醒。它首先创建一个SMTP服务器连接,然后登录邮箱,构造邮件内容,并发送邮件。邮件的主题和内容根据用户设定的条件动态生成。
while True:
Url = "https://api.binance.com/api/v3/ticker/24hr" # Binance API地址
r = requests.get(Url) # 发起GET请求
json_list = r.json() # 获取JSON格式的响应数据
cryptoname = {}
lprice = 0
for i in range(len(json_list)): # 遍历API返回的数据
if json_list[i]["symbol"] == spot_name.upper(): # 查找用户指定的加密货币
cryptoname = json_list[i]
try:
lprice = float(cryptoname["lastPrice"][4:6]) # 获取最新的价格
print(lprice)
except ValueError:
print("This Exchange is not available.") # 如果找不到该货币,打印错误信息
if lprice >= trig_point and cpolarity == 1: # 如果价格高于阈值且用户选择的是“高于”
send_mail()
exit()
if lprice <= trig_point and cpolarity == 2: # 如果价格低于阈值且用户选择的是“低于”
send_mail()
exit()
这段代码是整个脚本的核心逻辑。它通过一个无限循环不断检查加密货币的最新价格。每次循环都会调用Binance的API获取数据,然后在数据中查找用户指定的加密货币。如果价格达到用户设定的阈值,就会调用send_mail
函数发送邮件提醒。
这个脚本的应用场景非常实用。想象一下,你正在关注某种加密货币的价格,但又不想一直盯着屏幕。这个脚本就能帮你实时监控价格,并在价格达到你设定的阈值时发送邮件提醒。这样一来,你就可以在第一时间做出反应,无论是买入还是卖出。
我们可以对代码进行扩展,让它同时监控多种加密货币的价格。例如,你可以同时设置多个货币的价格阈值,并在任何一个货币达到阈值时发送提醒。
def check_prices():
currencies = {
"BTCUSDT": {"cpolarity": 1, "trig_point": 50000},
"ETHUSDT": {"cpolarity": 2, "trig_point": 3000},
"LTCUSDT": {"cpolarity": 1, "trig_point": 200}
}
while True:
Url = "https://api.binance.com/api/v3/ticker/24hr"
r = requests.get(Url)
json_list = r.json()
for currency, settings in currencies.items():
for i in range(len(json_list)):
if json_list[i]["symbol"] == currency:
lprice = float(json_list[i]["lastPrice"])
if (lprice >= settings["trig_point"] and settings["cpolarity"] == 1) or \
(lprice <= settings["trig_point"] and settings["cpolarity"] == 2):
send_mail(currency, lprice, settings["cpolarity"], settings["trig_point"])
exit()
这个函数可以同时监控多个货币的价格,并根据每个货币的设置发送提醒。
我们还可以扩展代码,让它在价格波动超过一定百分比时发送提醒。例如,你可以设置一个阈值,当价格在短时间内波动超过这个阈值时,发送提醒。
def check_price_fluctuation():
spot_name = input("Input the crypto currency to get alerts (eg. BTCUSDT): ")
fluctuation_threshold = float(input("Input the fluctuation threshold (in %): "))
previous_price = 0
while True:
Url = "https://api.binance.com/api/v3/ticker/24hr"
r = requests.get(Url)
json_list = r.json()
for i in range(len(json_list)):
if json_list[i]["symbol"] == spot_name.upper():
current_price = float(json_list[i]["lastPrice"])
if previous_price != 0:
fluctuation = abs((current_price - previous_price) / previous_price) * 100
if fluctuation >= fluctuation_threshold:
send_mail(spot_name, current_price, fluctuation_threshold)
exit()
previous_price = current_price
这个函数会在价格波动超过用户设定的阈值时发送提醒。
通过今天的分享,你是不是觉得用Python监控加密货币价格其实并不难?这个脚本虽然简单,但却非常实用。你可以根据自己的需求进行扩展,让它在更多的场景中发挥作用。无论是监控多种货币,还是监测价格波动,它都能帮你实现。需要完整的源码,请在评论区留言,或私信我。