コード例 #1
0
 def __init__(self, feed, vinchain_instance=None):
     self.vinchain = vinchain_instance or shared_vinchain_instance()
     if len(feed) == 2:
         super(PriceFeed, self).__init__({
             "producer":
             Account(feed[0], lazy=True, vinchain_instance=self.vinchain),
             "date":
             parse_time(feed[1][0]),
             "maintenance_collateral_ratio":
             feed[1][1]["maintenance_collateral_ratio"],
             "maximum_short_squeeze_ratio":
             feed[1][1]["maximum_short_squeeze_ratio"],
             "settlement_price":
             Price(feed[1][1]["settlement_price"]),
             "core_exchange_rate":
             Price(feed[1][1]["core_exchange_rate"])
         })
     else:
         super(PriceFeed, self).__init__({
             "maintenance_collateral_ratio":
             feed["maintenance_collateral_ratio"],
             "maximum_short_squeeze_ratio":
             feed["maximum_short_squeeze_ratio"],
             "settlement_price":
             Price(feed["settlement_price"]),
             "core_exchange_rate":
             Price(feed["core_exchange_rate"])
         })
コード例 #2
0
    def __init__(self, *args, vinchain_instance=None, **kwargs):

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if (len(args) == 1 and isinstance(args[0], str)):
            order = self.vinchain.rpc.get_objects([args[0]])[0]
            if order:
                super(Order, self).__init__(order["sell_price"])
                self["seller"] = order["seller"]
                self["id"] = order.get("id")
                self["deleted"] = False
            else:
                self["id"] = args[0]
                self["deleted"] = True
                self["quote"] = None
                self["base"] = None
                self["price"] = None
                self["seller"] = None
        elif (isinstance(args[0], dict) and "sell_price" in args[0]):
            super(Order, self).__init__(args[0]["sell_price"])
            self["id"] = args[0].get("id")
        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"],
                       vinchain_instance=self.vinchain),
                Amount(args[0]["amount_to_sell"],
                       vinchain_instance=self.vinchain),
            )
            self["id"] = args[0].get("id")
        elif isinstance(args[0], Amount) and isinstance(args[1], Amount):
            super(Order, self).__init__(*args, **kwargs)
        else:
            raise ValueError("Unkown format to load Order")
コード例 #3
0
    def __init__(self, order, vinchain_instance=None, **kwargs):

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if isinstance(order, dict) and "price" in order:
            super(FilledOrder, self).__init__(
                order.get("price"),
                base=kwargs.get("base"),
                quote=kwargs.get("quote"),
            )
            self["time"] = formatTimeString(order["date"])
            self["side1_account_id"] = order["side1_account_id"]
            self["side2_account_id"] = order["side2_account_id"]

        elif isinstance(order, dict):
            # filled orders from account history
            if "op" in order:
                order = order["op"]
            base_asset = kwargs.get("base_asset",
                                    order["receives"]["asset_id"])
            super(FilledOrder, self).__init__(
                order,
                base_asset=base_asset,
            )
            if "time" in order:
                self["time"] = formatTimeString(order["time"])
            if "account_id" in order:
                self["account_id"] = order["account_id"]

        else:
            raise ValueError("Couldn't parse 'Price'.")
コード例 #4
0
    def __init__(self, vinchain_instance=None):
        self.vinchain = vinchain_instance or shared_vinchain_instance()
        self.schedule = self.vinchain.rpc.get_object("2.12.0").get(
            "current_shuffled_witnesses", [])

        super(Witnesses, self).__init__([
            Witness(x, lazy=True, vinchain_instance=self.vinchain)
            for x in self.schedule
        ])
コード例 #5
0
    def __init__(
        self,
        accounts=[],
        markets=[],
        objects=[],
        on_tx=None,
        on_object=None,
        on_block=None,
        on_account=None,
        on_market=None,
        vinchain_instance=None,
    ):
        # Events
        super(Notify, self).__init__()
        self.events = Events()

        # VinChain instance
        self.vinchain = vinchain_instance or shared_vinchain_instance()

        # Markets
        market_ids = []
        for market_name in markets:
            market = Market(market_name, vinchain_instance=self.vinchain)
            market_ids.append([
                market["base"]["id"],
                market["quote"]["id"],
            ])

        # Callbacks
        if on_tx:
            self.on_tx += on_tx
        if on_object:
            self.on_object += on_object
        if on_block:
            self.on_block += on_block
        if on_account:
            self.on_account += on_account
        if on_market:
            self.on_market += on_market

        # Open the websocket
        self.websocket = VinChainWebsocket(
            urls=self.vinchain.rpc.urls,
            user=self.vinchain.rpc.user,
            password=self.vinchain.rpc.password,
            accounts=accounts,
            markets=market_ids,
            objects=objects,
            on_tx=on_tx,
            on_object=on_object,
            on_block=on_block,
            on_account=self.process_account,
            on_market=self.process_market,
        )
コード例 #6
0
    def __init__(self,
                 from_account=None,
                 to_account=None,
                 vinchain_instance=None):

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if to_account:
            self.to_account = Account(to_account,
                                      vinchain_instance=self.vinchain)
        if from_account:
            self.from_account = Account(from_account,
                                        vinchain_instance=self.vinchain)
コード例 #7
0
    def __init__(
        self,
        vinchain_instance=None,
        mode="irreversible"
    ):
        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if mode == "irreversible":
            self.mode = 'last_irreversible_block_num'
        elif mode == "head":
            self.mode = "head_block_number"
        else:
            raise ValueError("invalid value for 'mode'!")
コード例 #8
0
    def __init__(self, call, vinchain_instance=None, **kwargs):

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if isinstance(call, dict) and "call_price" in call:
            super(UpdateCallOrder, self).__init__(
                call.get("call_price"),
                base=call["call_price"].get("base"),
                quote=call["call_price"].get("quote"),
            )

        else:
            raise ValueError("Couldn't parse 'Call'.")
コード例 #9
0
    def __init__(
        self,
        data,
        vinchain_instance=None
    ):
        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if isinstance(data, dict):
            super(AccountUpdate, self).__init__(data)
        else:
            account = Account(data, vinchain_instance=self.vinchain)
            update = self.vinchain.rpc.get_objects([
                "2.6.%s" % (account["id"].split(".")[2])
            ])[0]
            super(AccountUpdate, self).__init__(update)
コード例 #10
0
    def __init__(self, account_name=None, vinchain_instance=None):
        self.vinchain = vinchain_instance or shared_vinchain_instance()
        if account_name:
            account = Account(account_name, vinchain_instance=self.vinchain)
            self.workers = self.vinchain.rpc.get_workers_by_account(
                account["id"])
        else:
            self.workers = self.vinchain.rpc.get_all_workers()

        super(Workers, self).__init__(
            [
                Worker(x, lazy=True, vinchain_instance=self.vinchain)
                for x in self.workers
            ]
        )
コード例 #11
0
    def __init__(self,
                 data,
                 klass=None,
                 space_id=1,
                 object_id=None,
                 lazy=False,
                 use_cache=True,
                 vinchain_instance=None,
                 *args,
                 **kwargs):
        self.vinchain = vinchain_instance or shared_vinchain_instance()
        self.cached = False
        self.identifier = None

        # We don't read lists, sets, or tuples
        if isinstance(data, (list, set, tuple)):
            raise ValueError(
                "Cannot interpret lists! Please load elements individually!")

        if klass and isinstance(data, klass):
            self.identifier = data.get("id")
            super().__init__(data)
        elif isinstance(data, dict):
            self.identifier = data.get("id")
            super().__init__(data)
        elif isinstance(data, int):
            # This is only for block number bascially
            self.identifier = data
            if not lazy and not self.cached:
                self.refresh()
            # make sure to store the blocknumber for caching
            self["id"] = str(data)
            # Set identifier again as it is overwritten in super() in refresh()
            self.identifier = data
        else:
            self.identifier = data
            if self.test_valid_objectid(self.identifier):
                # Here we assume we deal with an id
                self.testid(self.identifier)
            if self.iscached(data):
                super().__init__(self.getcache(data))
            elif not lazy and not self.cached:
                self.refresh()

        if use_cache and not lazy:
            self.cache()
            self.cached = True
コード例 #12
0
 def __init__(
     self,
     tx={},
     proposer=None,
     expiration=None,
     vinchain_instance=None
 ):
     self.vinchain = vinchain_instance or shared_vinchain_instance()
     self.clear()
     if tx and isinstance(tx, dict):
         super(TransactionBuilder, self).__init__(tx)
         # Load operations
         self.ops = tx["operations"]
         self._require_reconstruction = False
     else:
         self._require_reconstruction = True
     self.set_expiration(expiration)
