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 test_default_connection2(self): b1 = BitShares("wss://node.testnet.bitshares.eu", nobroadcast=True) test = Asset("1.3.0", blockchain_instance=b1) test.refresh() b2 = BitShares("wss://node.bitshares.eu", nobroadcast=True) bts = Asset("1.3.0", blockchain_instance=b2) bts.refresh() self.assertEqual(test["symbol"], "TEST") self.assertEqual(bts["symbol"], "X4T")
def reconnect(): global account, market, nodes, chain, pings try: history_text.delete("1.0", "end") history_text.insert(END, '\n\n CONNECTING...') master.update() except: pass print(cyan(time.ctime() + ' CONNECTING...')) start = time.time() # create fresh websocket connection connected = 0 while not connected: # fetch fresh nodes list from subprocess and shuffle it metaNODE = Bitshares_Trustless_Client() nds = metaNODE['whitelist'] del metaNODE if isinstance(nds, list): nodes = nds shuffle(nodes) node = nodes[0] print(green(node)) pings = [0] try: account = Account(USERNAME, bitshares_instance=BitShares(nodes, num_retries=2)) market = Market(BitPAIR, bitshares_instance=BitShares(nodes, num_retries=2), mode='head') chain = Blockchain(bitshares_instance=BitShares(nodes, num_retries=2), mode='head') if chain.get_network()['chain_id'] != ID: raise ValueError('Not Mainnet Chain') connected = 1 except Exception as e: try: history_text.insert(END, '\n\n RECONNECTING...') master.update() except: pass msg = (time.ctime() + str(type(e).__name__) + str(e.args)) print('RECONNECTING ' + msg) pass try: market.bitshares.wallet.unlock(PASS_PHRASE) except: # print('YOUR WALLET IS LOCKED') pass print('CONNECTION ELAPSED: ', ('%.1f' % (time.time() - start)))
def test_bts1bts2(self): b1 = BitShares( "wss://node.testnet.bitshares.eu", nobroadcast=True, ) b2 = BitShares( "wss://node.bitshares.eu", nobroadcast=True, ) self.assertNotEqual(b1.rpc.url, b2.rpc.url)
def test_default_connection(self): b1 = BitShares("wss://node.testnet.bitshares.eu", nobroadcast=True) set_shared_bitshares_instance(b1) test = Asset("1.3.0", blockchain_instance=b1) # Needed to clear cache test.refresh() b2 = BitShares("wss://node.bitshares.eu", nobroadcast=True) set_shared_bitshares_instance(b2) bts = Asset("1.3.0", blockchain_instance=b2) # Needed to clear cache bts.refresh() self.assertEqual(test["symbol"], "TEST") self.assertEqual(bts["symbol"], "BTS")
def main(): parser = argparse.ArgumentParser(description='Print current feeds for asset', 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') parser.add_argument('asset') 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) asset = Asset(args.asset, bitshares_instance=bitshares) feeds = asset.feeds for feed in feeds: print('{}: {}'.format(feed['producer']['name'], feed['settlement_price']))
def test_gateway_handler(self): bitshares = BitShares(settings.BITSHARES_NODE_URL, nobroadcast=settings.BLOCKCHAIN_NOBROADCAST, keys=[settings.BITSHARES_GATEWAY_WIF]) bitshares.set_default_account(settings.BITSHARES_GATEWAY_ACCOUNT) transnet = Transnet(settings.TRANSNET_NODE_URL, nobroadcast=settings.BLOCKCHAIN_NOBROADCAST, keys={ 'active': settings.TRANSNET_GATEWAY_WIF, 'memo': settings.TRANSNET_GATEWAY_WIF_MEMO }) transnet.set_default_account(settings.TRANSNET_GATEWAY_ACCOUNT) transaction = BitsharesTransnetTransaction.objects.create( trx_id='test', trx_in_block=3, op_in_trx=3, asset='UTECH.UTCORE', amount=pow(10, 5), account_external='superpchelka23', account_internal='superpchelka23') handler = BitsharesGatewayHandler(bitshares, settings.BITSHARES_GATEWAY_ACCOUNT, transnet, settings.TRANSNET_GATEWAY_ACCOUNT, settings.TRANSNET_GATEWAY_WIF_MEMO, {'UTECH.UTCORE': 'UTECH.UTCORE'}) handler.handle([transaction], lambda: True) self.assertTrue(transaction.closed, 'Transaction must be properly processed')
def test_account_listener(self): self.bitshares = BitShares(settings.BITSHARES_NODE_URL, nobroadcast=settings.BLOCKCHAIN_NOBROADCAST, keys={ 'active': settings.BITSHARES_GATEWAY_WIF, 'memo': settings.BITSHARES_GATEWAY_WIF_MEMO }) handler = TestAccountListenerHandler() transfers_provider = BitsharesAccountTransfersProvider( self.bitshares, settings.BITSHARES_GATEWAY_WIF_MEMO, settings.BITSHARES_GATEWAY_ACCOUNT, BitsharesTransnetTransaction) transfer_listener = AccountTransfersListener(transfers_provider) transfer_listener.add_handler(handler) threading.Thread(target=lambda: transfer_listener.start()).start() max_waiting_seconds = 15 start_time = now() while not handler.processed and ( now() - start_time).seconds < max_waiting_seconds: pass transfer_listener.stop() self.assertTrue(handler.processed, 'No one transactions were handled')
def remove_offline_worker(config, worker_name): # Initialize the base strategy to get control over the data bitshares_instance = BitShares(config['node']) strategy = BaseStrategy(worker_name, config, bitshares_instance=bitshares_instance) strategy.purge()
def take_offer(self, data): bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head') trade_message = '' new_data = {} if data['market_or_pool'] == 'pool': new_data['operation_type'] = 'Pool Operation' if data['buy_or_sell'] == 'buy': amount_to_sell = Amount(data['expected_price']) new_data['anticipated'] = Amount('{} {}'.format(data['amount_to_buy_sell'], data['selected_asset'])) min_to_receive = new_data['anticipated'] * .993 trade_message = bitshares.exchange_with_liquidity_pool( pool=data['pool_id'], amount_to_sell=amount_to_sell, min_to_receive=min_to_receive, account=data['account'], ) else: amount_to_sell = Amount('{} {}'.format(data['amount_to_buy_sell'], data['selected_asset'])) new_data['anticipated'] = Amount(data['expected_price']) min_to_receive = new_data['anticipated'] * .993 trade_message = bitshares.exchange_with_liquidity_pool( pool=data['pool_id'], amount_to_sell=amount_to_sell, min_to_receive=min_to_receive, account=data['account'], ) new_data['operation_results'] = trade_message['operation_results'] new_data['paid'] = Amount(new_data['operation_results'][0][1]['paid'][0]) new_data['received'] = Amount(new_data['operation_results'][0][1]['received'][0]) # still not working quite right else: # market trade pass pub.sendMessage('print_transaction', data=new_data)
def withdraw_lp(self, data): trade_message = '' new_data = {} try: bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head') trade_message = bitshares.withdraw_from_liquidity_pool( pool=data['asset'], share_amount=Amount( data['withdraw_amount'], data['asset'], ), account=data['account'], ) new_data['operation_results'] = trade_message['operation_results'] except Exception as err: print(err) if new_data: try: new_data['paid'] = Amount(new_data['operation_results'][0][1]['paid'][0]) new_data['received_x'] = Amount(new_data['operation_results'][0][1]['received'][0]) new_data['received_y'] = Amount(new_data['operation_results'][0][1]['received'][1]) pub.sendMessage('print_withdraw', data=new_data) except: print('error parsing withdraw operation results') else: print('withdraw operation failed')
def __init__(self, *args, **kwargs): super(Testcases, self).__init__(*args, **kwargs) bitshares = BitShares( "wss://node.bitshares.eu", nobroadcast=True, ) set_shared_bitshares_instance(bitshares)
def run(): # testnet = BitShares("wss://node.testnet.bitshares.eu") testnet = BitShares("ws://this.uptick.rocks:18090") account = Account("committee-account", full=True, bitshares_instance=testnet) proposals = account["proposals"] client = GrapheneAPI("localhost", 8092, "", "") for proposal in proposals: pprint(proposal) if click.confirm("Approve proposal %s" % proposal["id"]): # Get current fees core_asset = client.get_asset("1.3.0") committee_account = client.get_account("committee-account") proposal = client.get_object(proposal["id"])[0] prop_op = proposal["proposed_transaction"]["operations"] tx = client.approve_proposal( "faucet", proposal["id"], {"active_approvals_to_add": [ "committee-member-1", "committee-member-2", "committee-member-3", "committee-member-4", "committee-member-5", "committee-member-6", "committee-member-7", "committee-member-8", "committee-member-9", "committee-member-10"] }, True) pprint(tx)
def new_func(ctx, *args, **kwargs): newoptions = ctx.obj newoptions.update(kwargsChain) ctx.bitshares = BitShares(**newoptions) ctx.blockchain = ctx.bitshares set_shared_bitshares_instance(ctx.bitshares) return ctx.invoke(f, *args, **kwargs)
def main(): parser = argparse.ArgumentParser(description='', 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') parser.add_argument('account') 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) w = Witness(args.account, bitshares_instance=bitshares) pprint(dict(w))
def test_default_connection(self): b1 = BitShares("wss://eu.nodes.bitshares.ws", nobroadcast=True) set_shared_bitshares_instance(b1) test = Asset("1.3.0", blockchain_instance=b1) # Needed to clear cache test.refresh() """
def new_func(ctx, *args, **kwargs): ctx.bitshares = BitShares(ctx.config["node"], num_retries=-1, expiration=60, **ctx.obj) set_shared_bitshares_instance(ctx.bitshares) return ctx.invoke(f, *args, **kwargs)
def bitshares(self) -> BitShares: """Returns an instance of BitShares and caches it in the attribute _bitshares after creation""" if not self._bitshares: self._bitshares = BitShares(settings.BITSHARES_RPC_NODE, bundle=True, keys=[]) return self._bitshares
def deposit_lp(self, data): trade_message = '' new_data = {} try: bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head') trade_message = bitshares.deposit_into_liquidity_pool( pool=data['poolshare_symbol'], amount_a=Amount( data['asset_x_amount'], data['asset_x_symbol'], ), amount_b=Amount( data['asset_y_amount'], data['asset_y_symbol'], ), account=data['account'], ) new_data['operation_results'] = trade_message['operation_results'] except Exception as err: print(err) if new_data: try: new_data['paid_x'] = Amount(new_data['operation_results'][0][1]['paid'][0]) new_data['paid_y'] = Amount(new_data['operation_results'][0][1]['paid'][1]) new_data['received'] = Amount(new_data['operation_results'][0][1]['received'][0]) pub.sendMessage('print_deposit', data=new_data) except: print('error parsing deposit operation results') else: print('deposit operation failed')
def ping(n, num, arr): # ping the blockchain and return latency try: start = time.time() chain = Blockchain(bitshares_instance=BitShares(n, num_retries=0), mode='head') # print(n,chain.rpc.chain_params["chain_id"]) ping_latency = time.time() - start current_block = chain.get_current_block_num() blocktimestamp = abs( chain.block_timestamp(current_block)) # + utc_offset) block_latency = time.time() - blocktimestamp # print (blocktimestamp) # print (time.time()) # print (block_latency) # print (ping_latency) # print (time.ctime()) # print (utc_offset) # print (chain.get_network()) if chain.get_network()['chain_id'] != ID: num.value = 333333 elif block_latency < (ping_latency + 4): num.value = ping_latency else: num.value = 111111 except: num.value = 222222 pass
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bts = BitShares( nobroadcast=True, ) set_shared_bitshares_instance(self.bts)
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 new_func(ctx, *args, **kwargs): ctx.bitshares = BitShares( ctx.config["node"], **ctx.obj ) set_shared_bitshares_instance(ctx.bitshares) return ctx.invoke(f, *args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bts = BitShares("wss://node.testnet.bitshares.eu", nobroadcast=True, keys={"active": wif}) set_shared_bitshares_instance(self.bts) self.bts.set_default_account("init0")
def initBlockchainObject(api_node): global blockchain try: blockchain = BitShares(api_node, num_retries=0) return blockchain except: print("ERROR: Could not connect to API node at %s" % api_node) exit()
def new_func(ctx, *args, **kwargs): ctx.bitshares = BitShares( ctx.config["node"], bundle=True, # We bundle many feeds into a single tx **ctx.obj ) set_shared_bitshares_instance(ctx.bitshares) return ctx.invoke(f, *args, **kwargs)
def setup_bitshares_market(bts_symbol): bitshares_instance = BitShares( "wss://losangeles.us.api.bitshares.org/ws", nobroadcast=True # <<--- set this to False when you want to fire! ) set_shared_bitshares_instance(bitshares_instance) bts_market = Market(bts_symbol, bitshares_instance=bitshares_instance) return bts_market
def new_func(ctx, *args, **kwargs): nodelist = sort_nodes(ctx) ctx.bitshares = BitShares(nodelist, num_retries=-1, expiration=60, **ctx.obj) set_shared_bitshares_instance(ctx.bitshares) return ctx.invoke(f, *args, **kwargs)
def test_default_connection(self): b1 = BitShares( "wss://node.testnet.bitshares.eu", nobroadcast=True, ) set_shared_bitshares_instance(b1) test = Asset("1.3.0") b2 = BitShares( "wss://node.bitshares.eu", nobroadcast=True, ) set_shared_bitshares_instance(b2) bts = Asset("1.3.0") self.assertEqual(test["symbol"], "TEST") self.assertEqual(bts["symbol"], "BTS")
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.bts = BitShares(url, nobroadcast=True) set_shared_bitshares_instance(self.bts) self.asset = Asset("1.3.0") self.symbol = self.asset["symbol"] self.precision = self.asset["precision"] self.asset2 = Asset("1.3.1")