Skip to content

Commit

Permalink
Merge pull request #64 from bitshares/nomics
Browse files Browse the repository at this point in the history
Nomics implementation
  • Loading branch information
oxarbitrage authored Aug 30, 2019
2 parents 840f160 + c88f22d commit 9444323
Show file tree
Hide file tree
Showing 5 changed files with 213 additions and 0 deletions.
25 changes: 25 additions & 0 deletions api/es_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,28 @@ def get_trx(trx, from_=0, size=10):
response = s.execute()

return [ hit.to_dict() for hit in response ]


def get_trade_history(size=10, from_date='2015-10-10', to_date='now', sort_by='-operation_id_num',
search_after=None, base="1.3.0", quote="1.3.121"):

s = Search(using=es, index="bitshares-*")

s = s.extra(size=size)
if search_after and search_after != '':
s = s.extra(search_after=search_after.split(','))

q = Q()
q = q & Q("match", operation_type=4)
q = q & Q("match", operation_history__op_object__is_maker=True)

q = q & Q("match", operation_history__op_object__fill_price__base__asset_id=base)
q = q & Q("match", operation_history__op_object__fill_price__quote__asset_id=quote)

range_query = Q("range", block_data__block_time={'gte': from_date, 'lte': to_date})
s.query = q & range_query

s = s.sort(*sort_by.split(','))
response = s.execute()

return [hit.to_dict() for hit in response]
6 changes: 6 additions & 0 deletions api/explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,11 +587,17 @@ def lookup_assets(start):
asset_names = bitshares_es_client.get_asset_names(start)
return [ [ asset_name ] for asset_name in asset_names ]


def get_last_block_number():
dynamic_global_properties = bitshares_ws_client.request('database', 'get_dynamic_global_properties', [])
return dynamic_global_properties["head_block_number"]


def get_last_block_time():
dynamic_global_properties = bitshares_ws_client.request('database', 'get_dynamic_global_properties', [])
return dynamic_global_properties["time"]


def get_account_history(account_id, page, search_after):
account_id = _get_account_id(account_id)

Expand Down
105 changes: 105 additions & 0 deletions api/nomics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import datetime
import calendar
import connexion

from services.bitshares_websocket_client import client as bitshares_ws_client
from services.bitshares_elasticsearch_client import client as bitshares_es_client
from services.cache import cache
import api.explorer
import es_wrapper
import config


def info():
return {
"name": "Bitshares",
"description": "The BitShares Blockchain is an industrial-grade decentralized platform built for "
"high-performance financial smart contracts mostly known for: its token factory,"
" a decentralized exchange as a built-in native dapp (known as the DEX) and its stablecoins"
" or, as they are called in BitShares, Smartcoins. It represents the first decentralized"
" autonomous community that lets its core token holders decide on its future direction and"
" products by means of on-chain voting. It is also the first DPoS blockchain in existence and"
" the first blockchain to implement stablecoins.",
"location": "Worldwide",
"logo": "https://bitshares.org/exchange-logo.png",
"website": "https://bitshares.org/",
"twitter": "https://twitter.com/bitshares",
"capability": {
"markets": True,
"trades": True,
"tradesSocket": False,
"orders": False,
"ordersSocket": False,
"ordersSnapshot": True,
"candles": False
}
}


def markets():
result = [
{"id": "CNY-BTS", "base": "CNY", "quote": "BTS"},
{"id": "USD-BTS", "base": "USD", "quote": "BTS"},
{"id": "CNY-USD", "base": "CNY", "quote": "USD"},
{"id": "EUR-BTS", "base": "EUR", "quote": "BTS"},
{"id": "RUBLE-BTS", "base": "RUBLE", "quote": "BTS"},
{"id": "SILVER-BTS", "base": "SILVER", "quote": "BTS"},
{"id": "GOLD-BTS", "base": "GOLD", "quote": "BTS"}
]

return result


@cache.memoize()
def trades(market, since):

market_id = market.split('-')
base = market_id[0]
quote = market_id[1]

base_asset = api.explorer._get_asset_id_and_precision(base)
quote_asset = api.explorer._get_asset_id_and_precision(quote)

trade_history = es_wrapper.get_trade_history(search_after=since, base=base_asset[0], quote=quote_asset[0], size=20,
sort_by='operation_id_num')

results = []
for trade in trade_history:
base_amount = trade["operation_history"]["op_object"]["fill_price"]["base"]["amount"]
quote_amount = trade["operation_history"]["op_object"]["fill_price"]["base"]["amount"]

results.append({
"id": str(trade["operation_id_num"]),
"timestamp": trade["block_data"]["block_time"],
"price": str(float(float(base_amount)/int(base_asset[1]))/float(float(quote_amount)/int(quote_asset[1]))),
"amount": str(trade["operation_history"]["op_object"]["receives"]["amount"]/quote_asset[1])
})

return results


def snapshot(market):
result = {}

market_id = market.split('-')
base = market_id[0]
quote = market_id[1]

order_book = api.explorer.get_order_book(base, quote, 100)

bids = []
asks = []

for bid in order_book["bids"]:
bids.append([float(bid["price"]), float(bid["base"])])

result["bids"] = bids

for ask in order_book["asks"]:
asks.append([float(ask["price"]), float(ask["base"])])

result["asks"] = asks

result["timestamp"] = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")

return result
12 changes: 12 additions & 0 deletions swagger/paths_explorer.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,18 @@ paths:
tags:
- api
- operation
"/last_block_time":
get:
description: Get current block time
operationId: api.explorer.get_last_block_time
responses:
'200':
description: last known block time
'500':
description: Error processing parameters
tags:
- api
- operation
"/dex_total_volume":
get:
description: Get some total dex volume figures
Expand Down
65 changes: 65 additions & 0 deletions swagger/paths_nomics.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
paths:
"/nomics/info":
get:
description: Returns information about the exchange as a whole, and is used by Nomics to display information about Bitshares to users.
operationId: api.nomics.info
responses:
'200':
description: JSON object containing excchange info
'500':
description: Error processing parameters
tags:
- nomics
"/nomics/markets":
get:
description: Returns a list of the top markets on the Bitshares exchange.
operationId: api.nomics.markets
responses:
'200':
description: Top markets
'500':
description: Error processing parameters
tags:
- nomics
"/nomics/trades":
get:
description: Search for an asset(symbol)
operationId: api.nomics.trades
parameters:
- in: query
name: market
default: USD-BTS
type: string
required: true
description: Market
- in: query
name: since
default: ''
type: string
required: false
description: A trade ID from a previous /trades response. If none is provided, the oldest trades should be returned
responses:
'200':
description: Found assets
'500':
description: Error processing parameters
tags:
- nomics
"/nomics/orders/snapshot":
get:
description: The /orders/snapshot endpoint returns the current order book for a given market. It allows Nomics to get a simple snapshot of open orders.
operationId: api.nomics.snapshot
parameters:
- in: query
name: market
default: USD-CNY
type: string
required: true
description: Market
responses:
'200':
description: History in selected period.
'500':
description: Error processing parameters
tags:
- nomics

0 comments on commit 9444323

Please sign in to comment.