簡體   English   中英

盡管 Python 中的輸入相同,但 Function 返回不同的結果

[英]Function returning different result despite the same inputs in Python

這是我的 function,它使用 Poloniex Exchange API。 它獲取詢問(價格和金額的元組)的dict ,然后計算使用給定支出將獲得的 BTC 總量。

但是多次運行 function 會返回不同的金額,盡管要求和支出保持不變。 這個問題應該可以通過多次打印“詢問”(定義如下)和 function 結果來復制。

def findBuyAmount(spend):
    #getOrderBook
    URL = "https://poloniex.com/public?command=returnOrderBook&currencyPair=USDT_BTC&depth=20"
    #request the bids and asks (returns nested dict)
    r_ab = requests.get(url = URL) 
    # extracting data in json format -> returns a dict in this case! 
    ab_data = r_ab.json() 
    asks = ab_data.get('asks',[])
    #convert strings into decimals
    asks=[[float(elem[0]), elem[1]] for elem in asks]
    amount=0
    for elem in asks: #each elem is a tuple of price and amount
        if spend > 0:
            if elem[1]*elem[0] > spend: #check if the ask exceeds volume of our spend
                amount = amount+((elem[1]/elem[0])*spend) #BTC that would be obtained using our spend at this price
                spend = 0 #spend has been used entirely, leading to a loop break

            if elem[1]*elem[0] < spend: #check if the spend exceeds the current ask
                amount = amount + elem[1] #BTC that would be obtained using some of our spend at this price
                spend = spend - elem[1]*elem[0] #remainder

        else:
            break
    return amount

如果 asks 字典中的第一個問題是[51508.93591717, 0.62723766]並且花費是1000 ,我預計金額等於(0.62723766/51508.93591717) * 1000但我會得到各種不同的輸出。 我怎樣才能解決這個問題?

您會得到各種不同的輸出,因為每次運行 function 時都會獲取新數據。 將獲取和計算拆分為單獨的函數,以便您可以獨立測試它們。 您還可以通過正確命名變量來使邏輯更清晰:

import requests

def get_asks(url="https://poloniex.com/public?command=returnOrderBook&currencyPair=USDT_BTC&depth=20"):
    response = requests.get(url=url)
    ab_data = response.json()
    asks = ab_data.get('asks', [])
    #convert strings into decimals
    return [(float(price), qty) for price, qty in asks]

def find_buy_amount(spend, asks):
    amount = 0
    for price, qty in asks:
        if spend > 0:
            ask_value = price * qty
            if ask_value >= spend:
                amount += spend / price 
                spend = 0
            else:
                amount += qty
                spend -= ask_value    
        else:
            break
    return amount

asks = get_asks()
print("Asks:", asks)
print("Buy: ", find_buy_amount(1000, asks))

當要價超過剩余支出時,您的數學是錯誤的; 此時訂單簿上的數量無關緊要,因此您可以購買的數量只是spend / price

隨着功能的拆分,您還可以對同一個訂單簿運行任意次數的find_buy_amount ,並看到結果實際上總是相同的。

問題在於您的“我們沒有足夠的錢”路徑。 在這種情況下,您可以購買的數量並不取決於提供的數量。

            if elem[1]*elem[0] > spend:
                amount += spend/elem[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM