这是我使用 Poloniex Exchange API 的函数。它得到一个dict
询问(价格和金额的元组),然后计算使用给定支出将获得的 BTC 总量。
但是,尽管询问的字典和花费保持不变,但多次运行该函数会返回不同的金额。这个问题应该可以通过多次打印“asks”(定义如下)和函数结果来复制。
def findBuyAmount(spend):
#getOrderBook
URL = "https://poloniex.com/public?command=returnOrderBook¤cyPair=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
,但我会得到各种不同的输出。我怎样才能解决这个问题?