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 publish_test_feeds(): print(btsconf.confs["bts"].config_defaults) priceA = Price(0.4, base="USD", quote="BTS", bitshares_instance=btsconf.confs["bts"]) priceB = Price(0.9, base="USD", quote="BTS", bitshares_instance=btsconf.confs["bts"]) for i in range(0, 10): btsconf.confs["bts"].publish_price_feed("USD", settlement_price=priceA, cer=priceA, mssr=110, mcr=175, account="init" + str(i)) btsconf.confs["bts"].publish_price_feed("USD", settlement_price=priceB, cer=priceB, mssr=110, mcr=175, account="init10")
def newfeed(ctx, symbol, price, market, cer, mssr, mcr, account): """ Publish a price feed! Examples: \b uptick newfeed USD 0.01 USD/BTS uptick newfeed USD 100 BTS/USD Core Exchange Rate (CER) \b If no CER is provided, the cer will be the same as the settlement price with a 5% premium (Only if the 'market' is against the core asset (e.g. BTS)). The CER is always defined against the core asset (BTS). This means that if the backing asset is not the core asset (BTS), then you must specify your own cer as a float. The float `x` will be interpreted as `x BTS/SYMBOL`. """ if cer: cer = Price(cer, quote=symbol, base="1.3.0", bitshares_instance=ctx.bitshares) print_tx( ctx.bitshares.publish_price_feed(symbol, Price(price, market), cer=cer, mssr=mssr, mcr=mcr, account=account))
def test_div2(self): p1 = Price(10.0, "USD/GOLD") p2 = Price(5.0, "USD/GOLD") # 10 USD/GOLD / 5 USD/EUR = 2 EUR/GOLD p3 = p1 / p2 self.assertTrue(isinstance(p3, (float, int))) self.assertEqual(float(p3), 2.0)
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 test_div(self): p1 = Price(10.0, "USD/GOLD") p2 = Price(5.0, "USD/EUR") # 10 USD/GOLD / 5 USD/EUR = 2 EUR/GOLD p3 = p1 / p2 p4 = p3.as_base("EUR") self.assertEqual(p4["base"]["symbol"], "EUR") self.assertEqual(p4["quote"]["symbol"], "GOLD") # 10 USD/GOLD * 0.2 EUR/USD = 2 EUR/GOLD = 0.5 GOLD/EUR self.assertEqual(float(p4), 2)
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 sell(ctx, sell_amount, sell_asset, price, buy_asset, account): amount = Amount(sell_amount, sell_asset) price = Price(price, quote=sell_asset, base=buy_asset, bitshares_instance=ctx.bitshares) pprint(price.market.sell(price, amount, account=account))
def publish_feed(witness, price_to_publish_in_usd, discount): print(price_to_publish_in_usd) # GETTING USD BTS PRICE USD:BTS price market = Market("BTS:USD") price = market.ticker()['baseSettlement_price'] print(price) price.invert() # invert to allow easier multiplication # BTS:USD price one_usd_bts = price priceinbts = float(price_to_publish_in_usd) * one_usd_bts['price'] pricempa = Price("{} BTS/GOLOS".format(priceinbts)) print(pricempa) #unlock wallet... market.bitshares.wallet.unlock("YOUR BITSHARES UPTICK WALLET UNLOCK CODE") (market.bitshares.publish_price_feed( symbol="GOLOS", settlement_price=pricempa, cer=pricempa * (1 / 1.2), mcr=175, account=witness, )) print("Published price feed: " + str(price_to_publish_in_usd) + " USD/GOL (-" + str(discount * 100) + "%) at " + time.ctime() + "\n")
def mySell(ccy_quot, ccy_base, amount_quot, amount_base, amount, account, bitshares): if account.name != "test2017": # Use account test2017 to simulate the market reactivity to offer and demand acc2 = accounts["test2017"] bts2 = BitShares(btsNode, acc2.name, acc2.pwd) market = Market(ccy_quot + ":" + ccy_base, bitshares_instance=bts2) bts2.wallet.unlock("supersecret") market.buy(Price(amount_quot, amount_base, bitshares_instance=bts2), Amount(str(amount) + " " + ccy_quot, bitshares_instance=bts2), account=Account(acc2.name, bitshares_instance=bts2)) bts2.wallet.lock() market = Market(ccy_quot + ":" + ccy_base, bitshares_instance=bitshares) bitshares.wallet.unlock("supersecret") market.sell(Price(amount_quot, amount_base, bitshares_instance=bitshares), Amount(str(amount) + " " + ccy_quot, bitshares_instance=bitshares), account=account) bitshares.wallet.lock() sleep(2) return
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 test_multiplication(self): p1 = Price(10.0, "USD/GOLD") p2 = Price(5.0, "EUR/USD") p3 = p1 * p2 p4 = p3.as_base("GOLD") self.assertEqual(p4["quote"]["symbol"], "EUR") self.assertEqual(p4["base"]["symbol"], "GOLD") # 10 USD/GOLD * 0.2 EUR/USD = 50 EUR/GOLD = 0.02 GOLD/EUR self.assertEqual(float(p4), 0.02) # Inline multiplication p5 = p1 p5 *= p2 p4 = p5.as_base("GOLD") self.assertEqual(p4["quote"]["symbol"], "EUR") self.assertEqual(p4["base"]["symbol"], "GOLD") # 10 USD/GOLD * 0.2 EUR/USD = 2 EUR/GOLD = 0.02 GOLD/EUR self.assertEqual(float(p4), 0.02)
def newfeed(ctx, symbol, price, market, account): """ Publish a price feed! Examples: \b uptick newfeed USD 0.01 USD/BTS uptick newfeed USD 100 BTS/USD """ pprint(ctx.bitshares.publish_price_feed(symbol, Price(price, market)))
def run_hertz_function(): time_before = pendulum.now() # Getting the value of USD in BTS market = Market("USD:BTS") # Set reference market to USD:BTS price = market.ticker()[ "quoteSettlement_price"] # Get Settlement price of USD price.invert( ) # Switching from quantity of BTS per USD to USD price of one BTS. #Hertz variables: #Change only for alternative Algorithm Based Assets. hertz_reference_timestamp = "2015-10-13T14:12:24+00:00" # Bitshares 2.0 genesis block timestamp hertz_current_timestamp = pendulum.now().timestamp( ) # Current timestamp for reference within the hertz script hertz_amplitude = 0.14 # 14% fluctuating the price feed $+-0.14 (2% per day) hertz_period_days = 28 # Aka wavelength, time for one full SIN wave cycle. hertz_phase_days = 0.908056 # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day. hertz_reference_asset_value = 1.00 # $1.00 USD, not much point changing as the ratio will be the same. hertz_core_exchange_rate = 0.80 # Calculate the current value of Hertz in USD hertz_value = get_hertz_feed(hertz_reference_timestamp, hertz_current_timestamp, hertz_period_days, hertz_phase_days, hertz_reference_asset_value, hertz_amplitude) hertz = Price(hertz_value, "USD/HERTZ" ) # Limit the hertz_usd decimal places & convert from float. cg = CoinGeckoAPI() # Initialise coingecko bts_usd_coingecko = cg.get_price( ids='bitshares', vs_currencies='usd') # Price of BTS in USD from coingecko bts_usd_coingecko_value = Price(bts_usd_coingecko["bitshares"]["usd"], "USD/BTS") # Price format hertz_bts = bts_usd_coingecko_value.invert() * hertz.as_quote( "HERTZ") # Feed price hertz_cer = hertz_bts * hertz_core_exchange_rate # Some printed outputs #print("Price of HERTZ in USD: {}".format(hertz)) #print("Price of HERTZ in BTS: {}".format(hertz_bts)) #print("Price of BTS in USD: {}".format(bts_usd_coingecko_value)) #print("Price of USD in BTS: {}".format(bts_usd_coingecko_value.invert())) # Unlock the Bitshares wallet hertz.bitshares.wallet.unlock("LOCAL_WALLET_PASSWORD") """ Publish the price feed to the BTS DEX Make sure you change the 'account' before executing. Don't change any of the other values. """ pprint( hertz.bitshares.publish_price_feed( "HERTZ", hertz_bts, cer=hertz_cer, # Setting in line with Wackou's price feed scripts mssr=110, mcr=200, account="REPLACE_WITH_YOUR_USERNAME"))
def publish_price(account, price): btsNode = 'wss://node.testnet.bitshares.eu' bitshares = BitShares(btsNode, account.name, account.pwd) price = float(price) stlprice = Price(price, "TEST/" + account.asset, bitshares_instance=bitshares) btsAccount = Account(account.name, bitshares_instance=bitshares) bitshares.wallet.unlock(wallet_pwd) bitshares.publish_price_feed(account.asset, stlprice, account=btsAccount) bitshares.wallet.lock()
def sell(ctx, sell_amount, sell_asset, price, buy_asset, order_expiration, account): """ Sell a specific asset at a certain rate against a base asset """ amount = Amount(sell_amount, sell_asset) price = Price(price, quote=sell_asset, base=buy_asset, bitshares_instance=ctx.bitshares) print_tx( price.market.sell(price, amount, account=account, expiration=order_expiration))
def buy(ctx, buy_amount, buy_asset, price, sell_asset, order_expiration, account): """ Buy a specific asset at a certain rate against a base asset """ amount = Amount(buy_amount, buy_asset) price = Price(price, base=sell_asset, quote=buy_asset, bitshares_instance=ctx.bitshares) pprint( price.market.buy(price, amount, account=account, expiration=order_expiration))
def print_prices(feeds): t = PrettyTable([ "symbol", "collateral", "new price", "cer", "mean", "median", "wgt. avg.", "wgt. std (#)", "blockchain", "mssr", "mcr", "my last price", "last update", ]) t.align = 'c' t.border = True for symbol, feed in feeds.items(): if not feed: continue myprice = feed["price"] blockchain = float(Price(feed["global_feed"]["settlement_price"])) if "current_feed" in feed and feed["current_feed"]: last = float(feed["current_feed"]["settlement_price"]) age = (str(datetime.utcnow() - feed["current_feed"]["date"])) else: last = -1.0 age = "unknown" # Get Final Price according to price metric t.add_row([ symbol, ("%s") % (feed["short_backing_symbol"]), ("%s" % formatPrice(feed["price"])), ("%s" % formatPrice(feed["cer"])), ("%s (%s)" % (formatPrice( feed["mean"]), priceChange(myprice, feed.get("mean")))), ("%s (%s)" % (formatPrice( feed["median"]), priceChange(myprice, feed.get("median")))), ("%s (%s)" % (formatPrice(feed["weighted"]), priceChange(myprice, feed.get("weighted")))), ("%s (%2d)" % (formatStd(feed["std"]), feed.get("number"))), ("%s (%s)" % (formatPrice(blockchain), priceChange(myprice, blockchain))), ("%.1f%%" % feed["mssr"]), ("%.1f%%" % feed["mcr"]), ("%s (%s)" % (formatPrice(last), priceChange(myprice, last))), age + " ago" ]) print(t.get_string())
def test_feed(self, witness, symbol, feed): current_feed = self.data["asset"][symbol]["bitasset_data"]["current_feed"] pw = feed["settlement_price"] p = Price(current_feed["settlement_price"]) def diff_percentage(p, pw): return math.fabs((float(pw) - float(p)) / float(p) * 100) param = self.params.get("diff_percentage") if param: max = float(param.get("max")) if max: if max < diff_percentage(p, pw): self.failure(witness, error=dict(diff=diff_percentage(p, pw))) if not self.failed: self.success(witness)
#Hertz variables: #Change only for alternative Algorithm Based Assets. hertz_reference_timestamp = "2015-10-13T14:12:24+00:00" # Bitshares 2.0 genesis block timestamp hertz_current_timestamp = pendulum.now().timestamp( ) # Current timestamp for reference within the hertz script hertz_amplitude = 0.14 # 14% fluctuating the price feed $+-0.14 (2% per day) hertz_period_days = 28 # Aka wavelength, time for one full SIN wave cycle. hertz_phase_days = 0.908056 # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day. hertz_reference_asset_value = 1.00 # $1.00 USD, not much point changing as the ratio will be the same. # Calculate the current value of Hertz in USD hertz_value = get_hertz_feed(hertz_reference_timestamp, hertz_current_timestamp, hertz_period_days, hertz_phase_days, hertz_reference_asset_value, hertz_amplitude) hertz = Price(hertz_value, "USD/HERTZ" ) # Limit the hertz_usd decimal places & convert from float. print(hertz) # Calculate HERTZ price in BTS (THIS IS WHAT YOU PUBLISH!) hertz_bts = price.as_base("BTS") * hertz.as_quote("HERTZ") print("Hz-Quote: {}".format(hertz.as_quote("HERTZ"))) print("base: {}".format(price.as_base("BTS"))) hertz_core_exchange_rate = 0.80 # 20% offset, CER > Settlement! hertz_cer = hertz_bts * hertz_core_exchange_rate # Some printed outputs print("Price of HERTZ in USD: {}".format(hertz)) print("Price of HERTZ in BTS: {}".format(hertz_bts)) print("Price of BTS in USD: {}".format(price))
def describe(ctx, pool, slip, slip_buy, verbose): """Describe a Liquidity Pool. Gives detailed information about a particular liquidity pool, including component assets, share supply, and current exchange rates, including slippage estimates to help predict realizable exchange rate based on size of trade, and fee structure of the pool. POOL: The pool to describe. This can be given as a pool id (e.g. "1.19.x") or as the share asset symbol (or asset id) of the pool's share asset. Note on Slippage Estimates: Estimated trades account for pool fees, but do not account for market fees of the traded assets, if any. You may need to account for these yourself. You can use the --slip option to add a slippage percent to the slippage table to estimate outcomes of larger trades. Slippage percents are based on SELLING a percentage quantity of asset into the pool. To calculate a slippage based on BUYING a percentage of the pool, use the --slip-buy option. (The formula is buy_pct = sell_pct/(100% - sell_pct).) """ # Quite messy, and desires a proper Pool object class. T.B.D. Someday. slip_pcts = [0.01, 0.05, 0.10] if slip: slip_pcts.append(float(slip)/100) slip_pcts.sort() if slip_buy: pct=float(slip_buy)/100 slip_pcts.append(pct/(1-pct)) slip_pcts.sort() pool_id = ctx.bitshares._find_liquidity_pool(pool) # ad hoc data = ctx.bitshares.rpc.get_object(pool_id) if data: t = [["Key", "Value"]] try: orig_data = data asset_a = Asset(data.pop("asset_a"), blockchain_instance=ctx.bitshares) asset_b = Asset(data.pop("asset_b"), blockchain_instance=ctx.bitshares) share_asset = Asset(data.pop("share_asset"), blockchain_instance=ctx.bitshares) pool_owner = Account(share_asset["issuer"], blockchain_instance=ctx.bitshares) share_dyn = ctx.bitshares.rpc.get_object(share_asset["dynamic_asset_data_id"]) share_supply = int(share_dyn["current_supply"]) share_supply = Amount(share_supply/10**share_asset.precision, share_asset) amount_a = Amount(int(data.pop("balance_a"))/10**asset_a.precision, asset_a) amount_b = Amount(int(data.pop("balance_b"))/10**asset_b.precision, asset_b) pool_k = int(data.pop("virtual_value"))/10**(asset_a.precision + asset_b.precision) taker_fee = int(data.pop("taker_fee_percent"))/100 withdrawal_fee = int(data.pop("withdrawal_fee_percent"))/100 data.pop("id") if verbose: pool_desc = share_asset["options"]["description"] if "description" in share_asset: pool_desc = share_asset["description"] if isinstance(pool_desc, dict): pool_desc = format_tx(pool_desc) # Generate Table: t.append(["Pool Name", "%s"%(share_asset["symbol"])]) if verbose: t.append(["Pool Description", pool_desc]) t.append(["Pool Id", "%s"%(pool_id)]) t.append(["Pool Owner", "%s (%s)"%(pool_owner["name"],pool_owner["id"])]) t.append(["Asset A", "%s (%s)"%(asset_a["symbol"],asset_a["id"])]) t.append(["Asset B", "%s (%s)"%(asset_b["symbol"],asset_b["id"])]) t.append(["",""]) t.append(["Balance of Asset A", str(amount_a)]) t.append(["Balance of Asset B", str(amount_b)]) t.append(["",""]) t.append(["Outstanding Pool Shares", "%s (%s)"%(str(share_supply),share_asset["id"])]) t.append(["Pool Invariant (k=xy)", pool_k]) t.append(["",""]) t.append(["Nominal Pool Price (A/B)", Price(base=amount_a, quote=amount_b, blockchain_instance=ctx.bitshares)]) t.append(["Nominal Pool Price (B/A)", Price(base=amount_b, quote=amount_a, blockchain_instance=ctx.bitshares)]) t.append(["",""]) t.append(["Price Resilience:",""]) def recv(pct): return (pct/(1+pct))*((100.0-taker_fee)/100) t.append(["",""]) t.append([" Selling Asset A:",""]) t.append(["",""]) for sl in slip_pcts: t.append([ " %4g%% Slippage"%(sl*100), "Sell %s for %s"%(amount_a*sl, amount_b*recv(sl)) ]) t.append(["",""]) t.append([" Selling Asset B:",""]) t.append(["",""]) for sl in slip_pcts: t.append([ " %4g%% Slippage"%(sl*100), "Sell %s for %s"%(amount_b*sl, amount_a*recv(sl)) ]) t.append(["",""]) t.append([" (est. with fees)",""]) t.append(["",""]) t.append(["Exchange Fee", "%0.2f%%"%taker_fee]) t.append(["Withdrawal Fee", "%0.2f%%"%withdrawal_fee]) except: raise t = [["Key", "Value"]] data = orig_data pass # If schema not what we expected, reset and fall through to sorted list. for key in sorted(data): value=data[key] if isinstance(value, dict) or isinstance(value, list): value = format_tx(value) t.append([key, value]) print_table(t) else: print_message("Could not retrieve pool object", "warning")
def update(ctx, assets): """ Update price feed for assets """ exitcode = 0 # Do i have a producer? assert "producer" in ctx.config and ctx.config["producer"], \ "Please provide a feed producer name in the configuration!" feed = Feed(config=ctx.config) feed.fetch() feed.derive(assets) prices = feed.get_prices() print_log(prices) print_prices(prices) for symbol, price in prices.items(): # Skip empy symbols if not price: continue flags = price["flags"] # Prices that don't move sufficiently, or are not too old, can # be skipped right away if "min_change" not in flags and "over_max_age" not in flags: continue if (ctx.obj["confirm_warning"] and "over_warn_change" in flags and "skip_change" not in flags): if not confirmwarning( "Price change for %s (%f) has been above 'warn_change'. Please confirm!" % (symbol, price["priceChange"])): continue if "skip_change" in flags: if ctx.obj["skip_critical"]: alert( "Price change for %s (%f) has been above 'skip_change'. Skipping!" % ( symbol, price["priceChange"], )) exitcode = 1 continue else: if not confirmalert( "Price change for %s (%f) has been above 'skip_change'. Please confirm to still publish, else feed will be skipped!" % ( symbol, price["priceChange"], )): continue # Prices are denoted in `base`/`quote`. For a bitUSD feed, we # want something like 0.05 USD per BTS. This makes "USD" the # `base` and BTS the `quote`. settlement_price = Price(price["price"], base=symbol, quote=price["short_backing_symbol"]) cer = Price(price["cer"], base=symbol, quote=price["short_backing_symbol"]) ctx.bitshares.publish_price_feed(symbol, settlement_price=settlement_price, cer=cer, mssr=price["mssr"], mcr=price["mcr"], account=ctx.config["producer"]) # Always ask for confirmation if this flag is set to true if "confirm" in ctx.config and ctx.config["confirm"]: ctx.bitshares.txbuffer.constructTx() pprint(ctx.bitshares.txbuffer.json()) if not confirmwarning("Please confirm"): return if ctx.bitshares.txbuffer.ops: ctx.bitshares.txbuffer.broadcast() sys.exit(exitcode)
#! /usr/bin/env python3 from getpass import getpass from bitshares.price import Price from bitshares.market import Market from datetime import date # USD:BTS price market = Market("USD:BTS") price = market.ticker()["quoteSettlement_price"] price.invert() # invert to allow easier multiplication # HERO:USD price hero_usd = (1.05**((date.today() - date(1913, 12, 23)).days / 365.2425)) hero = Price(hero_usd, "USD/HERO") # HERO:BTS price hero_bts = price * hero print("Price of HERO in USD: {}".format(hero)) print("Price of USD in BTS: {}".format(price)) print("Price of HERO in BTS: {}".format(hero_bts)) # unlock wallet market.bitshares.wallet.unlock("YOUR UPTICK WALLET UNLOCK CODE") print(market.bitshares.publish_price_feed("HERO", hero_bts, account="roelandp"))
def get_hertz_value(api_key: hug.types.text, request, hug_timer=15): """Retrieve reference Hertz feed price value in JSON.""" if (check_api_token(api_key) == True): # Check the api key google_analytics(request, 'get_hertz_value') # Getting the value of USD in BTS market = Market("USD:BTS") # Set reference market to USD:BTS price = market.ticker()["quoteSettlement_price"] # Get Settlement price of USD price.invert() # Switching from quantity of BTS per USD to USD price of one BTS. hertz_reference_timestamp = "2015-10-13T14:12:24+00:00" # Bitshares 2.0 genesis block timestamp hertz_current_timestamp = pendulum.now().timestamp() # Current timestamp for reference within the hertz script hertz_amplitude = 0.14 # 14% fluctuating the price feed $+-0.14 (1% per day) hertz_period_days = 28 # Aka wavelength, time for one full SIN wave cycle. hertz_phase_days = 0.908056 # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day. hertz_reference_asset_value = 1.00 # $1.00 USD, not much point changing as the ratio will be the same. hertz_value = get_hertz_feed(hertz_reference_timestamp, hertz_current_timestamp, hertz_period_days, hertz_phase_days, hertz_reference_asset_value, hertz_amplitude) hertz = Price(hertz_value, "USD/HERTZ") # Limit the hertz_usd decimal places & convert from float. # Calculate HERTZ price in BTS (THIS IS WHAT YOU PUBLISH!) hertz_bts = price.as_base("BTS") * hertz.as_quote("HERTZ") unofficial_data = {'hertz_price_in_usd': hertz['price'], 'hertz_price_in_bts': hertz_bts['price'], 'core_exchange_rate': hertz_bts['price']*0.80, 'usd_price_in_bts': 1/price['price'], 'bts_price_in_usd': price['price']} ######## try: target_asset = Asset("HERTZ", 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) bitasset_data = extracted_object['bitasset_data'] current_feeds = bitasset_data['current_feed'] current_feed_settlement_price = current_feeds['settlement_price'] current_feed_cer = current_feeds['core_exchange_rate'] if (int(current_feed_settlement_price['base']['amount']) > 0 and int(current_feed_settlement_price['quote']['amount']) > 0): current_feed_settlement_price['api_calculated_rate'] = int(current_feed_settlement_price['quote']['amount'])/int(current_feed_settlement_price['base']['amount']) else: current_feed_settlement_price['api_calculated_rate'] = 0 if (int(current_feed_cer['base']['amount']) > 0 and int(current_feed_cer['quote']['amount']) > 0): current_feed_cer['api_calculated_rate'] = int(current_feed_cer['quote']['amount'])/int(current_feed_cer['base']['amount']) else: current_feed_cer['api_calculated_rate'] = 0 witness_feeds = bitasset_data['feeds'] witness_feed_data = {} witness_iterator = 0 for witness_feed in witness_feeds: # Extract that data! witness_id = witness_feed[0] witness_iterator += 1 try: target_account = Account(str(witness_id)) except: print("Witness account doesn't work?!") extracted_object = extract_object(target_account) witness_name = extracted_object['name'] publish_timestamp = witness_feed[1][0] feed_data = witness_feed[1][1] settlement_price = feed_data['settlement_price'] if (int(settlement_price['quote']['amount']) > 0): maintenance_collateral_ratio = feed_data['maintenance_collateral_ratio'] maximum_short_squeeze_ratio = feed_data['maximum_short_squeeze_ratio'] core_exchange_rate = feed_data['core_exchange_rate'] settlement_price_before = int(settlement_price['quote']['amount'])/int(settlement_price['base']['amount']) core_exchange_rate_before = int(core_exchange_rate['quote']['amount'])/(int(core_exchange_rate['base']['amount'])) settlement_price['api_calculated_rate'] = settlement_price_before / 10 core_exchange_rate['api_calculated_rate'] = core_exchange_rate_before / 10 try: target_witness = Witness(witness_name) except: target_witness = None if (target_witness is not None): witness_role_data = extract_object(target_witness) witness_identity = witness_role_data['id'] witness_url = witness_role_data['url'] witness_feed_data[str(witness_iterator)] = {'witness_account_id': witness_id, 'witness_name': witness_name, 'witness_id': witness_identity, 'witness_url': witness_url, 'publish_timestamp': publish_timestamp, 'settlement_price': settlement_price, 'maintenance_collateral_ratio': maintenance_collateral_ratio, 'maximum_short_squeeze_ratio': maximum_short_squeeze_ratio, 'core_exchange_rate': core_exchange_rate} else: witness_feed_data[str(witness_iterator)] = {'witness_account_id': witness_id, 'witness_name': witness_name, 'witness_id': "N/A", 'witness_url': "#", 'publish_timestamp': publish_timestamp, 'settlement_price': settlement_price, 'maintenance_collateral_ratio': maintenance_collateral_ratio, 'maximum_short_squeeze_ratio': maximum_short_squeeze_ratio, 'core_exchange_rate': core_exchange_rate} else: continue return {'unofficial_reference': unofficial_data, 'witness_feeds': witness_feed_data, 'current_feeds': current_feeds, 'valid_key': True, 'took': float(hug_timer)} else: # API KEY INVALID! return {'valid_key': False, 'took': float(hug_timer)}
def update(ctx, assets): """ Update price feed for assets """ feed = Feed(config=ctx.config) feed.fetch() feed.derive(assets) prices = feed.get_prices() print_prices(prices) for symbol, price in prices.items(): flags = price["flags"] # Prices that don't move sufficiently, or are not too old, can # be skipped right away if "min_change" not in flags and "over_max_age" not in flags: continue if (ctx.obj["confirm_warning"] and "over_warn_change" in flags and "skip_change" not in flags): if not confirmwarning( "Price change for %s (%f) has been above 'warn_change'. Please confirm!" % (symbol, price["priceChange"])): continue if "skip_change" in flags: if ctx.obj["skip_critical"]: alert( "Price change for %s (%f) has been above 'skip_change'. Skipping!" % ( symbol, price["priceChange"], )) continue else: if not confirmalert( "Price change for %s (%f) has been above 'skip_change'. Please confirm to still publish, else feed will be skipped!" % ( symbol, price["priceChange"], )): continue settlement_price = Price(price["price"], quote=symbol, base=price["short_backing_symbol"]) cer = Price(price["cer"], quote=symbol, base=price["short_backing_symbol"]) ctx.bitshares.publish_price_feed(symbol, settlement_price=settlement_price, cer=cer, mssr=price["mssr"], mcr=price["mcr"], account=ctx.config["producer"]) # Always ask for confirmation if this flag is set to true if "confirm" in ctx.config and ctx.config["confirm"]: ctx.bitshares.txbuffer.constructTx() pprint(ctx.bitshares.txbuffer.json()) if not confirmwarning("Please confirm"): return if ctx.bitshares.txbuffer.ops: ctx.bitshares.txbuffer.broadcast()
def add_price(self, p1, p2): if not p1: return p2 return Price(quote=p1['quote'] + p2['quote'], base=p1['base'] + p2['base'])
for feed in feeds: average += feed price_to_publish_in_usd = average / len(feeds) # GETTING USD BTS PRICE USD:BTS price market = Market("BTS:USD") price = market.ticker()['baseSettlement_price'] print(price) price.invert() # invert to allow easier multiplication # BTS:USD price one_usd_bts = price priceinbts = price_to_publish_in_usd * one_usd_bts['price'] pricempa = Price("{} BTS/BTWTY".format(priceinbts)) print(pricempa) #unlock wallet... market.bitshares.wallet.unlock("YOUR UPTICK WALLET UNLOCK CODE") (market.bitshares.publish_price_feed( symbol="BTWTY", settlement_price=pricempa, cer=pricempa * (1 / 1.2), mcr=175, mssr=140, account="roelandp", ))