async def load_trading_mining_data(viteAddress: str): try: api_url = get_dex_api_url(1) + '/mining/trade' params = {'address': viteAddress} response = requests.get(url=api_url, params=params) if response.status_code == status.HTTP_200_OK: resp = response.json() check_response(resp) csv_data = build_mining_data_list(resp['data']['miningList']) generated_message = generate_return_file_msg(csv_data) response = StreamingResponse( content=generated_message['file'], media_type='text/csv', headers={ 'Content-Disposition': 'filename=tradeMining_{viteAddress}.csv' }) return response else: raise HTTPException(status_code=response.status_code, detail='Error from vite network') except Exception as e: raise e
async def load_mining_pledge_data(viteAddress: str): try: api_url = get_dex_api_url(1) + '/mining/pledge' params = {'address': viteAddress} response = requests.get(url=api_url, params=params) if response.status_code == status.HTTP_200_OK: resp = response.json() check_response(resp) csv_data = [] for staking in resp['data']['miningList']: dtobj = datetime.fromtimestamp(staking['date'], timezone.utc) dataRow = { 'pledgeAmount': staking['pledgeAmount'], 'miningAmount': staking['miningAmount'], 'miningToken': staking['miningToken'], 'status': staking['status'], 'date': staking['date'], 'dt': dtobj.strftime('%d/%m/%Y %H:%M:%S.%f')[:-3], } csv_data.append(dataRow) generated_message = generate_return_file_msg(csv_data) response = StreamingResponse( content=generated_message['file'], media_type='text/csv', headers={ 'Content-Disposition': 'filename=pledgeMining_{viteAddress}.csv' }) return response else: raise HTTPException(status_code=response.status_code, detail='Error from vite network') except Exception as e: raise e
async def load_markets(): try: api_url = get_dex_api_url(2) + '/markets' response = requests.get(url=api_url) if response.status_code == status.HTTP_200_OK: resp = response.json() if (resp['code'] != 0): raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=resp['msg']) if not 'data' in resp or len(resp['data']) == 0: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail='No data received from exchange') trade_pairs = [] trade_tokens = [] quote_tokens = [] for tradePair in resp['data']: trade_pairs.append(tradePair['symbol']) if tradePair['tradeTokenSymbol'] not in trade_tokens: trade_tokens.append(tradePair['tradeTokenSymbol']) if tradePair['quoteTokenSymbol'] not in quote_tokens: quote_tokens.append(tradePair['quoteTokenSymbol']) data = { 'tradePairs': trade_pairs, 'tradeTokens': trade_tokens, 'quoteTokens': quote_tokens, } return data except Exception as e: raise e
async def load_dividends(viteAddress: str): api_url = get_dex_api_url(1) + '/dividend' try: params = {'address': viteAddress} response = requests.get(url=api_url, params=params) if response.status_code == status.HTTP_200_OK: resp = response.json() if (resp['code'] != 0): raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=resp['msg']) if not 'dividendList' in resp['data'] or len( resp['data']['dividendList']) == 0: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='No data received from exchange') dividends = [] for dividend in resp['data']['dividendList']: dtobj = datetime.fromtimestamp(dividend['date'], timezone.utc) dividend_dict = {'vxQuantity': dividend['vxQuantity']} if ('BTC' in dividend['dividendStat']): dividend_dict[ dividend['dividendStat']['BTC']['tokenDividends'][0] ['tokenSymbol']] = dividend['dividendStat']['BTC'][ 'tokenDividends'][0]['amount'] if ('ETH' in dividend['dividendStat']): dividend_dict[ dividend['dividendStat']['ETH']['tokenDividends'][0] ['tokenSymbol']] = dividend['dividendStat']['ETH'][ 'tokenDividends'][0]['amount'] if ('USDT' in dividend['dividendStat']): dividend_dict[ dividend['dividendStat']['USDT']['tokenDividends'][0] ['tokenSymbol']] = dividend['dividendStat']['USDT'][ 'tokenDividends'][0]['amount'] dividend_dict['date'] = dividend['date'] dividend_dict['dt'] = dtobj.strftime( '%d/%m/%Y %H:%M:%S.%f')[:-3] dividends.append(dividend_dict) generated_message = generate_return_file_msg(dividends) response = StreamingResponse( content=generated_message['file'], media_type='text/csv', headers={ 'Content-Disposition': 'filename=dividends_{viteAddress}.csv' }) return response else: raise HTTPException(status_code=response.status_code, detail='Error from vite network') except Exception as e: print(e) raise e
async def load_prices(tradePair: str, interval: str, fromDate: Optional[date] = None, toDate: Optional[date] = None): # https://vite.wiki/dex/api/dex-apis.html#get-klines-candlestick-bars apiURL = get_dex_api_url(2) + '/klines' limit = 500 params = { 'symbol': tradePair, 'interval': interval, 'limit': limit, } if fromDate is not None: params['startTime'] = int( datetime(fromDate.year, fromDate.month, fromDate.day).timestamp()) if toDate is not None: params['endTime'] = int( datetime(toDate.year, toDate.month, toDate.day).timestamp()) filtered_params = {k: v for k, v in params.items() if v is not None} try: response = requests.get(url=apiURL, params=filtered_params) print(response.json()) if response.status_code == 200: resp = response.json() prices = [] if (resp['code'] != 0): raise HTTPException(status_code=500, detail=resp['msg']) if not ('t' in resp['data'] and 'c' in resp['data'] and 'p' in resp['data'] and 'h' in resp['data'] and 'l' in resp['data'] and 'v' in resp['data']): raise HTTPException(status_code=404, detail='No data received from exchange') result_count = len(resp['data']['t']) for i in range(0, result_count): dtobj = datetime.fromtimestamp(resp['data']['t'][i], timezone.utc) if (resp['data']['c'][i] != 0.0 and resp['data']['p'][i] != 0.0 and resp['data']['v'][i] != 0.0): priceDict = { 'timeStamp': resp['data']['t'][i], 'dt': dtobj.strftime('%d/%m/%Y %H:%M'), 'symbol': tradePair, 'interval': interval, 'openPrice': resp['data']['p'][i], 'closePrice': resp['data']['c'][i], 'lowestPrice': resp['data']['l'][i], 'highestPrice': resp['data']['h'][i], 'tradeVolume': resp['data']['v'][i], } prices.append(priceDict) else: raise HTTPException(status_code=response.status_code, detail='Error from vite network') generated_message = generate_return_file_msg(prices) response = StreamingResponse( content=generated_message['file'], media_type='text/csv', headers={'Content-Disposition': 'filename=prices.csv'}) return response except Exception as e: raise e
async def load_orders(viteAddress: str, fromDate: Optional[date] = None, toDate: Optional[date] = None, sellBuy: Optional[int] = None, tradePair: Optional[str] = None, quoteToken: Optional[str] = None, tradeToken: Optional[str] = None, orderStatus: Optional[str] = None): api_url = get_dex_api_url(2) + '/orders' limit = 100 dict_order_type = { 0: 'Limit Order', 1: 'Market Order', } dict_order_status = { 0: 'Unkown', 1: 'Pending', 2: 'Received', 3: 'Open', 4: 'Filled', 5: 'Partially Filled', 6: 'Pending Cancel', 7: 'Cancelled', 8: 'Partially', 9: 'Failed', 10: 'Expired', } dict_side = { 0: 'Buy Order', 1: 'Sell Order', } params = { 'address': viteAddress, 'limit': limit, } if fromDate is not None: params['startTime'] = int( datetime(fromDate.year, fromDate.month, fromDate.day).timestamp()) if toDate is not None: params['endTime'] = int( datetime(toDate.year, toDate.month, toDate.day).timestamp()) params['side'] = sellBuy params['symbol'] = tradePair params['quoteTokenSymbol'] = quoteToken params['tradeTokenSymbol'] = tradeToken params['status'] = orderStatus filtered_params = {k: v for k, v in params.items() if v is not None} try: orders = [] run_request = True while (run_request == True): print(filtered_params) response = requests.get(url=api_url, params=filtered_params) print(response.json()) if response.status_code == status.HTTP_200_OK: resp = response.json() if (resp['code'] != 0): raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=resp['msg']) if not 'order' in resp['data'] or len( resp['data']['order']) == 0: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail='No data received from exchange') for order in resp['data']['order']: dtobj = datetime.fromtimestamp(order['createTime'], timezone.utc) order_dict = { 'address': order['address'], 'orderId': order['orderId'], 'symbol': order['symbol'], 'tradeTokenSymbol': order['tradeTokenSymbol'], 'quoteTokenSymbol': order['quoteTokenSymbol'], 'side': dict_side[order['side']], 'price': order['price'], 'quantity': order['quantity'], 'amount': order['amount'], 'executedQuantity': order['executedQuantity'], 'executedAmount': order['executedAmount'], 'executedPercent': order['executedPercent'], 'executedAvgPrice': order['executedAvgPrice'], 'fee': order['fee'], 'status': dict_order_status[order['status']], 'type': dict_order_type[order['type']], 'createTime': order['createTime'], 'dt': dtobj.strftime('%d/%m/%Y %H:%M:%S.%f')[:-3] } orders.append(order_dict) if limit == len(resp['data']['order']): last_order = resp['data']['order'][-1:] filtered_params[ 'endTime'] = last_order[0]['createTime'] - 1 else: run_request = False else: raise HTTPException(status_code=response.status_code, detail='Error from vite network') generated_message = generate_return_file_msg(orders) response = StreamingResponse(content=generated_message['file'], media_type='text/csv', headers={ 'Content-Disposition': 'filename=orders_{viteAddress}.csv' }) return response except Exception as e: raise e