def flood(ctx, account, ops, txs, to): from bitsharesbase.operations import Transfer from bitshares.transactionbuilder import TransactionBuilder assert ctx.bitshares.rpc.chain_params[ "prefix"] == "TEST", "Flooding only on the testnet. Please switch the API to node testnet.bitshares.eu" account = Account(account, bitshares_instance=ctx.bitshares) to_account = Account(to, bitshares_instance=ctx.bitshares) tx = TransactionBuilder(bitshares_instance=ctx.bitshares) txcnt = 0 while txcnt < txs or txs < 0: txcnt += 1 for j in range(0, ops): tx.appendOps( Transfer( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "from": account["id"], "to": to_account["id"], "amount": { "amount": 1, "asset_id": "1.3.0" }, "memo": None })) tx.appendSigner(account, "active") tx.broadcast() click.echo(tx["signatures"])
def remove_authorities(self, type, authorities=[]): """ Remove authorities from an assets white/black list :param str type: ``blacklist`` or ``whitelist`` :param list authorities: List of authorities (Accounts) """ assert type in ["blacklist", "whitelist"] assert isinstance(authorities, (list, set)) options = self["options"] if type == "whitelist": for a in authorities: options["whitelist_authorities"].remove(Account(a)["id"]) if type == "blacklist": for a in authorities: options["blacklist_authorities"].remove(Account(a)["id"]) op = operations.Asset_update( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [] }) return self.bitshares.finalizeOp(op, self["issuer"], "active")
def history(ctx, account, limit, type, csv, exclude): from bitsharesbase.operations import getOperationNameForId header = ["#", "time (block)", "operation", "details"] if csv: import csv t = csv.writer(sys.stdout, delimiter=";") t.writerow(header) else: t = PrettyTable(header) t.align = "r" t.align["details"] = "l" for a in account: account = Account(a, bitshares_instance=ctx.bitshares) for b in account.rawhistory(limit=limit, only_ops=type, exclude_ops=exclude): row = [ b["id"].split(".")[2], "%s" % (b["block_num"]), "{} ({})".format(getOperationNameForId(b["op"][0]), b["op"][0]), pprintOperation(b), ] if csv: t.writerow(row) else: t.add_row(row) if not csv: click.echo(t)
def cloneaccount(ctx, account_name, account, feepayer): """ 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) if feepayer is None: feepayer = account else: feepayer = Account(feepayer) op = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "registrar": feepayer["id"], "referrer": feepayer["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"))
def appendTransferOpToTx(builder, from_name, to_name, amount, symbol): ## TODO: Cleanup exception catching for better user feedback try: account = Account(from_name, blockchain_instance=blockchain) amountAsset = Amount(amount, symbol, blockchain_instance=blockchain) to = Account(to_name, blockchain_instance=blockchain) except NumRetriesReached: Logger.Write("ERROR: Can't reach API node: 'NumRetries' reached. Check network connection.") raise except: Logger.Write("Problem locating source or destination account, or asset. Might not exist.") raise memoObj = Memo(from_account=account, to_account=to, blockchain_instance=blockchain) memo_text = "" #"Signed by BitShares App on Ledger Nano S!" op = operations.Transfer( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "from": account["id"], "to": to["id"], "amount": {"amount": int(amountAsset), "asset_id": amountAsset.asset["id"]}, "memo": memoObj.encrypt(memo_text), } ) builder.appendOps(op) return builder
def postprocess_operation(self, operation): """ This method only obtains operations that are relevant for us. It tries to decode the memo and sends all the relevant information to the storage for insertion into the database. :param dict operation: operation as dictionary """ payload = operation["op"][1] operation.update({ "from_name": Account( payload["from"], bitshares_instance=self.bitshares )["name"], "to_name": Account( payload["to"], bitshares_instance=self.bitshares )["name"], "decoded_memo": self.decode_memo(payload), }) logging.getLogger(__name__).debug("Recognized accounts, inserting transfer " + str(operation["transaction_id"])) try: self.storage.insert_or_update_operation(operation) except DuplicateOperationException: logging.getLogger(__name__).debug("Storage already contained operation, skipping ...")
def _setupvesting(): creator = Account("foundation") owner = Account("init0") amount = Amount("10000000 DNA") op = operations.Vesting_balance_create( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "creator": creator["id"], "owner": owner["id"], "amount": amount.json(), "policy": [3, { "duration": 60 * 60 * 24 * 365 }], "extensions": [], }) try: click.echo(blockchain.finalizeOp(op, creator, "active")) click.echo("Vested!") except Exception as e: click.echo(click.style(str(e), fg="red"))
def validate_private_key(self, account, private_key): """ Check whether private key is associated with account :param str account: bitshares account name :param str private_key: private key """ wallet = self.bitshares.wallet if not private_key: # Check if the account is already in the database account_ids = wallet.getAccounts() accounts = [ Account(account_id, bitshares_instance=self.bitshares) for account_id in account_ids ] if any(account == account['name'] for account in accounts): return True return False try: pubkey = format( PrivateKey(private_key).pubkey, self.bitshares.prefix) except ValueError: return False # Load all accounts with corresponding public key from the blockchain account_ids = wallet.getAccountsFromPublicKey(pubkey) account_names = [ Account(account_id, bitshares_instance=self.bitshares).name for account_id in account_ids ] if account in account_names: return True else: return False
def proposals(ctx, account): """ List proposals """ proposals = Proposals(account) t = PrettyTable([ "id", "expiration", "required approvals", "available approvals", "review period time", "proposal", ]) t.align = 'l' for proposal in proposals: t.add_row([ proposal["id"], proposal["expiration_time"], [ Account(x)["name"] for x in (proposal["required_active_approvals"] + proposal["required_owner_approvals"]) ], json.dumps([ Account(x)["name"] for x in proposal["available_active_approvals"] ] + proposal["available_key_approvals"] + proposal["available_owner_approvals"], indent=1), proposal.get("review_period_time", None), json.dumps(proposal["proposed_transaction"], indent=4), ]) click.echo(str(t))
def parse_transfer_entry(self, entry): """ Parse single transfer entry into a dict object suitable for writing line :param dict entry: elastic wrapper entry :return: dict object suitable for writing line """ op_id = entry['account_history']['operation_id'] op_date = entry['block_data']['block_time'] op = self.load_op(entry) data = copy.deepcopy(LINE_DICT_TEMPLATE) raw_amount = op['amount'] if 'amount' in op else op['amount_'] amount = Amount(raw_amount, bitshares_instance=self.bitshares) from_account = Account(op['from'], bitshares_instance=self.bitshares) to_account = Account(op['to'], bitshares_instance=self.bitshares) fee = Amount(op['fee'], bitshares_instance=self.bitshares) log.info('Transfer: {} -> {}, {}'.format(from_account.name, to_account.name, amount)) if from_account.name == self.account.name: data['kind'] = 'Withdrawal' data['sell_cur'] = amount.symbol data['sell_amount'] = amount.amount data['fee_cur'] = fee.symbol data['fee_amount'] = fee.amount else: data['kind'] = 'Deposit' data['buy_cur'] = amount.symbol data['buy_amount'] = amount.amount data['comment'] = op_id data['date'] = op_date return data
def proposals(ctx, account): """ List proposals """ proposals = Proposals(account) t = [[ "id", "expiration", "required approvals", "available approvals", "review period time", "proposal", ]] for proposal in proposals: t.append([ proposal["id"], proposal["expiration_time"], [Account(x)["name"] for x in ( proposal["required_active_approvals"] + proposal["required_owner_approvals"] )], json.dumps( [Account(x)["name"] for x in proposal["available_active_approvals"]] + proposal["available_key_approvals"] + proposal["available_owner_approvals"], indent=1), proposal.get("review_period_time", None), format_json(proposal["proposed_transaction"], indent=4), ]) print_table(t)
def main(): ''' filename = "data.csv" #str(datetime.date()) f = open(filename, 'a') #f.write(HEADER) ''' account = Account(accountName) ''' market = Market("OPEN.ETH:BTS") for i in range(0, len(account.balances)): print (str(account.balances[i]).replace(' ',','), end =",") print (str(market.ticker()["latest"]).replace(' ', ','), end =",") ''' print(account.balances) print(account.openorders) i = 0 #1 this method not pulling past 100 operation event with limit set to for j in range(0, 10): for h in account.history(first=i): print(h) print(str(i)) i += 1 #2 not working for pulling all the trades, for some reason it keeps stopping at like 120 trades??? # How can I get them all? #for h in Market("BTS:OPEN.ETH").accounttrades( account=account, limit=10000000 ): # print(h) print("hi")
def pprintOperation(op): from bitshares.price import Order, FilledOrder id = op["op"][0] op = op["op"][1] if id == 1: return str(Order(op)) elif id == 4: return str(FilledOrder(op)) elif id == 5: return "New account created for {}".format(op["name"]) elif id == 2: return "Canceled order %s" % op["order"] elif id == 6: return "Account {} updated".format(Account(op["account"])["name"]) elif id == 33: return "Claiming from vesting: %s" % str(Amount(op["amount"])) elif id == 15: return "Reserve {}".format(str(Amount(op["amount_to_reserve"]))) elif id == 0: from_account = Account(op["from"]) to_account = Account(op["to"]) amount = Amount(op["amount"]) return "Transfer from {from_account[name]} to {to_account[name]}: {amount}".format( **locals()) else: return format_dict(op)
def test_unlist(self): from bitsharesbase.operations import Account_whitelist account = Account("witness-account") tx = account.nolist("committee-account") self.assertEqual(len(tx["operations"]), 1) self.assertEqual(tx["operations"][0][0], 7) self.assertEqual(tx["operations"][0][1]["authorizing_account"], account["id"]) self.assertEqual(tx["operations"][0][1]["new_listing"], Account_whitelist.no_listing)
def balances_bit_shares(config, secrets_json, source, scopeTickers): printSource = '' # this is cleaner than passing printSource as a param. if not config.VERBOSE: printSource = source+"\n " # VERBOSE already printed it. from bitshares import BitShares amounts = BitShares(config, secrets_json['account']) for key, value in amounts.items(): if not scopeTickers or key in scopeTickers: printBalance(printSource, key, value) printSource = ' ' try: # bitshares.account will work under Python3, but throw exception if Python2 from bitshares.account import Account account = Account(secrets_json['account']) print (account.json()) # We add the balances and open-orders amounts, since we still own unfilled open-orders amounts = { } for balance in account.balances: ticker = balance.symbol.replace('BRIDGE.','') if ticker not in amounts: amounts[ticker] = 0 amounts[ticker] += balance.amount for openorder in account.openorders: order = openorder['base'] ticker = order.symbol.replace('BRIDGE.','') if ticker not in amounts: amounts[ticker] = 0 amounts[ticker] += order.amount for key, value in amounts.items(): if not scopeTickers or key in scopeTickers: printBalance(printSource, key, value) printSource = ' ' return '' except KeyboardInterrupt as ex: raise KeyboardInterrupt() except: ex = sys.exc_info()[0] if config.VERBOSE: print( "Exception in balances.balances_bit_shares(): "+str(ex), file=sys.stderr ) proc = subprocess.Popen(['/opt/mining/mining/balances/bit-shares.py', source], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) out, err = proc.communicate(None) if err: print(err,file=sys.stderr) return out = out.decode('utf-8') lines = out.splitlines() # "[0.00001017 BRIDGE.BTC, 162.1362 BRIDGE.RVN]" line = lines[0].replace('[','').replace(']','') vals = line.split(", ") for val in vals: val_coin = val.split(' ') value = val_coin[0] ticker = val_coin[1].replace('BRIDGE.','') if not scopeTickers or ticker in scopeTickers: #print(' '+ticker + " " + value) printBalance(printSource, ticker, float(value.replace(',',''))) printSource = ' '
def test_account_upgrade(self): account = Account("init0") pprint(account) tx = account.upgrade() ops = tx["operations"] op = ops[0][1] self.assertEqual(len(ops), 1) self.assertEqual(getOperationNameForId(ops[0][0]), "account_upgrade") self.assertTrue(op["upgrade_to_lifetime_member"]) self.assertEqual(op["account_to_upgrade"], "1.2.100")
def witnesses(self): voter = self.config.get("voter") if not voter: return [] witnesses = list() account = Account(voter, full=True) for vote in account["votes"]: if "witness_account" not in vote: continue witnesses.append(Account(vote["witness_account"])["name"]) return witnesses
def __init__(self, config, name, 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 self.config = config self.bot = config["bots"][name] self._account = Account(self.bot["account"], full=True, bitshares_instance=self.bitshares) self._market = Market(config["bots"][name]["market"], bitshares_instance=self.bitshares) # Settings for bitshares instance self.bitshares.bundle = bool(self.bot.get("bundle", False)) # disabled flag - this flag can be flipped to True by a bot and # will be reset to False after reset only self.disabled = False
def account_info_refresh(): try: spending_account = Account(var_from_account_name.get(), blockchain_instance=blockchain) balances = spending_account.balances history = spending_account.history(limit=40) account_id = spending_account.identifier except AccountDoesNotExistsException: Logger.Write("ERROR: Specified account does not exist on BitShares network.") balances = [] history = [] account_id = "" frameAssets.setBalances(balances) frameHistory.setHistory(history, account_id)
def release( self, whitelist_authorities=[], blacklist_authorities=[], whitelist_markets=[], blacklist_markets=[], ): """ Release this asset and allow unrestricted transfer, trading, etc. :param list whitelist_authorities: List of accounts that serve as whitelist authorities :param list blacklist_authorities: List of accounts that serve as blacklist authorities :param list whitelist_markets: List of assets to allow trading with :param list blacklist_markets: List of assets to prevent trading with """ flags = { "white_list": False, "transfer_restricted": False, } options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update({ "flags": flags_int, "whitelist_authorities": [Account(a)["id"] for a in whitelist_authorities], "blacklist_authorities": [Account(a)["id"] for a in blacklist_authorities], "whitelist_markets": [Asset(a)["id"] for a in whitelist_markets], "blacklist_markets": [Asset(a)["id"] for a in blacklist_markets], }) op = operations.Asset_update( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [] }) return self.blockchain.finalizeOp(op, self["issuer"], "active")
def account_is_ltm(account_name: hug.types.text, api_key: hug.types.text, request, hug_timer=5): """Given a valid account name, check if they're LTM & output confirmation as JSON.""" if (check_api_token(api_key) == True): # Check the api key # API KEY VALID google_analytics(request, 'account_is_ltm') 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_ltm = target_account.is_ltm return {'account_is_ltm': target_account_ltm, '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 call_order_update(inst, delta_collateral, delta_debt, account=None): """ call_order_update :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) kwargs = { 'fee': { "amount": 0, "asset_id": "1.3.0" }, 'funding_account': account["id"], 'delta_collateral': delta_collateral, 'delta_debt': delta_debt, } op = operations.Call_order_update(**kwargs) return inst.finalizeOp(op, account, "active")
def initiate_crowdfund(inst, asset_id, t, u, account=None): """ initiate_crowdfund :param str account: the account to cancel to (defaults to ``default_account``) :param str balance object: the balance object to cancel """ 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) kwargs = { "fee": { "amount": 0, "asset_id": "1.3.0" }, "owner": account["id"], "asset_id": asset_id, "t": t, "u": u } op = operations.Initiate_crowdfund(**kwargs) return inst.finalizeOp(op, account, "active")
def participate_crowdfund(inst, crowdfund, valuation, cap, account=None): """ participate_crowdfund :param str account: the account to cancel to (defaults to ``default_account``) :param str balance object: the balance object to cancel """ 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) kwargs = { "fee": { "amount": 0, "asset_id": "1.3.0" }, "buyer": account["id"], "valuation": valuation, "cap": cap, "crowdfund": crowdfund } op = operations.Participate_crowdfund(**kwargs) return inst.finalizeOp(op, account, "active")
def cancel_vesting(inst, balance_object, account=None): """ cancel_vesting :param str account: the account to cancel to (defaults to ``default_account``) :param str balance object: the balance object to cancel """ 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) kwargs = { "fee": { "amount": 0, "asset_id": "1.3.0" }, "payer": account["id"], "sender": account["id"], "balance_object": balance_object, } op = operations.Cancel_vesting(**kwargs) return inst.finalizeOp(op, account, "active")
def reconnect(BitPAIR, USERNAME, PASS_PHRASE): # create fresh websocket connection connected = 0 while not connected: # fetch fresh nodes list from subprocess and shuffle it nds = race_read('nodes.txt') if isinstance(nds, list): nodes = nds shuffle(nodes) node = nodes[0] try: account = Account(USERNAME, bitshares_instance=BitShares(node, num_retries=0)) market = Market(BitPAIR, bitshares_instance=BitShares(node, num_retries=0), mode='head') chain = Blockchain( bitshares_instance=BitShares(node, num_retries=0), mode='head') if chain.get_network()['chain_id'] != ID: raise ValueError('Not Mainnet Chain') connected = 1 except: pass try: market.bitshares.wallet.unlock(PASS_PHRASE) except: pass return account, market, nodes, chain
def validate_private_key_type(self, account, private_key): account = Account(account) pubkey = format(PrivateKey(private_key).pubkey, self.bitshares.prefix) key_type = self.bitshares.wallet.getKeyType(account, pubkey) if key_type != 'active': return False return True
def __init__( self, config, name, 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 self.config = config self.bot = config["bots"][name] self._account = Account( self.bot["account"], full=True, bitshares_instance=self.bitshares ) self._market = Market( config["bots"][name]["market"], bitshares_instance=self.bitshares ) # Settings for bitshares instance self.bitshares.bundle = bool(self.bot.get("bundle", False)) # disabled flag - this flag can be flipped to True by a bot and # will be reset to False after reset only self.disabled = False
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"]
def order_and_cancel(): 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('your active private key') except Exception as e: pass net.wallet.unlock('your wallet unlock password') account = Account('account name', bitshares_instance=net) market = Market(base=Asset('CYB'), quote=Asset('JADE.ETH'), bitshares_instance=net) # buy 0.001 JADE.ETH at price JADE.ETH:CYB 1000, expire in 60 seconds # market.sell will do the sell operation market.buy(1000, 0.001, 60, False, 'account name', 'Head') # query open orders for order in account.openorders: base_amount = order['base'].amount base_symbol = order['base'].symbol quote_amount = order['quote'].amount quote_symbol = order['quote'].symbol order_number = order['id'] print('{}:{}--{}/{}'.format(quote_symbol, base_symbol, quote_amount, base_amount)) # cancel order market.cancel(order_number, 'account name')
def halt(self): """ Halt this asset from being moved or traded """ nullaccount = Account("null-account") # We set the null-account flags = { "white_list": True, "transfer_restricted": True, } options = self["options"] test_permissions(options["issuer_permissions"], flags) flags_int = force_flag(options["flags"], flags) options.update({ "flags": flags_int, "whitelist_authorities": [nullaccount["id"]], "blacklist_authorities": [], "whitelist_markets": [self["id"]], "blacklist_markets": [], }) op = operations.Asset_update( **{ "fee": { "amount": 0, "asset_id": "1.3.0" }, "issuer": self["issuer"], "asset_to_update": self["id"], "new_options": options, "extensions": [] }) return self.bitshares.finalizeOp(op, self["issuer"], "active")
class BaseStrategy(Storage, StateMachine, Events): """ Base Strategy and methods available in all Sub Classes that inherit this BaseStrategy. BaseStrategy inherits: * :class:`stakemachine.storage.Storage` * :class:`stakemachine.statemachine.StateMachine` * ``Events`` Available attributes: * ``basestrategy.bitshares``: instance of ´`bitshares.BitShares()`` * ``basestrategy.add_state``: Add a specific state * ``basestrategy.set_state``: Set finite state machine * ``basestrategy.get_state``: Change state of state machine * ``basestrategy.account``: The Account object of this bot * ``basestrategy.market``: The market used by this bot * ``basestrategy.orders``: List of open orders of the bot's account in the bot's market * ``basestrategy.balance``: List of assets and amounts available in the bot's account Also, Base Strategy inherits :class:`stakemachine.storage.Storage` which allows to permanently store data in a sqlite database using: ``basestrategy["key"] = "value"`` .. note:: This applies a ``json.loads(json.dumps(value))``! """ __events__ = [ 'ontick', 'onMarketUpdate', 'onAccount', 'error_ontick', 'error_onMarketUpdate', 'error_onAccount', 'onOrderMatched', 'onOrderPlaced', 'onUpdateCallOrder', ] def __init__( self, config, name, 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 self.config = config self.bot = config["bots"][name] self._account = Account( self.bot["account"], full=True, bitshares_instance=self.bitshares ) self._market = Market( config["bots"][name]["market"], bitshares_instance=self.bitshares ) # Settings for bitshares instance self.bitshares.bundle = bool(self.bot.get("bundle", False)) # disabled flag - this flag can be flipped to True by a bot and # will be reset to False after reset only self.disabled = False @property def orders(self): """ Return the bot's open accounts in the current market """ self.account.refresh() return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders] @property def market(self): """ Return the market object as :class:`bitshares.market.Market` """ return self._market @property def account(self): """ Return the full account as :class:`bitshares.account.Account` object! Can be refreshed by using ``x.refresh()`` """ return self._account def balance(self, asset): """ Return the balance of your bot's account for a specific asset """ return self._account.balance(asset) @property def balances(self): """ Return the balances of your bot's account """ return self._account.balances def _callbackPlaceFillOrders(self, d): """ This method distringuishes notifications caused by Matched orders from those caused by placed orders """ if isinstance(d, FilledOrder): self.onOrderMatched(d) elif isinstance(d, Order): self.onOrderPlaced(d) elif isinstance(d, UpdateCallOrder): self.onUpdateCallOrder(d) else: pass def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False return r def cancelall(self): """ Cancel all orders of this bot """ if self.orders: return self.bitshares.cancel( [o["id"] for o in self.orders], account=self.account )
our_account = "id-b0t" our_symbol = "CNY" current_ratio = 0 # наша пара base = Asset(our_symbol) quote = Asset("BTS") # выбираем рынок market = Market(base, quote) # открываем свой локальный кошелек market.bitshares.wallet.unlock("secret_wallet_password") # получаем аккаунт для работы бота account = Account(our_account) print(account) # проверяем есть ли займы по нашему битассету cp = account.callpositions # если есть любые займы if len(cp) > 0: print(cp) # проверяем есть ли по юаню cp2 = cp.get(our_symbol) if cp2 is not None: print(cp2) # получаем коэффициент перекрытия current_ratio = cp2.get('ratio') print(current_ratio)