Beispiel #1
0
def print_permissions(account):
    t = PrettyTable(["Permission", "Threshold", "Key/Account"],
                    hrules=allBorders)
    t.align = "r"
    for permission in ["owner", "active"]:
        auths = []
        # account auths:
        for authority in account[permission]["account_auths"]:
            auths.append("%s (%d)" %
                         (Account(authority[0])["name"], authority[1]))
        # key auths:
        for authority in account[permission]["key_auths"]:
            auths.append("%s (%d)" % (authority[0], authority[1]))
        t.add_row([
            permission,
            account[permission]["weight_threshold"],
            "\n".join(auths),
        ])
    click.echo(t)
Beispiel #2
0
 def get_call_orders(self, limit=100):
     from .price import Price
     from .amount import Amount
     assert limit <= 100
     assert self.is_bitasset
     self.ensure_full()
     r = list()
     bitasset = self["bitasset_data"]
     settlement_price = Price(bitasset["current_feed"]["settlement_price"])
     ret = self.bitshares.rpc.get_call_orders(self["id"], limit)
     for call in ret[:limit]:
         call_price = Price(call["call_price"])
         collateral_amount = Amount(
             {
                 "amount": call["collateral"],
                 "asset_id": call["call_price"]["base"]["asset_id"]
             },
             bitshares_instance=self.bitshares)
         debt_amount = Amount(
             {
                 "amount": call["debt"],
                 "asset_id": call["call_price"]["quote"]["asset_id"],
             },
             bitshares_instance=self.bitshares)
         r.append({
             "account":
             Account(call["borrower"],
                     lazy=True,
                     bitshares_instance=self.bitshares),
             "collateral":
             collateral_amount,
             "debt":
             debt_amount,
             "call_price":
             call_price,
             "settlement_price":
             settlement_price,
             "ratio":
             float(collateral_amount) / float(debt_amount) *
             float(settlement_price)
         })
     return r
Beispiel #3
0
def workers(ctx, account, top, sort):
    """ List all workers (of an account)
    """
    def normalize_sort_keys(name):
        if name == "votes":
            return "total_votes_for"
        return name

    workers = Workers(account)
    t = [["id", "name/url", "daily_pay", "votes", "time", "account"]]
    sort = sort
    sort = normalize_sort_keys(sort)
    if sort in ["total_votes_for"]:
        workers_sorted = sorted(workers,
                                key=lambda x: int(x[sort]),
                                reverse=True)
    elif sort == "id":
        workers_sorted = sorted(workers,
                                key=lambda x: int(x[sort].split(".")[2]),
                                reverse=True)
    else:
        workers_sorted = sorted(workers, key=lambda x: x[sort], reverse=True)
    if top:
        workers_sorted = workers_sorted[:top + 1]
    for worker in workers_sorted:
        if worker["work_end_date"] < datetime.datetime.utcnow():
            continue
        votes = Amount({
            "amount": worker["total_votes_for"],
            "asset_id": "1.3.0"
        })
        amount = Amount({"amount": worker["daily_pay"], "asset_id": "1.3.0"})
        t.append([
            worker["id"],
            "{name}\n{url}".format(**worker),
            str(amount),
            str(votes),
            "{work_begin_date:%Y-%m-%d}\n-\n{work_end_date:%Y-%m-%d}".format(
                **worker),
            str(Account(worker["worker_account"])["name"]),
        ])
    print_table(t)
Beispiel #4
0
    def update_feed_producers(self, producers):
        """ Update bitasset feed producers

            :param list producers: List of accounts that are allowed to produce
                 a feed
        """
        assert self.is_bitasset, \
            "Asset needs to be a bitasset/market pegged asset"
        op = operations.Asset_update_feed_producers(
            **{
                "fee": {
                    "amount": 0,
                    "asset_id": "1.3.0"
                },
                "issuer": self["issuer"],
                "asset_to_update": self["id"],
                "new_feed_producers": [Account(a)["id"] for a in producers],
                "extensions": []
            })
        return self.blockchain.finalizeOp(op, self["issuer"], "active")
Beispiel #5
0
def get_worker_proposals(api_key: hug.types.text, hug_timer=15):
    """Get a list of all worker proposals!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID

        num_workers_request = request_json(
            '{"jsonrpc": "2.0", "method": "get_worker_count", "params": [], "id": 1}'
        )

        if num_workers_request.status_code is not 200:
            # We want to catch any failed GET requests!
            return {
                'request_status_code_error': True,
                'valid_key': True,
                'took': float(hug_timer)
            }
        else:
            # Request is valid!
            num_workers = num_workers_request.json()['result']

            worker_list = []
            for worker in range(num_workers):
                worker_id = "1.14." + str(worker)
                current_worker = bitshares_api_node.rpc.get_objects(
                    [worker_id])[0]

                target_account = Account(current_worker['worker_account'])
                target_account_data = extract_object(target_account)

                current_worker['worker_account_details'] = target_account_data

                worker_list.append(current_worker)

            return {
                'workers': worker_list,
                'valid_key': True,
                'took': float(hug_timer)
            }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
Beispiel #6
0
def get_committee_member(committee_id: hug.types.text, api_key: hug.types.text, request, hug_timer=15):
	"""Retrieve information about a single committee member (inc full account details)!"""
	if (check_api_token(api_key) == True): # Check the api key
		google_analytics(request, 'get_committee_member')
		if ("1.5." not in committee_id):
			return {'valid_committee_id': False,
					'valid_key': True,
					'took': float(hug_timer)}

		try:
			target_committee_member = bitshares_api_node.rpc.get_objects([committee_id])[0]
		except:
			return {'valid_committee_id': False,
					'valid_key': True,
					'took': float(hug_timer)}

		if target_committee_member is None:
			return {'valid_committee_id': False,
					'valid_key': True,
					'took': float(hug_timer)}

		target_account = Account(target_committee_member['committee_member_account'], full=True) # Full info!
		target_account_data = extract_object(target_account)

		active_committee_members = Blockchain().config()['active_committee_members']

		if committee_id in active_committee_members:
			target_account_data['status'] = True
		else:
			target_account_data['status'] = False

		target_committee_member['committee_member_details'] = target_account_data

		return {'get_committee_member': target_committee_member,
				'valid_committee_id': True,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
Beispiel #7
0
def issue_asset(inst,
                issue_to_account,
                to_issue_asset,
                amount,
                memo=None,
                account=None,
                **kwargs):
    """ issue_asset


       :param str account: the account to cancel
           to (defaults to ``default_account``)
   """
    if not account:
        if "default_account" in inst.config:
            account = inst.config["default_account"]
    if not account:
        raise ValueError("You need to provide an account")
    account = Account(account)

    if 'extensions' in kwargs:
        extensions = kwargs['extensions']
    else:
        extensions = Set([])
    print(extensions)
    asset_to_issue = {"amount": amount, "asset_id": to_issue_asset}
    kwargs = {
        'fee': {
            "amount": 0,
            "asset_id": "1.3.0"
        },
        'issuer': account["id"],
        'asset_to_issue': asset_to_issue,
        'issue_to_account': issue_to_account,
        'memo': memo,
        'extensions': extensions
    }

    op = operations.Asset_issue(**kwargs)

    return inst.finalizeOp(op, account, "active")
Beispiel #8
0
def importaccount(ctx, account, role):
    """ Import an account using an account password
    """
    from bitsharesbase.account import PasswordKey

    password = click.prompt(
        "Account Passphrase",
        hide_input=True,
    )
    account = Account(account, bitshares_instance=ctx.bitshares)
    imported = False

    if role == "owner":
        owner_key = PasswordKey(account["name"], password, role="owner")
        owner_pubkey = format(owner_key.get_public_key(), ctx.bitshares.rpc.chain_params["prefix"])
        if owner_pubkey in [x[0] for x in account["owner"]["key_auths"]]:
            click.echo("Importing owner key!")
            owner_privkey = owner_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(owner_privkey)
            imported = True

    if role == "active":
        active_key = PasswordKey(account["name"], password, role="active")
        active_pubkey = format(active_key.get_public_key(), ctx.bitshares.rpc.chain_params["prefix"])
        if active_pubkey in [x[0] for x in account["active"]["key_auths"]]:
            click.echo("Importing active key!")
            active_privkey = active_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(active_privkey)
            imported = True

    if role == "memo":
        memo_key = PasswordKey(account["name"], password, role=role)
        memo_pubkey = format(memo_key.get_public_key(), ctx.bitshares.rpc.chain_params["prefix"])
        if memo_pubkey == account["memo_key"]:
            click.echo("Importing memo key!")
            memo_privkey = memo_key.get_private_key()
            ctx.bitshares.wallet.addPrivateKey(memo_privkey)
            imported = True

    if not imported:
        click.echo("No matching key(s) found. Password correct?")
Beispiel #9
0
def full_account_info(account_name: hug.types.text,
                      api_key: hug.types.text,
                      hug_timer=5):
    """Retrieve verbose information about an individual Bitshares account!"""
    try:
        target_account = Account(account_name, full=True)
    except:
        return {
            'valid_account': False,
            'account': account_name,
            'valid_key': True,
            'took': float(hug_timer)
        }

    extracted_object = extract_object(target_account)

    return {
        'full_account_info': extracted_object,
        'valid_key': True,
        'took': float(hug_timer)
    }
Beispiel #10
0
def print_permissions(account):
    t = [["Permission", "Threshold", "Key/Account"]]
    for permission in ["owner", "active"]:
        auths = []
        # account auths:
        for authority in sorted(account[permission]["account_auths"],
                                key=lambda x: x[1],
                                reverse=True):
            auths.append("%s (%d)" %
                         (Account(authority[0])["name"], authority[1]))
        # key auths:
        for authority in sorted(account[permission]["key_auths"],
                                key=lambda x: x[1],
                                reverse=True):
            auths.append("%s (%d)" % (authority[0], authority[1]))
        t.append([
            permission, account[permission]["weight_threshold"],
            "\n".join(auths)
        ])
    t.append(["memo", "n/a", account["options"]["memo_key"]])
    print_table(t, hrules=True)
Beispiel #11
0
def transfer_asset():
    cybex_config(node_rpc_endpoint=NODE_WS_ENDPOINT, chain_id=CHAIN_ID)

    net = BitShares(node=NODE_WS_ENDPOINT, **{'prefix': 'cyb'})

    unlock(net)

    try:
        net.wallet.addPrivateKey(FROM_ACCOUNT_ACTIVE_PRIVATE_KEY)
    except Exception as e:
        pass

    net.wallet.unlock(WALLET_PASSWD)

    acc = Account(FROM_ACCOUNT, bitshares_instance=net)

    net.transfer(TO_ACCOUNT,
                 ASSET_AMOUNT,
                 ASSET_NAME,
                 'memo string',
                 account=acc)
Beispiel #12
0
def list_accounts(bitshares_instance):
    """ Get all accounts installed in local wallet in format suitable for Whiptail.menu()

        Returning format is compatible both with Whiptail and NoWhiptail.

        :return: list of tuples (int, 'account_name - key_type')
    """
    accounts = []
    pubkeys = bitshares_instance.wallet.getPublicKeys(current=True)

    for pubkey in pubkeys:
        account_ids = bitshares_instance.wallet.getAccountsFromPublicKey(pubkey)
        for account_id in account_ids:
            account = Account(account_id, bitshares_instance=bitshares_instance)
            key_type = bitshares_instance.wallet.getKeyType(account, pubkey)
            accounts.append({'name': account.name, 'type': key_type})

    account_list = [
        (str(num), '{} - {}'.format(account['name'], account['type'])) for num, account in enumerate(accounts)
    ]
    return account_list
def main():
    parser = argparse.ArgumentParser(description='Show multiple accounts ids',
                                     epilog='Report bugs to: ')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),
    parser.add_argument('-c',
                        '--config',
                        default='./config.yml',
                        help='specify custom path for config file')
    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.safe_load(ymlfile)

    bitshares = BitShares(node=conf['node_bts'], no_broadcast=True)

    if not conf['my_accounts']:
        log.critical(
            'You need to list your accounts in "my_accounts" config variable')
        sys.exit(1)

    ids = ''
    for account_name in conf['my_accounts']:
        account = Account(account_name, bitshares_instance=bitshares)
        ids += '"{}" '.format((account['id']))

    print(ids)
Beispiel #14
0
def get_all_account_balances(api_key: hug.types.text, hug_timer=60):
    """Retrieve all Bitshares account names & balances.
       WARNING: This may take hours to complete! """
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        chain = Blockchain()
        chain_get_all_accounts = chain.get_all_accounts()

        list_of_accounts = []

        for account in chain_get_all_accounts:
            target_account_balances = Account(account).balances
            if (len(target_account_balances) > 0):
                balance_json_list = []
                for balance in target_account_balances:
                    current_balance_target = Amount(balance)
                    balance_json_list.append({
                        current_balance_target.symbol:
                        current_balance_target.amount
                    })

                list_of_accounts.append({
                    'account_name': account,
                    'balances': balance_json_list
                })
            else:
                list_of_accounts.append({
                    'account_name': account,
                    'balances': []
                })

        return {
            'accounts': list_of_accounts,
            'num_accounts': len(list_of_accounts),
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
Beispiel #15
0
def openorders(ctx, account):
    account = Account(
        account or config["default_account"],
        bitshares_instance=ctx.bitshares
    )
    t = PrettyTable([
        "Price",
        "Quote",
        "Base",
        "ID"
    ])
    t.align = "r"
    for o in account.openorders:
        t.add_row([
            "{:f} {}/{}".format(
                o["price"],
                o["base"]["asset"]["symbol"],
                o["quote"]["asset"]["symbol"]),
            str(o["quote"]),
            str(o["base"]),
            o["id"]])
    click.echo(t)
Beispiel #16
0
def account_balances(account_name: hug.types.text, api_key: hug.types.text, request, hug_timer=5):
	"""Bitshares account balances! Simply supply an account name & provide the API key!"""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'account_balances')

		try:
		  target_account = Account(account_name, full=True)
		except:
		  print("Account doesn't exist.")
		  return {'valid_account': False,
				  'account': account_name,
				  'valid_key': True,
				  'took': float(hug_timer)}

		target_account_balances = target_account.balances
		if (len(target_account_balances) > 0):

			balance_json_list = {}
			for balance in target_account_balances:
			  current_balance_target = Amount(balance)
			  balance_json_list[current_balance_target.symbol] = current_balance_target.amount

			return {'balances': balance_json_list,
					'account_has_balances': True,
					'account': account_name,
					'valid_account': True,
					'valid_key': True,
					'took': float(hug_timer)}
		else:
			return {'account_has_balances': False,
					'account': account_name,
					'valid_account': True,
					'valid_key': True,
					'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
def account_callpositions(account_name: hug.types.text,
                          api_key: hug.types.text,
                          hug_timer=5):
    """Bitshares account call positions! Simply supply an account name & provide the API key!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID

        try:
            target_account = Account(account_name)
        except:
            print("Account doesn't exist.")
            return {
                'valid_account': False,
                'account': account_name,
                'valid_key': True,
                'took': float(hug_timer)
            }

        target_account_callpos = target_account.callpositions
        if (len(target_account_callpos) > 0):
            return {
                'call_positions': target_account_callpos,
                'account_has_call_positions': True,
                'account': account_name,
                'valid_account': True,
                'valid_key': True,
                'took': float(hug_timer)
            }
        else:
            return {
                'account_has_call_positions': False,
                'account': account_name,
                'valid_account': True,
                'valid_key': True,
                'took': float(hug_timer)
            }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
Beispiel #18
0
def cloneaccount(ctx, account_name, account):
    """ Clone an account

        This copies the owner and active permissions as well as the
        options (e.g. votes, memo key)
    """
    from bitsharesbase import transactions, operations
    account = Account(account)
    op = {
        "fee": {"amount": 0, "asset_id": "1.3.0"},
        "registrar": account["id"],
        "referrer": account["id"],
        "referrer_percent": 100,
        "name": account_name,
        'owner': account["owner"],
        'active': account["active"],
        "options": account["options"],
        "extensions": {},
        "prefix": ctx.bitshares.rpc.chain_params["prefix"]
    }
    op = operations.Account_create(**op)
    print_tx(ctx.bitshares.finalizeOp(op, account, "active"))
Beispiel #19
0
def history(ctx, account, limit, type, csv, exclude, raw):
    """ Show history of an account
    """
    from bitsharesbase.operations import getOperationNameForId
    t = [["#", "time (block)", "operation", "details"]]

    for a in account:
        account = Account(a, bitshares_instance=ctx.bitshares)
        for b in account.history(
            limit=limit,
            only_ops=type,
            exclude_ops=exclude
        ):
            block = BlockHeader(b["block_num"])
            row = [
                b["id"].split(".")[2],
                "%s (%s)" % (block.time(), b["block_num"]),
                "{} ({})".format(getOperationNameForId(b["op"][0]), b["op"][0]),
                pprintOperation(b) if not raw else json.dumps(b, indent=4),
            ]
            t.append(row)
    print_table(t)
Beispiel #20
0
def find_witness(witness_name: hug.types.text,
                 api_key: hug.types.text,
                 hug_timer=5):
    """Given a valid witness name, output witness data in JSON."""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        try:
            target_witness = Witness(witness_name)
        except:
            # Market is not valid
            return {
                'valid_witness': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        target_account = Account(target_witness['witness_account'], full=True)
        witness_account_data = extract_object(target_account)
        witness_role_data = extract_object(target_witness)

        active_witnesses = Blockchain().config()['active_witnesses']

        if witness_role_data['id'] in active_witnesses:
            witness_status = True
        else:
            witness_status = False

        return {
            'witness_role_data': witness_role_data,
            'witness_account_data': witness_account_data,
            'active_witness': witness_status,
            'valid_witness': True,
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
Beispiel #21
0
def account_history(account_name: hug.types.text, api_key: hug.types.text, request, hug_timer=5):
	"""Given a valid account name, output the user's history in JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'account_history')

		try:
		  target_account = Account(account_name)
		except:
		  # Accoun is not valid!
		  return {'valid_account': False,
				  'account': account_name,
				  'valid_key': True,
				  'took': float(hug_timer)}

		target_account_history = target_account.history(first=0, last=100, limit=100)

		tx_container = []
		for transaction in target_account_history:
		  tx_container.append(transaction)

		if (len(tx_container) > 0):
			return {'tx_history': tx_container,
					'account_has_tx_history': True,
					'account': account_name,
					'valid_account': True,
					'valid_key': True,
					'took': float(hug_timer)}
		else:
			return {'account_has_tx_history': False,
					'account': account_name,
					'valid_account': True,
					'valid_key': True,
					'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
Beispiel #22
0
def history(ctx, account, limit, type, csv, exclude, raw, memo):
    """ Show history of an account
    """
    from bitsharesbase.operations import getOperationNameForId

    if memo:
        pwd = click.prompt("Current Wallet Passphrase", hide_input=True)
        ctx.bitshares.wallet.unlock(pwd)

    t = [["#", "time (block)", "operation", "details"]]

    for a in account:
        account = Account(a, bitshares_instance=ctx.bitshares)
        for b in tqdm(account.history(limit=limit, only_ops=type, exclude_ops=exclude)):
            block = BlockHeader(b["block_num"])
            row = [
                b["id"],
                "%s (%s)" % (block.time(), b["block_num"]),
                "{} ({})".format(getOperationNameForId(b["op"][0]), b["op"][0]),
                pprintOperation(b, memo, ctx) if not raw else json.dumps(b, indent=4),
            ]
            t.append(row)
    print_table(t)
Beispiel #23
0
def get_worker(worker_id: hug.types.text,
               api_key: hug.types.text,
               hug_timer=15):
    """Retrieve a specific worker proposal & the details of the worker's account."""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        if '1.14' not in worker_id:
            return {
                'valid_worker': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        try:
            target_worker = bitshares_api_node.rpc.get_objects([worker_id])[0]
        except:
            return {
                'valid_worker': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        target_account = Account(target_worker['worker_account'], full=True)

        target_account_data = extract_object(target_account)

        target_worker['worker_account_details'] = target_account_data

        return {
            'worker': target_worker,
            'valid_worker': True,
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
Beispiel #24
0
def addkey(ctx, key):
    """ Add a private key to the wallet
    """
    if not key:
        while True:
            key = click.prompt(
                "Private Key (wif) [Enter to quit]",
                hide_input=True,
                show_default=False,
                default="exit"
            )
            if not key or key == "exit":
                break
            try:
                ctx.bitshares.wallet.addPrivateKey(key)
            except Exception as e:
                click.echo(str(e))
                continue
    else:
        for k in key:
            try:
                ctx.bitshares.wallet.addPrivateKey(k)
            except Exception as e:
                click.echo(str(e))

    installedKeys = ctx.bitshares.wallet.getPublicKeys()
    if len(installedKeys) == 1:
        name = ctx.bitshares.wallet.getAccountFromPublicKey(installedKeys[0])
        if name:  # only if a name to the key was found
            account = Account(name, bitshares_instance=ctx.bitshares)
            click.echo("=" * 30)
            click.echo("Setting new default user: %s" % account["name"])
            click.echo()
            click.echo("You can change these settings with:")
            click.echo("    uptick set default_account <account>")
            click.echo("=" * 30)
            config["default_account"] = account["name"]
Beispiel #25
0
 def test_create_asset(self):
     symbol = "FOOBAR"
     precision = 7
     max_supply = 100000
     description = "Test asset"
     is_bitasset = True
     market_fee_percent = 0.1
     max_market_fee = 10
     blacklist_authorities = ["init1"]
     blacklist_authorities_ids = [
         Account(a)["id"] for a in blacklist_authorities
     ]
     blacklist_markets = ["BTS"]
     blacklist_markets_ids = ["1.3.0"]
     permissions = {
         "charge_market_fee": True,
         "white_list": True,
         "override_authority": True,
         "transfer_restricted": True,
         "disable_force_settle": True,
         "global_settle": True,
         "disable_confidential": True,
         "witness_fed_asset": True,
         "committee_fed_asset": True,
     }
     flags = {
         "charge_market_fee": False,
         "white_list": False,
         "override_authority": False,
         "transfer_restricted": False,
         "disable_force_settle": False,
         "global_settle": False,
         "disable_confidential": False,
         "witness_fed_asset": False,
         "committee_fed_asset": False,
     }
     tx = bitshares.create_asset(
         symbol,
         precision,
         max_supply,
         market_fee_percent=market_fee_percent,
         max_market_fee=max_market_fee,
         description=description,
         is_bitasset=is_bitasset,
         blacklist_authorities=blacklist_authorities,
         blacklist_markets=blacklist_markets,
         permissions=permissions,
         flags=flags,
     )
     self.assertEqual(getOperationNameForId(tx["operations"][0][0]),
                      "asset_create")
     op = tx["operations"][0][1]
     self.assertEqual(op["issuer"], "1.2.100")
     self.assertEqual(op["symbol"], symbol)
     self.assertEqual(op["precision"], precision)
     self.assertEqual(op["common_options"]["max_supply"],
                      int(max_supply * 10**precision))
     self.assertEqual(op["common_options"]["market_fee_percent"],
                      int(market_fee_percent * 100))
     self.assertEqual(
         op["common_options"]["max_market_fee"],
         int(max_market_fee * 10**precision),
     )
     self.assertEqual(op["common_options"]["description"], description)
     self.assertEqual(op["common_options"]["blacklist_authorities"],
                      blacklist_authorities_ids)
     self.assertEqual(op["common_options"]["blacklist_markets"],
                      blacklist_markets_ids)
     self.assertEqual(todict(op["common_options"]["issuer_permissions"]),
                      permissions)
     self.assertEqual(todict(op["common_options"]["flags"]), flags)
Beispiel #26
0
    def __init__(self,
                 name,
                 config=None,
                 onAccount=None,
                 onOrderMatched=None,
                 onOrderPlaced=None,
                 onMarketUpdate=None,
                 onUpdateCallOrder=None,
                 ontick=None,
                 bitshares_instance=None,
                 *args,
                 **kwargs):
        # BitShares instance
        self.bitshares = bitshares_instance or shared_bitshares_instance()

        # Storage
        Storage.__init__(self, name)

        # Statemachine
        StateMachine.__init__(self, name)

        # Events
        Events.__init__(self)

        if ontick:
            self.ontick += ontick
        if onMarketUpdate:
            self.onMarketUpdate += onMarketUpdate
        if onAccount:
            self.onAccount += onAccount
        if onOrderMatched:
            self.onOrderMatched += onOrderMatched
        if onOrderPlaced:
            self.onOrderPlaced += onOrderPlaced
        if onUpdateCallOrder:
            self.onUpdateCallOrder += onUpdateCallOrder

        # Redirect this event to also call order placed and order matched
        self.onMarketUpdate += self._callbackPlaceFillOrders

        if config:
            self.config = config
        else:
            self.config = config = Config.get_worker_config_file(name)

        self.worker = config["workers"][name]
        self._account = Account(self.worker["account"],
                                full=True,
                                bitshares_instance=self.bitshares)
        self._market = Market(config["workers"][name]["market"],
                              bitshares_instance=self.bitshares)

        # Recheck flag - Tell the strategy to check for updated orders
        self.recheck_orders = False

        # Settings for bitshares instance
        self.bitshares.bundle = bool(self.worker.get("bundle", False))

        # Disabled flag - this flag can be flipped to True by a worker and
        # will be reset to False after reset only
        self.disabled = False

        # A private logger that adds worker identify data to the LogRecord
        self.log = logging.LoggerAdapter(
            logging.getLogger('dexbot.per_worker'), {
                'worker_name': name,
                'account': self.worker['account'],
                'market': self.worker['market'],
                'is_disabled': lambda: self.disabled
            })

        self.orders_log = logging.LoggerAdapter(
            logging.getLogger('dexbot.orders_log'), {})
Beispiel #27
0
    def __init__(self,
                 name,
                 config=None,
                 onAccount=None,
                 onOrderMatched=None,
                 onOrderPlaced=None,
                 onMarketUpdate=None,
                 onUpdateCallOrder=None,
                 ontick=None,
                 bitshares_instance=None,
                 *args,
                 **kwargs):

        # BitShares instance
        self.bitshares = bitshares_instance or shared_bitshares_instance()

        # Storage
        Storage.__init__(self, name)

        # Events
        Events.__init__(self)

        if ontick:
            self.ontick += ontick
        if onMarketUpdate:
            self.onMarketUpdate += onMarketUpdate
        if onAccount:
            self.onAccount += onAccount
        if onOrderMatched:
            self.onOrderMatched += onOrderMatched
        if onOrderPlaced:
            self.onOrderPlaced += onOrderPlaced
        if onUpdateCallOrder:
            self.onUpdateCallOrder += onUpdateCallOrder

        # Redirect this event to also call order placed and order matched
        self.onMarketUpdate += self._callbackPlaceFillOrders

        self.assets_intersections_data = None
        if config:
            self.config = config
            self.assets_intersections_data = Config.assets_intersections(
                config)
        else:
            self.config = config = Config.get_worker_config_file(name)

        # Get worker's parameters from the config
        self.worker = config["workers"][name]

        # Recheck flag - Tell the strategy to check for updated orders
        self.recheck_orders = False

        # Count of orders to be fetched from the API
        self.fetch_depth = 8

        # What percent of balance the worker should use
        self.operational_percent_quote = self.worker.get(
            'operational_percent_quote', 0) / 100
        self.operational_percent_base = self.worker.get(
            'operational_percent_base', 0) / 100

        # Get Bitshares account and market for this worker
        self._account = Account(self.worker["account"],
                                full=True,
                                bitshares_instance=self.bitshares)
        self._market = Market(config["workers"][name]["market"],
                              bitshares_instance=self.bitshares)

        # Set fee asset
        fee_asset_symbol = self.worker.get('fee_asset')

        if fee_asset_symbol:
            try:
                self.fee_asset = Asset(fee_asset_symbol,
                                       bitshares_instance=self.bitshares)
            except bitshares.exceptions.AssetDoesNotExistsException:
                self.fee_asset = Asset('1.3.0',
                                       bitshares_instance=self.bitshares)
        else:
            # If there is no fee asset, use BTS
            self.fee_asset = Asset('1.3.0', bitshares_instance=self.bitshares)

        # CER cache
        self.core_exchange_rate = None

        # Ticker
        self.ticker = self._market.ticker

        # Settings for bitshares instance
        self.bitshares.bundle = bool(self.worker.get("bundle", False))

        # Disabled flag - this flag can be flipped to True by a worker and will be reset to False after reset only
        self.disabled = False

        # Order expiration time in seconds
        self.expiration = 60 * 60 * 24 * 365 * 5

        # buy/sell actions will return order id by default
        self.returnOrderId = 'head'

        # A private logger that adds worker identify data to the LogRecord
        self.log = logging.LoggerAdapter(
            logging.getLogger('dexbot.per_worker'), {
                'worker_name': name,
                'account': self.worker['account'],
                'market': self.worker['market'],
                'is_disabled': lambda: self.disabled
            })

        self.orders_log = logging.LoggerAdapter(
            logging.getLogger('dexbot.orders_log'), {})
 def getProducer(self):
     """ Get the feed producers account
     """
     self.producer = Account(self.config["producer"])
Beispiel #29
0
 def test_calls(self):
     account = Account("init0")
     self.assertIsInstance(account.callpositions, dict)
def main():
    def convert_asset(from_value, from_asset, to_asset):
        """ Converts asset to another based on the latest market value

            :param float | from_value: Amount of the input asset
            :param string | from_asset: Symbol of the input asset
            :param string | to_asset: Symbol of the output asset
            :return: float Asset converted to another asset as float value
        """
        market = Market('{}/{}'.format(from_asset, to_asset),
                        bitshares_instance=bitshares)
        ticker = market.ticker()
        latest_price = ticker.get('latest', {}).get('price', None)
        precision = market['base']['precision']

        return round((from_value * latest_price), precision)

    def transform_asset(sum_balances, from_asset, to_asset):
        """ In sum_balances dict, convert one asset into another

            :param dict | sum_balances: dict with balances
            :param str | from_asset: asset to convert from
            :param str | to_asset: destination asset
        """
        if from_asset in sum_balances:
            amount = convert_asset(sum_balances[from_asset], from_asset,
                                   to_asset)
            sum_balances[from_asset] = 0
            if to_asset in sum_balances:
                sum_balances[to_asset] += amount
            else:
                sum_balances[to_asset] = amount
        return sum_balances

    parser = argparse.ArgumentParser(
        description=
        'Summarize all assets on all accounts and show BTC equivalent',
        epilog='Report bugs to: ')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),
    parser.add_argument('-c',
                        '--config',
                        default='./config.yml',
                        help='specify custom path for config file')
    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.safe_load(ymlfile)

    bitshares = BitShares(node=conf['node_bts'], no_broadcast=True)

    sum_balances = dict()

    for acc in conf['my_accounts']:
        account = Account(acc, bitshares_instance=bitshares)

        # Avail balances
        for i in account.balances:
            asset = i['symbol']
            sum_balances[asset] = sum_balances.setdefault(asset,
                                                          0) + i['amount']

        # Balance in orders
        for order in account.openorders:
            asset = order['for_sale']['symbol']
            sum_balances[asset] = sum_balances.setdefault(
                asset, 0) + order['for_sale']['amount']

        # Margin positions
        for asset, details in account.callpositions.items():
            sum_balances[asset] = sum_balances.setdefault(
                asset, 0) - details['debt']['amount']

            asset = details['collateral']['asset']['symbol']
            sum_balances[asset] = sum_balances.setdefault(
                asset, 0) + details['collateral']['amount']

    for asset, amount in sum_balances.items():
        log.debug('Total: {} {}'.format(asset, amount))

    for from_asset, to_asset in conf['transform_assets'].items():
        log.debug('Transforming {} to {}'.format(from_asset, to_asset))
        sum_balances = transform_asset(sum_balances, from_asset, to_asset)

    for asset, amount in sum_balances.items():
        if amount > 0 and asset != conf['btc_asset']:
            log.info('Using direct conversion {:.8f} {} -> {}'.format(
                amount, asset, conf['btc_asset']))
            sum_balances = transform_asset(sum_balances, asset,
                                           conf['btc_asset'])

    print('Accounts value in {}: {:.8f}'.format(
        conf['btc_asset'], sum_balances[conf['btc_asset']]))