Skip to content
Snippets Groups Projects
Commit 81456771 authored by Fabian Schuh's avatar Fabian Schuh
Browse files

[account] raw history now working

parent c4752c01
No related branches found
No related tags found
No related merge requests found
...@@ -12,7 +12,7 @@ class Account(dict): ...@@ -12,7 +12,7 @@ class Account(dict):
bitshares_instance=None bitshares_instance=None
): ):
self.cached = False self.cached = False
self.name = account self.name = account.strip().lower()
self.full = full self.full = full
if not bitshares_instance: if not bitshares_instance:
...@@ -136,37 +136,55 @@ class Account(dict): ...@@ -136,37 +136,55 @@ class Account(dict):
i += batch_size i += batch_size
def rawhistory( def rawhistory(
self, first=99999999999, self, first=None,
limit=-1, only_ops=[], exclude_ops=[] last=1, limit=100,
only_ops=[], exclude_ops=[]
): ):
""" Returns a generator for individual account transactions. The """ Returns a generator for individual account transactions. The
latest operation will be first. This call can be used in a latest operation will be first. This call can be used in a
``for`` loop. ``for`` loop.
:param str account: account name to get history for :param int first: sequence number of the first transaction to return (*optional*)
:param int first: sequence number of the first transaction to return :param int limit: limit number of transactions to return (*optional*)
:param int limit: limit number of transactions to return :param array only_ops: Limit generator by these operations (*optional*)
:param array only_ops: Limit generator by these operations :param array exclude_ops: Exclude thse operations from generator (*optional*)
""" """
_limit=100
cnt = 0 cnt = 0
_limit = 100
if _limit > first: mostrecent = self.bitshares.rpc.get_account_history(
_limit = first self["id"],
while first > 0: "1.11.{}".format(0),
1,
"1.11.{}".format(9999999999999),
api="history"
)
if not mostrecent:
raise StopIteration
if not first:
first = int(mostrecent[0].get("id").split(".")[2]) + 1
while True:
# RPC call # RPC call
txs = self.bitshares.rpc.get_account_history(self.name, first, _limit) txs = self.bitshares.rpc.get_account_history(
for i in txs[::-1]: self["id"],
"1.11.{}".format(last),
_limit,
"1.11.{}".format(first - 1),
api="history"
)
for i in txs:
if exclude_ops and i[1]["op"][0] in exclude_ops: if exclude_ops and i[1]["op"][0] in exclude_ops:
continue continue
if not only_ops or i[1]["op"][0] in only_ops: if not only_ops or i[1]["op"][0] in only_ops:
cnt += 1 cnt += 1
yield i yield i
if limit >= 0 and cnt >= limit: if limit >= 0 and cnt >= limit:
break raise StopIteration
if limit >= 0 and cnt >= limit:
if not txs:
break break
if len(txs) < _limit: if len(txs) < _limit:
break break
first = txs[0][0] - 1 # new first first = int(txs[-1]["id"].split(".")[2])
if _limit > first:
_limit = first
...@@ -10,7 +10,14 @@ from bitsharesbase.objects import Operation ...@@ -10,7 +10,14 @@ from bitsharesbase.objects import Operation
class Market(dict): class Market(dict):
def __init__(self, *args, bitshares_instance=None, **kwargs): def __init__(
self,
*args,
base=None,
quote=None,
bitshares_instance=None,
**kwargs
):
if not bitshares_instance: if not bitshares_instance:
bitshares_instance = bts.BitShares() bitshares_instance = bts.BitShares()
self.bitshares = bitshares_instance self.bitshares = bitshares_instance
...@@ -21,6 +28,8 @@ class Market(dict): ...@@ -21,6 +28,8 @@ class Market(dict):
quote = Asset(quote_symbol, bitshares_instance=self.bitshares) quote = Asset(quote_symbol, bitshares_instance=self.bitshares)
base = Asset(base_symbol, bitshares_instance=self.bitshares) base = Asset(base_symbol, bitshares_instance=self.bitshares)
super(Market, self).__init__({"base": base, "quote": quote}) super(Market, self).__init__({"base": base, "quote": quote})
if len(args) == 0 and base and quote:
super(Market, self).__init__({"base": base, "quote": quote})
def ticker(self): def ticker(self):
""" Returns the ticker for all markets. """ Returns the ticker for all markets.
......
...@@ -68,7 +68,6 @@ class Price(dict): ...@@ -68,7 +68,6 @@ class Price(dict):
price = float(obj) price = float(obj)
base = Asset(base) base = Asset(base)
quote = Asset(quote) quote = Asset(quote)
else: else:
raise ValueError("Invalid way of calling Price()") raise ValueError("Invalid way of calling Price()")
...@@ -98,12 +97,24 @@ class Price(dict): ...@@ -98,12 +97,24 @@ class Price(dict):
return float('Inf') return float('Inf')
def __repr__(self): def __repr__(self):
return "%f %s/%s" % ( t = ""
if "time" in self and self["time"]:
t += "(%s) " % self["time"]
if "type" in self and self["type"]:
t += "%s " % str(self["type"])
if "quote_amount" in self and self["quote_amount"]:
t += "%s " % str(self["quote_amount"])
if "base_amount" in self and self["base_amount"]:
t += "%s " % str(self["base_amount"])
return t + "@%f %s/%s " % (
self["price"], self["price"],
self["base"].symbol, self["base"]["symbol"],
self["quote"].symbol self["quote"]["symbol"]
) )
__str__ = __repr__
def __float__(self): def __float__(self):
return self["price"] return self["price"]
...@@ -143,27 +154,59 @@ class Price(dict): ...@@ -143,27 +154,59 @@ class Price(dict):
__truediv__ = __div__ __truediv__ = __div__
__str__ = __repr__ __str__ = __repr__
@property
def market(self):
from .market import Market
return Market(
base=self["base"],
quote=self["quote"]
)
class Order(Price): class Order(Price):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
if isinstance(args[0], dict) and "sell_price" in args[0]: if (
isinstance(args[0], dict) and
"sell_price" in args[0]
):
super(Order, self).__init__(args[0]["sell_price"]) super(Order, self).__init__(args[0]["sell_price"])
for k, v in args[0].items(): for k, v in args[0].items():
self[k] = v self[k] = v
self["price"] = Price(args[0]["sell_price"])
self["quote_amount"] = Amount(args[0]["sell_price"]["quote"])
self["base_amount"] = Amount(args[0]["sell_price"]["base"])
self["quote"] = self["quote_amount"]["asset"]
self["base"] = self["base_amount"]["asset"]
elif (
isinstance(args[0], dict) and
"min_to_receive" in args[0] and
"amount_to_sell" in args[0]
):
super(Order, self).__init__(
Amount(args[0]["min_to_receive"]),
Amount(args[0]["amount_to_sell"]),
)
for k, v in args[0].items():
self[k] = v
self["price"] = Price(
Amount(args[0]["min_to_receive"]),
Amount(args[0]["amount_to_sell"])
)
self["quote_amount"] = Amount(args[0]["min_to_receive"])
self["base_amount"] = Amount(args[0]["amount_to_sell"])
self["quote"] = self["quote_amount"]["asset"]
self["base"] = self["base_amount"]["asset"]
elif isinstance(args[0], Amount) and isinstance(args[1], Amount):
self["price"] = Price(*args, **kwargs)
self["quote_amount"] = args[0]
self["base_amount"] = args[1]
self["quote"] = self["quote_amount"]["asset"]
self["base"] = self["base_amount"]["asset"]
else: else:
super(Order, self).__init__(*args, **kwargs) raise ValueError("Unkown format to load Order")
def __repr__(self):
return "%f %s/%s (%s|%s)" % (
self["price"],
self["base"].symbol,
self["quote"].symbol,
str(self["base"]),
str(self["quote"])
)
__str__ = __repr__
class FilledOrder(Price): class FilledOrder(Price):
...@@ -183,7 +226,14 @@ class FilledOrder(Price): ...@@ -183,7 +226,14 @@ class FilledOrder(Price):
order.get("value"), order.get("value"),
kwargs.get("base") kwargs.get("base")
) )
self["quote"] = self["quote_amount"]["asset"]
self["base"] = self["base_amount"]["asset"]
self["time"] = formatTimeString(order["date"]) self["time"] = formatTimeString(order["date"])
self["price"] = Price(
order.get("price"),
base=Asset(kwargs.get("base")),
quote=Asset(kwargs.get("quote")),
)
elif isinstance(order, dict) and "op" in order: elif isinstance(order, dict) and "op" in order:
quote = kwargs.get("quote") quote = kwargs.get("quote")
base = kwargs.get("base") base = kwargs.get("base")
...@@ -202,29 +252,28 @@ class FilledOrder(Price): ...@@ -202,29 +252,28 @@ class FilledOrder(Price):
self["quote_amount"] = Amount(order["op"]["pays"]) self["quote_amount"] = Amount(order["op"]["pays"])
self["base_amount"] = Amount(order["op"]["receives"]) self["base_amount"] = Amount(order["op"]["receives"])
self["type"] = "sell" self["type"] = "sell"
self["time"] = formatTimeString(self["time"])
else:
super(FilledOrder, self).__init__(order, **kwargs)
def __repr__(self): self["quote"] = self["quote_amount"]["asset"]
if "type" in self: self["base"] = self["base_amount"]["asset"]
return "(%s) %s %s for %s @%f %s/%s " % ( self["time"] = formatTimeString(self["time"])
self["time"], self["price"] = Price(
self["type"], order,
str(self["quote_amount"]), base=Asset(base),
str(self["base_amount"]), quote=Asset(quote),
self["price"],
self["base"].symbol,
self["quote"].symbol
) )
else: elif (
return "(%s) %s for %s %f @%s/%s" % ( isinstance(order, dict) and
self["time"], "receives" in order and
str(self["quote_amount"]), "pays" in order
str(self["base_amount"]), ):
self["price"], self["quote_amount"] = Amount(order["pays"])
self["base"].symbol, self["base_amount"] = Amount(order["receives"])
self["quote"].symbol self["quote"] = self["quote_amount"]["asset"]
self["base"] = self["base_amount"]["asset"]
self["time"] = None
self["price"] = Price(
self["base_amount"],
self["quote_amount"]
) )
else:
__str__ = __repr__ raise
...@@ -121,7 +121,7 @@ class TransactionBuilder(dict): ...@@ -121,7 +121,7 @@ class TransactionBuilder(dict):
# how to sign later. This is an array, because we # how to sign later. This is an array, because we
# may later want to allow multiple operations per tx # may later want to allow multiple operations per tx
self.update({"required_authorities": { self.update({"required_authorities": {
account: authority accountObj["name"]: authority
}}) }})
for account_auth in authority["account_auths"]: for account_auth in authority["account_auths"]:
account_auth_account = Account(account_auth[0]) account_auth_account = Account(account_auth[0])
...@@ -143,7 +143,7 @@ class TransactionBuilder(dict): ...@@ -143,7 +143,7 @@ class TransactionBuilder(dict):
def json(self): def json(self):
return dict(self) return dict(self)
def appendMissingSignatures(self, wifs): def appendMissingSignatures(self, wifs=[]):
missing_signatures = self.get("missing_signatures", []) missing_signatures = self.get("missing_signatures", [])
for pub in missing_signatures: for pub in missing_signatures:
wif = self.bitshares.wallet.getPrivateKeyForPublicKey(pub) wif = self.bitshares.wallet.getPrivateKeyForPublicKey(pub)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment