尽管 Python 中的输入相同,函数返回不同的结果

Function returning different result despite the same inputs in Python

这是我使用 Poloniex Exchange API 的函数。它得到一个 dict 请求(价格和金额的元组),然后计算使用给定支出将获得的 BTC 总量。

但是 运行 尽管请求数和花费保持不变,但 运行 多次 returns 不同的金额。这个问题应该可以通过多次打印“询问”(定义如下)和函数结果来复制。

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,我希望 amount 等于 (0.62723766/51508.93591717) * 1000 但我得到的却是各种不同的输出。我该如何解决这个问题?

问题出在你的“我们没有足够的钱”的路径上。在这种情况下,您可以购买的数量不取决于所提供的数量。

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

您会得到各种不同的输出,因为您每次 运行 函数时都会获取新数据。将获取和计算拆分为单独的函数,以便您可以独立测试它们。您还可以通过正确命名变量使逻辑更清晰:

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 使用相同的订单簿任意多次,结果实际上总是相同的。