0

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

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

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 dict 中的第一个 ask 是[51508.93591717, 0.62723766],spend 是1000,我希望数量相等(0.62723766/51508.93591717) * 1000,但我会得到各种不同的输出。我怎样才能解决这个问题?

4

2 回答 2

2

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

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使用同一个订单簿运行任意次数,并看到结果实际上总是相同的。

于 2021-03-10T00:31:47.687 回答
0

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

            if elem[1]*elem[0] > spend:
                amount += spend/elem[0]
于 2021-03-09T23:43:47.457 回答