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 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 get_blockchain_info(self): try: data = {'pool': Pool(self.pool_id_or_sym, invert=self.invert)} data['pool_object'] = data['pool']['object'] data['pool_name'] = Asset(data['pool_object']['share_asset']).symbol data['asset_x'] = Asset(data['pool_object']['asset_a']) data['asset_y'] = Asset(data['pool_object']['asset_b']) data['amount_x'] = Amount(int(data['pool_object']['balance_a'])/10**data['asset_x'].precision, data['asset_x']) data['amount_y'] = Amount(int(data['pool_object']['balance_b'])/10**data['asset_y'].precision, data['asset_y']) self.amount_x = data['amount_x'] self.amount_y = data['amount_y'] data['market_ticker_object'] = Market( # python bitshares reverses base and quote base=data['asset_y'], quote=data['asset_x'] ).ticker() data['market_orderbook'] = Market( base=data['asset_y'], quote=data['asset_x'] ).orderbook(50) data['pool_invariant'] = int(data['pool_object']['virtual_value'])/(10**(data['asset_x'].precision + data['asset_y'].precision)) #print(f"Invariant: {data['pool_invariant']}") # python bitshares reverses base and quote data['price_xy'] = Price(base=data['amount_y'], quote=data['amount_x']) data['price_yx'] = Price(base=data['amount_x'], quote=data['amount_y']) pub.sendMessage('update_gui', data=data) except Exception as err: print('Invalid pool selected. Error: {}'.format(err)) pub.sendMessage('invalid_pool')
def convert(bitshares, current, target, amount, account): if current == target: return if current == "TEST": convertFromTEST() return if target == "TEST": #FIXME convertFromTEST() return amount = float(amount) current_ass = Asset(current, False, True, bitshares_instance=bitshares) print(current_ass.feed) curPerBts = current_ass.feed["settlement_price"] target_ass = Asset(target, False, True, bitshares_instance=bitshares) print(target_ass.feed) tarPerBts = target_ass.feed["settlement_price"] print(curPerBts) print(tarPerBts) amount_quot = Amount(float(tarPerBts), target, bitshares_instance=bitshares) amount_base = Amount(float(curPerBts), current, bitshares_instance=bitshares) myBuy(target, current, amount_quot, amount_base, amount, Account(account.name, bitshares_instance=bitshares), bitshares) return
def print_log(feeds): t = PrettyTable([ "base", "quote", "price", "diff", "volume", "source" ]) t.align = 'l' for symbol, feed in feeds.items(): asset = Asset(symbol, full=True) asset.ensure_full() short_backing_asset = Asset( asset["bitasset_data"]["options"]["short_backing_asset"]) backing_symbol = short_backing_asset["symbol"] data = feed.get("log", {}) price = data.get(symbol) if not price: continue for d in price.get(backing_symbol, []): t.add_row([ symbol, backing_symbol, formatPrice(d.get("price")), highlightLargeDeviation(d.get("price"), feed["price"]), d.get("volume"), str(d.get("sources")), ]) print(t.get_string())
def correct_market_precision(self, order_difference, price, asset, current_cost): precision = Asset(asset).precision Asset.clear_cache() unrounded_payout = order_difference * price unrounded_payout += current_cost return float(round(unrounded_payout, precision))
def calls(ctx, obj): """ List call/short positions of an account or an asset """ if obj.upper() == obj: # Asset from bitshares.asset import Asset asset = Asset(obj, full=True) calls = asset.get_call_orders(10) t = PrettyTable( ["acount", "debt", "collateral", "call price", "ratio"]) t.align = 'r' for call in calls: t.add_row([ str(call["account"]["name"]), str(call["debt"]), str(call["collateral"]), str(call["call_price"]), "%.2f" % (call["ratio"]) ]) click.echo(str(t)) else: # Account from bitshares.dex import Dex dex = Dex(bitshares_instance=ctx.bitshares) calls = dex.list_debt_positions(account=obj) t = PrettyTable(["debt", "collateral", "call price", "ratio"]) t.align = 'r' for symbol in calls: t.add_row([ str(calls[symbol]["debt"]), str(calls[symbol]["collateral"]), str(calls[symbol]["call_price"]), "%.2f" % (calls[symbol]["ratio"]) ]) click.echo(str(t))
def test_init(self): # self.assertEqual(1, 1) Price("0.315 USD/BTS") Price(1.0, "USD/GOLD"), Price(0.315, base="USD", quote="BTS") Price(0.315, base=Asset("USD"), quote=Asset("BTS")) Price({ "base": { "amount": 1, "asset_id": "1.3.0" }, "quote": { "amount": 10, "asset_id": "1.3.106" } }) Price( { "receives": { "amount": 1, "asset_id": "1.3.0" }, "pays": { "amount": 10, "asset_id": "1.3.106" }, }, base_asset=Asset("1.3.0")) Price(quote="10 GOLD", base="1 USD") Price("10 GOLD", "1 USD") Price(Amount("10 GOLD"), Amount("1 USD"))
def csvPairPrintOut(self): if ( (self.receiveAsset == BaseAsset or self.receiveAsset == QuoteAsset ) and ( self.payAsset == BaseAsset or self.payAsset == QuoteAsset ) ): print ( str(self.currentBalanceBase) + "," + Asset(str(BaseAsset))['symbol'] , end=",") print ( str(self.currentBalanceQuote) + "," + Asset(str(QuoteAsset))['symbol'] , end="," ) print ( str( self.baseAssetPrice ) + "," + str( self.quoteAssetPrice), end="," ) print ( str( self.baseAccountValueCalc ) + "," + str( self.quoteAccountValueCalc), end="," ) print(str(self.baseAccountValueCalcPercent) + "," + str(self.quoteAccountValueCalcPercent), end=",") print ()
def test_refresh(self): asset = Asset("1.3.0", full=False) asset.ensure_full() self.assertIn("dynamic_asset_data", asset) self.assertIn("flags", asset) self.assertIn("permissions", asset) self.assertIsInstance(asset["flags"], dict) self.assertIsInstance(asset["permissions"], dict)
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")
def parse_trade_entry(self, entry): """ Parse single trade entry (fill order) 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 = entry['operation_history']['op_object'] data = copy.deepcopy(LINE_DICT_TEMPLATE) op = entry['operation_history']['op_object'] sell_asset = Asset(op['pays']['asset_id'], bitshares_instance=self.bitshares) sell_amount = Decimal( op['pays']['amount']).scaleb(-sell_asset['precision']) buy_asset = Asset(op['receives']['asset_id'], bitshares_instance=self.bitshares) buy_amount = Decimal( op['receives']['amount']).scaleb(-buy_asset['precision']) fee_asset = Asset(op['fee']['asset_id'], bitshares_instance=self.bitshares) fee_amount = Decimal( op['fee']['amount']).scaleb(-fee_asset['precision']) # Subtract fee from buy_amount # For ccgains, any fees for the transaction should already have been substracted from *amount*, but included # in *cost*. if fee_asset.symbol == buy_asset.symbol: buy_amount -= fee_amount data['kind'] = 'Trade' data['sell_cur'] = sell_asset.symbol data['sell_amount'] = sell_amount data['buy_cur'] = buy_asset.symbol data['buy_amount'] = buy_amount data['fee_cur'] = fee_asset.symbol data['fee_amount'] = fee_amount data['comment'] = op_id data['order_id'] = op['order_id'] data['prec'] = max(sell_asset['precision'], buy_asset['precision']) # Prevent division by zero price = Decimal('0') price_inverted = Decimal('0') if sell_amount and buy_amount: price = buy_amount / sell_amount price_inverted = sell_amount / buy_amount data['price'] = price data['price_inverted'] = price_inverted data['date'] = entry['block_data']['block_time'] return data
def type_intern(self, symbol): """ Process a price from a formula """ asset = Asset(symbol, full=True) short_backing_asset = Asset( asset["bitasset_data"]["options"]["short_backing_asset"]) backing_symbol = short_backing_asset["symbol"] asset["short_backing_asset"] = short_backing_asset if self.assetconf(symbol, "type") != "formula": return if self.assetconf(symbol, "reference") == "extern": price = eval( self.assetconf(symbol, "formula").format(**self.price_result)) elif self.assetconf(symbol, "reference") == "intern": # Parse the forumla according to ref_asset if self.assethasconf(symbol, "ref_asset"): ref_asset = self.assetconf(symbol, "ref_asset") market = Market("%s:%s" % (ref_asset, backing_symbol)) ticker_raw = market.ticker() ticker = {} for k, v in ticker_raw.items(): if isinstance(v, Price): ticker[k] = float(v.as_quote("BTS")) elif isinstance(v, Amount): ticker[k] = float(v) price = eval( str(self.assetconf(symbol, "formula")).format(**ticker)) else: price = eval(str(self.assetconf(symbol, "formula"))) else: raise ValueError("Missing 'reference' for asset %s" % symbol) orientation = self.assetconf(symbol, "formula_orientation", no_fail=True)\ or "{}:{}".format(backing_symbol, symbol) # default value price = Price(price, orientation) cer = self.get_cer(symbol, price) self.price_result[symbol] = { "price": float(price.as_quote(backing_symbol)), "cer": float(cer), "number": 1, "short_backing_symbol": backing_symbol, "mean": float(price), "median": float(price), "weighted": float(price), "mssr": self.assetconf(symbol, "maximum_short_squeeze_ratio"), "mcr": self.assetconf(symbol, "maintenance_collateral_ratio"), "std": 0.0, "number": 1, }
def getAsset(self, asset_id, cache=True, force_remote=False, force_local=False): from bitshares.asset import Asset if not (force_remote): if asset_id.startswith('1.3.'): stored_asset = self.assetStorage.getById( asset_id) if self.store else None else: stored_asset = self.assetStorage.getBySymbol( asset_id) if self.store else None else: stored_asset = None if stored_asset: stored_asset["precision"] = int(stored_asset["precision"]) stored_asset["options"]["max_supply"] = int( stored_asset["options"]["max_supply"]) forged_asset = Asset.__new__(Asset) forged_asset.identifier = stored_asset["id"] forged_asset.blockchain = self.bts forged_asset.cached = True forged_asset.lazy = True forged_asset.full = False forged_asset.asset = stored_asset["symbol"] for k, v in stored_asset.items(): forged_asset[k] = v self.minicache_precision[ stored_asset["symbol"]] = stored_asset["precision"] return forged_asset if self.offline or force_local: # Can't or Won't fetch remote asset raise ResourceUnavailableOffline("Asset %s" % str(asset_id)) from bitshares.exceptions import AssetDoesNotExistsException try: remote_asset = Asset(asset_id, full=True, lazy=False, blockchain_instance=self.bts) except AssetDoesNotExistsException: raise except: raise ResourceUnavailableOffline("Asset %s" % str(asset_id)) if cache: self.saveAsset(remote_asset) return remote_asset
def settlements(ctx, asset): from bitshares.asset import Asset asset = Asset(asset, full=True) calls = asset.get_settle_orders(10) t = PrettyTable(["acount", "amount", "date"]) t.align = 'r' for call in calls: t.add_row([ str(call["account"]["name"]), str(call["amount"]), str(call["date"]), ]) click.echo(str(t))
def settlements(ctx, asset, limit): """ Show pending settlement orders of a bitasset """ from bitshares.asset import Asset asset = Asset(asset, full=True) if not asset.is_bitasset: print_message("{} is not a bitasset.".format(asset["symbol"]), "warning") sys.exit(1) calls = asset.get_settle_orders(limit) t = [["acount", "amount", "date"]] for call in calls: t.append([str(call["account"]["name"]), str(call["amount"]), str(call["date"])]) print_table(t)
def get_asset(asset_name: hug.types.text, api_key: hug.types.text, request, hug_timer=5): """Get info regarding a single input asset.""" if (check_api_token(api_key) == True): # Check the api key # API KEY VALID google_analytics(request, 'get_asset') try: target_asset = Asset(asset_name, full=True) except: return {'valid_asset': False, 'valid_key': True, 'took': float(hug_timer)} try: bitasset_data = target_asset['bitasset_data_id'] except: bitasset_data = None extracted_object = extract_object(target_asset) return {'asset_data': extracted_object, 'valid_asset': True, 'valid_key': True, 'took': float(hug_timer)} else: # API KEY INVALID! return {'valid_key': False, 'took': float(hug_timer)}
def deposit(i, method): """ i: the InputTx fee: in basis points either succeeds returning BTS txid, or throws exception """ fee = Decimal(config[method]['fee']) asset_symbol = config[method]['asset'] asset = Asset(asset_symbol) dest_acct = Account(i.bts_account) i.date = i.date or time.strftime("%Y-%m-%d") cur = conn.cursor() try: fee = round(i.amount * fee / Decimal("10000"), 2) # are we KYC? cur.execute("select * from users where account_id = %s", (dest_acct['id'],)) assert cur.rowcount > 0, "KYC data not found for {}".format(i.bts_account) # actually do BitShares send bts_tx_id = bitshares.transfer(dest_acct, float(i.amount - fee), asset, account=acct) # save to DB cur.execute("insert into tx (bts_account, amount, fee, bts_txid, \"comment\", mode, \"when\", asset, fiat_txid) values (%s, %s, %s, %s, %s, 'D', %s, %s, %s)", (dest_acct['id'], i.amount - fee, fee, repr(bts_tx_id), i.comment, i.date, asset_symbol, i.fiat_txid)) except BaseException as e: cur.execute("insert into tx (bts_account, amount, \"when\", \"comment\", mode, bts_txid, asset) values (%s, %s, %s, %s, 'E','NONE', %s)", (dest_acct['id'], i.amount, i.date, i.comment + " " + str(e), asset_symbol)) cur.close() conn.commit() raise conn.commit() return bts_tx_id, i.amount - fee
def main(): parser = argparse.ArgumentParser(description='Get asset info', 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, full=True, bitshares_instance=bitshares) pprint(dict(asset))
def postProcess2(df): import pickle from bitshares.asset import Asset try: with open('assets.pickle', 'rb') as h: assets = pickle.load(h) except: assets = {} if df is None or len(df) == 0: return s1 = set(df.pays_asset.value_counts().index.tolist()) s2 = set(df.receives_asset.value_counts().index.tolist()) s1.update(s2) # for dropping unpopular pairs if False: df['popular_pair'] = False df.loc[(df['pays_asset'].isin(s1)) & (df['receives_asset'].isin(s1)), 'popular_pair'] = True df.drop(df[df['popular_pair'] == False].index, inplace=True) # TODO: there were not all assets in pickle file with this code for s in s1: if s in assets: asset_symbol, asset_precision = assets[s] print(".", end=' ') else: a2 = Asset(s) assets[s] = [a2.symbol, a2.precision] asset_symbol, asset_precision = [a2.symbol, a2.precision] print("new", end=' ') print(asset_symbol) # drop minimal trades (dust?) if False: dust_threshold = 1e5 / 10**asset_precision df.drop(df[(df['pays_asset'] == s) & (df['pays_amount'] < dust_threshold)].index, inplace=True) df.drop(df[(df['receives_asset'] == s) & (df['receives_amount'] < dust_threshold)].index, inplace=True) df.loc[df['pays_asset']==s, 'pays_amount'] /= (10 ** asset_precision) df.loc[df['receives_asset'] == s, 'receives_amount'] /= (10 ** asset_precision) with open('assets.pickle', 'wb') as h: pickle.dump(assets, h) df['price'] = -1 # popular pairs are ok df['price'] = df['receives_amount'] / df['pays_amount'] #df = df.set_index('block_time') print(0) date_from = df.block_time.min() date_to = df.block_time.max() print("save to parquet", len(df), end=' ') df.to_parquet('bts_trades_{}_{}.curated.parquet'.format(date_from, date_to), 'fastparquet', 'GZIP') print("ok") print("end of work")
def fixture_data(): # Clear tx buffer bitshares.clear() Account.clear_cache() with open(os.path.join(os.path.dirname(__file__), "fixtures.yaml")) as fid: data = yaml.safe_load(fid) for account in data.get("accounts"): Account.cache_object(account, account["id"]) Account.cache_object(account, account["name"]) for asset in data.get("assets"): Asset.cache_object(asset, asset["symbol"]) Asset.cache_object(asset, asset["id"]) proposals = [] for proposal in data.get("proposals", []): ops = [] for _op in proposal["operations"]: for opName, op in _op.items(): ops.append([operations[opName], op]) # Proposal! proposal_id = proposal["proposal_id"] proposal_data = { "available_active_approvals": [], "available_key_approvals": [], "available_owner_approvals": [], "expiration_time": "2018-05-29T10:23:13", "id": proposal_id, "proposed_transaction": { "expiration": "2018-05-29T10:23:13", "extensions": [], "operations": ops, "ref_block_num": 0, "ref_block_prefix": 0, }, "proposer": "1.2.7", "required_active_approvals": ["1.2.1"], "required_owner_approvals": [], } proposals.append(Proposal(proposal_data)) Proposals.cache_objects(proposals, "1.2.1") Proposals.cache_objects(proposals, "witness-account")
def bitasset_local(bitshares, base_bitasset, default_account): asset = base_bitasset() dex = Dex(blockchain_instance=bitshares) # Set initial price feed price = Price(1.5, base=asset, quote=Asset("TEST")) bitshares.publish_price_feed(asset.symbol, price, account=default_account) # Borrow some amount to_borrow = Amount(100, asset) dex.borrow(to_borrow, collateral_ratio=2.1, account=default_account) # Drop pricefeed to cause margin call price = Price(1.0, base=asset, quote=Asset("TEST")) bitshares.publish_price_feed(asset.symbol, price, account=default_account) return asset
def main(ctx, asset): """Print current feeds for an asset.""" asset = Asset(asset, bitshares_instance=ctx.bitshares) feeds = asset.feeds for feed in feeds: print('{}: {}'.format(feed['producer']['name'], feed['settlement_price']))
def fetch_market(): cybex_config(node_rpc_endpoint=NODE_WS_ENDPOINT, chain_id=CHAIN_ID) net = BitShares(node=NODE_WS_ENDPOINT, **{'prefix': 'CYB'}) net.wallet.unlock('123456') m = Market(base=Asset('CYB'), quote=Asset('JADE.ETH'), bitshares_instance=net) tick = m.ticker() latest = tick['latest'] price = latest['base'].amount / latest['quote'].amount print('JADE.ETH:CYB = {}'.format(price))
def test_properties(self): asset = Asset("1.3.0", full=False) self.assertIsInstance(asset.symbol, str) self.assertIsInstance(asset.precision, int) self.assertIsInstance(asset.is_bitasset, bool) self.assertIsInstance(asset.permissions, dict) self.assertEqual(asset.permissions, asset["permissions"]) self.assertIsInstance(asset.flags, dict) self.assertEqual(asset.flags, asset["flags"])
def settlements(ctx, asset): """ Show pending settlement orders of a bitasset """ from bitshares.asset import Asset asset = Asset(asset, full=True) if not asset.is_bitasset: click.echo("{} is not a bitasset.".format(asset["symbol"])) sys.exit(1) calls = asset.get_settle_orders(10) t = PrettyTable(["acount", "amount", "date"]) t.align = 'r' for call in calls: t.add_row([ str(call["account"]["name"]), str(call["amount"]), str(call["date"]), ]) click.echo(str(t))
def _loadchaindata(self): for symbol in self.config.get("assets"): asset = Asset(symbol, full=True) self.data["asset"][symbol] = asset self.data["feed"][symbol] = asset.feeds for witness_name in self.witnesses: witness = Witness(witness_name) self.data["witness"][witness_name] = witness self.data["account"][witness_name] = witness.account
def asset(ctx, obj): data = Asset(obj, full=True) t = [["Key", "Value"]] for key in sorted(data): value = data[key] if isinstance(value, dict): value = format_tx(value) t.append([key, value]) print_table(t)
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 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")