[英]How can I get the new price?
您好,我正在使用 Python 進行編程,我有一個腳本可以在 Binance 上獲取比特幣的價格。 這是我的代碼:
import requests
import json
url = requests.get('https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT')
data = url.json()
print(data['price'])
但我想要一個允許在價格變化時更新的腳本。 你知道我該怎么做嗎?
非常感謝 !
不幸的是,這似乎是一個問題,例如,您無法偵聽事件,而必須“詢問”數據。
在這種情況下,你可以做一些事情,比如每隔幾分鍾詢問一次價格,如果價格發生變化就做一些事情。
import requests
import json
import time
lastPrice = 0
def priceChanged():
# Handle the price change here
print("The price changed!")
# Forever
while True:
url = requests.get('https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT')
data = url.json()
# Change the string price into a number
newPrice = float(data['price'])
# Is it different to last time?
if (newPrice != lastPrice):
lastPrice = newPrice
priceChanged()
# Wait 2 mintues
time.sleep(120)
現在可以讓幣安服務器在價格發生變化時通知您。
您擁有的唯一解決方案是實施一項可以偵聽任何更改的作業。
例如像這樣
last_price = None
try:
price_file = 'price.txt'
f = open(price_file, "r")
last_price = f.read()
except Exception as e:
# failed to read last price
pass
price_file = 'price.txt'
def get_last_price():
last_price = None
try:
f = open(price_file, "r")
last_price = f.read()
except Exception as e:
# failed to read last price
pass
return last_price
def update_price(new_price):
f = open(price_file, "w")
f.write(new_price)
f.close()
def get_biance_price():
url = requests.get('https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT')
data = url.json()
return data['price']
last_price = get_last_price()
new_price = get_biance_price()
if last_price != new_price:
print('price changed!') # implement notification
update_price(new_price)
else:
print('price is the same')
現在調用這個腳本會在'price.txt' 中保存最新的價格,如果新的價格不同,就會通知你。 現在,您可以將 scirpt 放在一些 linux cron 作業中,並將其配置為以間隔調用腳本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.