コード例 #13
0
    def __init__(
        self,
        proposer,
        proposal_expiration=None,
        proposal_review=None,
        parent=None,
        vinchain_instance=None,
        *args,
        **kwargs
    ):
        self.vinchain = vinchain_instance or shared_vinchain_instance()

        self.set_expiration(proposal_expiration or 2 * 24 * 60 * 60)
        self.set_review(proposal_review)
        self.set_parent(parent)
        self.set_proposer(proposer)
        self.ops = list()
コード例 #14
0
    def __init__(
        self,
        *args,
        base=None,
        quote=None,
        vinchain_instance=None,
        **kwargs
    ):
        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if len(args) == 1 and isinstance(args[0], str):
            quote_symbol, base_symbol = assets_from_string(args[0])
            quote = Asset(quote_symbol, vinchain_instance=self.vinchain)
            base = Asset(base_symbol, vinchain_instance=self.vinchain)
            super(Market, self).__init__({"base": base, "quote": quote})
        elif len(args) == 0 and base and quote:
            super(Market, self).__init__({"base": base, "quote": quote})
        elif len(args) == 2 and not base and not quote:
            super(Market, self).__init__({"base": args[1], "quote": args[0]})
        else:
            raise ValueError("Unknown Market Format: %s" % str(args))
コード例 #15
0
    def __init__(
            self,
            *args,
            base=None,
            quote=None,
            base_asset=None,  # to identify sell/buy
            vinchain_instance=None):

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if (len(args) == 1 and isinstance(args[0], str) and not base
                and not quote):
            import re
            price, assets = args[0].split(" ")
            base_symbol, quote_symbol = assets_from_string(assets)
            base = Asset(base_symbol, vinchain_instance=self.vinchain)
            quote = Asset(quote_symbol, vinchain_instance=self.vinchain)
            frac = Fraction(float(price)).limit_denominator(
                10**base["precision"])
            self["quote"] = Amount(amount=frac.denominator,
                                   asset=quote,
                                   vinchain_instance=self.vinchain)
            self["base"] = Amount(amount=frac.numerator,
                                  asset=base,
                                  vinchain_instance=self.vinchain)

        elif (len(args) == 1 and isinstance(args[0], dict)
              and "base" in args[0] and "quote" in args[0]):
            assert "price" not in args[
                0], "You cannot provide a 'price' this way"
            # Regular 'price' objects according to vinchain-core
            base_id = args[0]["base"]["asset_id"]
            if args[0]["base"]["asset_id"] == base_id:
                self["base"] = Amount(args[0]["base"],
                                      vinchain_instance=self.vinchain)
                self["quote"] = Amount(args[0]["quote"],
                                       vinchain_instance=self.vinchain)
            else:
                self["quote"] = Amount(args[0]["base"],
                                       vinchain_instance=self.vinchain)
                self["base"] = Amount(args[0]["quote"],
                                      vinchain_instance=self.vinchain)

        elif len(args) == 1 and isinstance(args[0],
                                           dict) and "receives" in args[0]:
            # Filled order
            assert base_asset, "Need a 'base_asset' asset"
            base_asset = Asset(base_asset, vinchain_instance=self.vinchain)
            if args[0]["receives"]["asset_id"] == base_asset["id"]:
                # If the seller received "base" in a quote_base market, than
                # it has been a sell order of quote
                self["base"] = Amount(args[0]["receives"],
                                      vinchain_instance=self.vinchain)
                self["quote"] = Amount(args[0]["pays"],
                                       vinchain_instance=self.vinchain)
                self["type"] = "sell"
            else:
                # buy order
                self["base"] = Amount(args[0]["pays"],
                                      vinchain_instance=self.vinchain)
                self["quote"] = Amount(args[0]["receives"],
                                       vinchain_instance=self.vinchain)
                self["type"] = "buy"

        elif len(args) == 1 and (isinstance(base, Asset)
                                 and isinstance(quote, Asset)):
            price = args[0]
            frac = Fraction(float(price)).limit_denominator(
                10**base["precision"])
            self["quote"] = Amount(amount=frac.denominator,
                                   asset=quote,
                                   vinchain_instance=self.vinchain)
            self["base"] = Amount(amount=frac.numerator,
                                  asset=base,
                                  vinchain_instance=self.vinchain)

        elif (len(args) == 1 and isinstance(base, str)
              and isinstance(quote, str)):
            price = args[0]
            base = Asset(base, vinchain_instance=self.vinchain)
            quote = Asset(quote, vinchain_instance=self.vinchain)
            frac = Fraction(float(price)).limit_denominator(
                10**base["precision"])
            self["quote"] = Amount(amount=frac.denominator,
                                   asset=quote,
                                   vinchain_instance=self.vinchain)
            self["base"] = Amount(amount=frac.numerator,
                                  asset=base,
                                  vinchain_instance=self.vinchain)

        elif (len(args) == 0 and isinstance(base, str)
              and isinstance(quote, str)):
            self["quote"] = Amount(quote, vinchain_instance=self.vinchain)
            self["base"] = Amount(base, vinchain_instance=self.vinchain)

        # len(args) > 1
        elif len(args) == 2 and isinstance(args[0], str) and isinstance(
                args[1], str):
            self["base"] = Amount(args[1], vinchain_instance=self.vinchain)
            self["quote"] = Amount(args[0], vinchain_instance=self.vinchain)

        elif len(args) == 2 and isinstance(args[0], Amount) and isinstance(
                args[1], Amount):
            self["quote"], self["base"] = args[0], args[1]

        # len(args) == 0
        elif (isinstance(base, Amount) and isinstance(quote, Amount)):
            self["quote"] = quote
            self["base"] = base

        elif (len(args) == 2
              and (isinstance(args[0], float) or isinstance(args[0], int))
              and isinstance(args[1], str)):
            import re
            price = args[0]
            base_symbol, quote_symbol = assets_from_string(args[1])
            base = Asset(base_symbol, vinchain_instance=self.vinchain)
            quote = Asset(quote_symbol, vinchain_instance=self.vinchain)
            frac = Fraction(float(price)).limit_denominator(
                10**base["precision"])
            self["quote"] = Amount(amount=frac.denominator,
                                   asset=quote,
                                   vinchain_instance=self.vinchain)
            self["base"] = Amount(amount=frac.numerator,
                                  asset=base,
                                  vinchain_instance=self.vinchain)

        else:
            raise ValueError("Couldn't parse 'Price'.")
コード例 #16
0
 def __init__(self, message, vinchain_instance=None):
     self.vinchain = vinchain_instance or shared_vinchain_instance()
     self.message = message
     self.meta = {}
コード例 #17
0
    def __init__(self, *args, amount=None, asset=None, vinchain_instance=None):
        self["asset"] = {}

        self.vinchain = vinchain_instance or shared_vinchain_instance()

        if len(args) == 1 and isinstance(args[0], Amount):
            # Copy Asset object
            self["amount"] = args[0]["amount"]
            self["symbol"] = args[0]["symbol"]
            self["asset"] = args[0]["asset"]

        elif len(args) == 1 and isinstance(args[0], str):
            self["amount"], self["symbol"] = args[0].split(" ")
            self["asset"] = Asset(self["symbol"],
                                  vinchain_instance=self.vinchain)

        elif (len(args) == 1 and isinstance(args[0], dict)
              and "amount" in args[0] and "asset_id" in args[0]):
            self["asset"] = Asset(args[0]["asset_id"],
                                  vinchain_instance=self.vinchain)
            self["symbol"] = self["asset"]["symbol"]
            self["amount"] = int(
                args[0]["amount"]) / 10**self["asset"]["precision"]

        elif (len(args) == 1 and isinstance(args[0], dict)
              and "amount" in args[0] and "asset" in args[0]):
            self["asset"] = Asset(args[0]["asset"],
                                  vinchain_instance=self.vinchain)
            self["symbol"] = self["asset"]["symbol"]
            self["amount"] = int(
                args[0]["amount"]) / 10**self["asset"]["precision"]

        elif len(args) == 2 and isinstance(args[1], Asset):
            self["amount"] = args[0]
            self["symbol"] = args[1]["symbol"]
            self["asset"] = args[1]

        elif len(args) == 2 and isinstance(args[1], str):
            self["amount"] = args[0]
            self["asset"] = Asset(args[1], vinchain_instance=self.vinchain)
            self["symbol"] = self["asset"]["symbol"]

        elif isinstance(amount,
                        (int, float)) and asset and isinstance(asset, Asset):
            self["amount"] = amount
            self["asset"] = asset
            self["symbol"] = self["asset"]["symbol"]

        elif isinstance(amount,
                        (int, float)) and asset and isinstance(asset, dict):
            self["amount"] = amount
            self["asset"] = asset
            self["symbol"] = self["asset"]["symbol"]

        elif isinstance(amount,
                        (int, float)) and asset and isinstance(asset, str):
            self["amount"] = amount
            self["asset"] = Asset(asset, vinchain_instance=self.vinchain)
            self["symbol"] = asset

        else:
            raise ValueError

        # make sure amount is a float
        self["amount"] = float(self["amount"])