Esempio n. 1
0
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")
Esempio n. 2
0
def fees(ctx, currency):
    """ List fees
    """
    from bitsharesbase.operationids import getOperationNameForId
    from bitshares.market import Market

    market = Market("%s:%s" % (currency, "BTS"))
    ticker = market.ticker()
    if "quoteSettlement_price" in ticker:
        price = ticker.get("quoteSettlement_price")
    else:
        price = ticker.get("latest", 0)
    price.invert()

    chain = Blockchain(bitshares_instance=ctx.bitshares)
    feesObj = chain.chainParameters().get("current_fees")
    fees = feesObj["parameters"]

    t = [["Operation", "Type", "Fee", currency]]

    for fee in fees:
        for f in fee[1]:
            data = [
                highlight(getOperationNameForId(fee[0])),
                detail(f),
                detail(Amount({"amount": fee[1].get(f, 0), "asset_id": "1.3.0"})),
                detail(
                    price * Amount({"amount": fee[1].get(f, 0), "asset_id": "1.3.0"})
                ),
            ]
            t.append(data)
    print_table(t)
Esempio n. 3
0
def market_ticker(market_pair: hug.types.text, api_key: hug.types.text, request, hug_timer=5):
	"""Given a valid market pair, retrieve ticker data & output as JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'market_ticker')

		try:
		  target_market = Market(market_pair)
		except:
		  # Market is not valid
		  return {'valid_market': False,
				  'valid_key': True,
				  'took': float(hug_timer)}

		target_market_ticker_data = target_market.ticker()

		return {'market_ticker': target_market_ticker_data,
				'market': market_pair,
				'valid_market': True,
				'valid_key': True,
				'took': float(hug_timer)}

	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
Esempio n. 4
0
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 ticker_test():
    start = time.time()
    bitshares = BitShares(node=TEST_CONFIG['node'])
    market = Market('OPEN.BTC:BTS', bitshares_instance=bitshares)
    ticker = market.ticker()
    print(ticker)
    end = time.time()
    print("Total time: {}".format(end - start))
Esempio n. 6
0
def ticker(ctx, market):
    """ Show ticker of a market
    """
    market = Market(market, bitshares_instance=ctx.bitshares)
    ticker = market.ticker()
    t = [["key", "value"]]
    for key in ticker:
        t.append([key, str(ticker[key])])
    print_table(t)
Esempio n. 7
0
def ticker(ctx, market):
    """ Show ticker of a market
    """
    market = Market(market, bitshares_instance=ctx.bitshares)
    ticker = market.ticker()
    t = PrettyTable(["key", "value"])
    t.align = 'r'
    for key in ticker:
        t.add_row([key, str(ticker[key])])
    click.echo(str(t))
Esempio n. 8
0
 def convert_asset(from_value, from_asset, to_asset):
     """ Converts asset to another based on the latest market value
         :param from_value: Amount of the input asset
         :param from_asset: Symbol of the input asset
         :param to_asset: Symbol of the output asset
         :return: Asset converted to another asset as float value
     """
     market = Market('{}/{}'.format(from_asset, to_asset))
     ticker = market.ticker()
     latest_price = ticker.get('latest', {}).get('price', None)
     return from_value * latest_price
Esempio n. 9
0
    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,
        }
Esempio n. 10
0
 def get_converted_asset_amount(self, asset):
     """
     Returns asset amount converted to base asset amount
     """
     base_asset = self.market['base']
     quote_asset = Asset(asset['symbol'], bitshares_instance=self.bitshares)
     if base_asset['symbol'] == quote_asset['symbol']:
         return asset['amount']
     else:
         market = Market(base=base_asset,
                         quote=quote_asset,
                         bitshares_instance=self.bitshares)
         return market.ticker()['latest']['price'] * asset['amount']
Esempio n. 11
0
    def convert_asset(from_value, from_asset, to_asset):
        """ Converts asset to another based on the latest market value

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

        return truncate((from_value * latest_price), precision)
Esempio n. 12
0
def convert_asset(blockchain_instance: Any, from_value: float, from_asset: str,
                  to_asset: str) -> float:
    """Converts asset to another based on the latest market value.

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

    return round((from_value * latest_price), precision)
Esempio n. 13
0
def main(rpchost, rpcport, expiration, broadcast, proposer):
    rpc = GrapheneAPI(rpchost, rpcport)
    expiration = datetime.utcfromtimestamp(time.time() + int(expiration)).strftime(
        "%Y-%m-%dT%H:%M:%S"
    )

    # Get current fees
    obj = rpc.get_object("2.0.0")[0]
    old_fees = obj["parameters"]["current_fees"]
    scale = int(obj["parameters"]["current_fees"]["scale"]) / 1e4
    core_asset = rpc.get_asset("1.3.0")

    # Get ticker/current price
    market = Market(config.market)
    ticker = market.ticker()
    # core_exchange_rate = float(ticker["core_exchange_rate"])
    settlement_price = float(ticker["quoteSettlement_price"])

    # Translate native fee in core_asset fee
    new_fees = config.native_fees.copy()
    for opName in new_fees:
        for f in new_fees[opName]:
            if config.force_integer_core_fee:
                new_fees[opName][f] = int(
                    int(config.native_fees[opName][f] / scale * settlement_price)
                    * 10 ** core_asset["precision"]
                )
            else:
                new_fees[opName][f] = int(
                    config.native_fees[opName][f]
                    * 10 ** core_asset["precision"]
                    / scale
                    * settlement_price
                )

    tx = rpc.propose_fee_change(proposer, expiration, new_fees, broadcast)
    new_fees = tx["operations"][0][1]["proposed_ops"][0]["op"][1]["new_parameters"][
        "current_fees"
    ]

    # Show differences from previous to new fees
    pprint(DeepDiff(old_fees, new_fees))

    if not broadcast:
        print("=" * 80)
        print("Set --broadcast if the transaction shall be broadcast!")
Esempio n. 14
0
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 book(node=''):

    while 1:
        time.sleep(1)
        market = Market(BitPAIR,
                        bitshares_instance=BitShares(node),
                        mode='head')
        call = Decimal(time.time())
        last = market.ticker()['latest']
        slast = '%.16f' % last
        elapsed = Decimal(time.time()) - call
        raw = market.orderbook(limit=40)
        bids = raw['bids']
        asks = raw['asks']
        sbidp = [('%.16f' % bids[i]['price']) for i in range(len(bids))]
        saskp = [('%.16f' % asks[i]['price']) for i in range(len(asks))]
        sbidv = [('%.2f' % float(bids[i]['quote'])).rjust(12, ' ')
                 for i in range(len(bids))]
        saskv = [('%.2f' % float(asks[i]['quote'])).rjust(12, ' ')
                 for i in range(len(asks))]
        bidv = [float(bids[i]['quote']) for i in range(len(bids))]
        askv = [float(asks[i]['quote']) for i in range(len(asks))]
        cbidv = list(np.cumsum(bidv))
        caskv = list(np.cumsum(askv))
        cbidv = [('%.2f' % i).rjust(12, ' ') for i in cbidv]
        caskv = [('%.2f' % i).rjust(12, ' ') for i in caskv]

        print("\033c")
        print('')
        print('litepresence - microDEX - proof of concept')
        print('')
        print(time.ctime(), )
        print('                            ', ('%.17f' % elapsed), '   ', node)
        print('')
        print('                        LAST', slast[:10], slast[10:], '   ',
              BitPAIR)
        print('')
        print('            ', sbidv[0], '  ', (sbidp[0])[:10], (sbidp[0])[10:],
              '   ', (saskp[0])[:10], (saskp[0])[10:], (saskv[0]))
        print('                                           ', 'BIDS', '   ',
              'ASKS')
        for i in range(1, len(sbidp)):
            print(cbidv[i], sbidv[i], '  ', (sbidp[i])[:10], (sbidp[i])[10:],
                  '   ', (saskp[i])[:10], (saskp[i])[10:], saskv[i], caskv[i])
Esempio n. 16
0
    def convert_fee(self, fee_amount, fee_asset):
        """ Convert fee amount in BTS to fee in fee_asset

            :param float | fee_amount: fee amount paid in BTS
            :param Asset | fee_asset: fee asset to pay fee in
            :return: float | amount of fee_asset to pay fee
        """
        if isinstance(fee_asset, str):
            fee_asset = Asset(fee_asset)

        if fee_asset['id'] == '1.3.0':
            # Fee asset is BTS, so no further calculations are needed
            return fee_amount
        else:
            if not self.core_exchange_rate:
                # Determine how many fee_asset is needed for core-exchange
                temp_market = Market(base=fee_asset, quote=Asset('1.3.0'))
                self.core_exchange_rate = temp_market.ticker(
                )['core_exchange_rate']
            return fee_amount * self.core_exchange_rate['base']['amount']
def loop_test():
    bitshares = BitShares(node=TEST_CONFIG['node'])
    market = Market('OPEN.BTC:BTS', bitshares_instance=bitshares)
    count = 1
    total_time = 0
    while count < MAX_ITER:
        try:
            start = time.time()

            ticker = market.ticker()
            print(ticker)

            end = time.time()
            runtime = end - start
            print("Total time: {}".format(runtime))

            count += 1
            total_time += runtime
        except Exception as e:
            print(e)
            print('Connection Closed')
            break
    return total_time
Esempio n. 18
0
def fees(ctx, currency):
    """ List fees
    """
    from bitsharesbase.operationids import getOperationNameForId
    from bitshares.market import Market

    market = Market("%s:%s" % (currency, "BTS"))
    ticker = market.ticker()
    if "quoteSettlement_price" in ticker:
        price = ticker.get("quoteSettlement_price")
    else:
        price = ticker.get("latest", 0)

    chain = Blockchain(bitshares_instance=ctx.bitshares)
    feesObj = chain.chainParameters().get("current_fees")
    scale = feesObj["scale"]
    fees = feesObj["parameters"]

    t = PrettyTable(["Operation", "Type", "Fee", currency])
    t.align = "l"
    t.align["Fee"] = "r"
    t.align[currency] = "r"

    for fee in fees:
        for f in fee[1]:
            t.add_row([
                getOperationNameForId(fee[0]), f,
                str(Amount({
                    "amount": fee[1].get(f, 0),
                    "asset_id": "1.3.0"
                })),
                str(price * Amount({
                    "amount": fee[1].get(f, 0),
                    "asset_id": "1.3.0"
                }))
            ])
    click.echo(t)
Esempio n. 19
0
    def get_remote_data(self):
        return_data = []
        data = self.get_available_pair()

        for symbol in data['symbols'].keys():
            for anchor in data['anchors'].keys():
                try:
                    if symbol != anchor:
                        print('dealing {} : {}'.format(symbol, anchor))
                        market = Market('{}:{}'.format(symbol, anchor))
                        ticker = market.ticker()

                        symbol_ticker = {
                            'name':
                            data['symbols'][symbol]['name'],
                            'pair':
                            '{}/{}'.format(data['symbols'][symbol]['symbol'],
                                           data['anchors'][anchor]['symbol']),
                            'price':
                            ticker['latest']['price'],
                            'volume':
                            ticker['quoteVolume'].amount,
                            'volume_anchor':
                            ticker['baseVolume'].amount
                        }

                        # print(symbol_ticker)

                        if symbol_ticker['price'] > 0 and symbol_ticker[
                                'volume'] > 0:
                            return_data.append(symbol_ticker)
                except Exception as e:
                    print(e)

        # print(return_data)
        return return_data
Esempio n. 20
0
    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":
            ref_asset = self.assetconf(symbol, "ref_asset")
            market = Market("%s:%s" % (ref_asset, backing_symbol))
            ticker = {k: float(v) for k, v in market.ticker().items()}
            price = eval(self.assetconf(symbol, "formula").format(**ticker))
        else:
            raise ValueError("Missing 'reference' for asset %s" % symbol)

        self.price_result[symbol] = {
            "price": price,
            "cer": price * self.assetconf(symbol, "core_exchange_factor"),
            "number": 1,
            "short_backing_symbol": backing_symbol,
            "mean": price,
            "median": price,
            "weighted": price,
            "mssr": self.assetconf(symbol, "maximum_short_squeeze_ratio"),
            "mcr": self.assetconf(symbol, "maintenance_collateral_ratio"),
            "std": 0.0,
            "number": 1,
        }
Esempio n. 21
0
from bitshares import BitShares
import math
import config

if __name__ == "__main__":
    graphene = GrapheneAPI(config.wallet_host, config.wallet_port)
    bts = BitShares(config.witness_url)

    # Get current fees
    core_asset = graphene.get_asset("1.3.0")
    committee_account = graphene.get_account("committee-account")
    proposals = bts.rpc.get_proposed_transactions(committee_account["id"])

    # Get ticker/current price
    market = Market(config.market)
    ticker = market.ticker()
    core_exchange_rate = float(ticker["core_exchange_rate"])
    settlement_price = float(ticker["quoteSettlement_price"])

    for proposal in proposals:
        print("Proposal: %s" % proposal["id"])

        prop_op = proposal["proposed_transaction"]["operations"]

        if len(prop_op) > 1:
            print(" - [Warning] This proposal has more than 1 operation")

        for op in prop_op:

            if op[0] == 31:
Esempio n. 22
0
def dex_sell():

    # update wallet unlock to low latency node
    zprint('SELL')
    nds = race_read('nodes.txt')
    if isinstance(nds, list):
        nodes = nds
    account = Account(USERNAME,
                      bitshares_instance=BitShares(nodes, num_retries=0))
    market = Market(BitPAIR,
                    bitshares_instance=BitShares(nodes, num_retries=0),
                    mode='head')
    try:
        market.bitshares.wallet.unlock(PASS_PHRASE)
    except:
        pass
    # attempt to sell 10X or until satisfied
    def sell(price, amount):
        confirm.destroy()
        zprint('CONFIRMED')
        attempt = 1
        while attempt:
            try:
                details = market.sell(price, amount)
                print(details)
                attempt = 0
            except:
                zprint(("sell attempt %s failed" % attempt))
                attempt += 1
                if attempt > 10:
                    zprint('sell aborted')
                    return
                pass

    # interact with tkinter
    confirm = Tk()
    if market.bitshares.wallet.unlocked():
        price = sell_price.get()
        amount = sell_amount.get()
        if price == '':
            price = 0.5 * float(market.ticker()['latest'])
            sprice = 'market RATE'
        if amount == '':
            amount = ANTISAT
        try:
            price = float(price)
            amount = float(amount)
            if price != SATOSHI:
                sprice = '%.16f' % price
            assets = float(account.balance(BitASSET))
            if amount > (0.998 * assets):
                amount = 0.998 * assets
            samount = str(amount)
            sorder = str('CONFIRM SELL ' + samount + ' ' + BitASSET + ' @ ' +
                         sprice)

            if amount > 0:
                confirm.title(sorder)
                Button(confirm,
                       text='CONFIRM SELL',
                       command=lambda: sell(price, amount)).grid(row=1,
                                                                 column=0,
                                                                 pady=8)
                Button(confirm, text='INVALIDATE',
                       command=confirm.destroy).grid(row=2, column=0, pady=8)
            else:
                confirm.title('NO ASSETS TO SELL')
                Button(confirm, text='OK',
                       command=confirm.destroy).grid(row=2, column=0, pady=8)
        except:
            confirm.title('INVALID SELL ORDER')
            Button(confirm, text='OK', command=confirm.destroy).grid(row=2,
                                                                     column=0,
                                                                     pady=8)
    else:
        confirm.title('YOUR WALLET IS LOCKED')
        Button(confirm, text='OK', command=confirm.destroy).grid(row=2,
                                                                 column=0,
                                                                 pady=8)
    confirm.geometry('500x100+800+175')
    confirm.lift()
    confirm.call('wm', 'attributes', '.', '-topmost', True)
Esempio n. 23
0
from getpass import getpass

account = "alfredo-worker"
proposer = "oxarbitrage.a699"
vesting_id = "1.13.1608"

bitshares = BitShares(
    nobroadcast=False,
    bundle=True,
    proposer=proposer,
    proposal_expiration=60 * 60 * 24 * 2,
)
set_shared_bitshares_instance(bitshares)
market = Market("USD:BTS")
price = market.ticker()["quoteSettlement_price"]

bitshares.wallet.unlock(getpass())
vesting = Vesting(vesting_id)

print("Claiming Vesting Balance: %s" % vesting.claimable)
bitshares.vesting_balance_withdraw(vesting["id"],
                                   amount=vesting.claimable,
                                   account=account)

print("Buying as much bitUSD at price up to %s or %s" %
      (price * 0.90, (price * 0.90).copy().invert()))
market.buy(price * 0.9, Amount(3200, "USD"), killfill=True, account=account)

print("Worker alfredo payment - 15 days")
bitshares.transfer("oxarbitrage.a699", 3200, "USD", account=account)
Esempio n. 24
0
        "wss://openledger.hk/ws",  #location: "Hong Kong"
        "wss://bitshares-api.wancloud.io/ws",  #location:  "China"
        "wss://dex.rnglab.org",  #location: "Netherlands"
        "wss://dexnode.net/ws",  #location: "Dallas, USA"
        "wss://kc-us-dex.xeldal.com/ws",  #location: "Kansas City, USA"
        "wss://la.dexnode.net/ws",  #location: "Los Angeles, USA"
    ]

    bitshares_api_node = BitShares(full_node_list, nobroadcast=False)

    # Set the API node above as the shared Bitshares instance for the rest of the script
    set_shared_bitshares_instance(bitshares_api_node)

    # 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.

    # Calculate the current value of Hertz in USD
    hertz_value = get_hertz_feed(hertz_reference_timestamp,
Esempio n. 25
0
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)}
Esempio n. 26
0
feeds = []
if len(coincap_missing_assets) == 0:
    feeds.append(bit20_value_cc)
if len(cmc_missing_assets) == 0:
    feeds.append(bit20_value_cmc)

if len(feeds) > 0:
    average = 0
    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(
Esempio n. 27
0
from bitshares.market import Market
from bts_spread_mapper import get_bts_config

config_file = "safe/bitshares.ini"

passphrase, account = get_bts_config(config_file)

market = Market("USD:BTS")
print(market.ticker())
market.bitshares.wallet.unlock(passphrase)
#print(market.sell(50, 1))  # sell 1 USD for 50 BTS/USD, way above current spot exch rate.
Esempio n. 28
0
def dex(  # Public AND Private API Bitshares
        command, amount=ANTISAT, price=None,
        depth=1, expiration=ANTISAT):

    MARKET.bitshares.wallet.unlock(PASS_PHRASE)
    ACCOUNT.refresh()

    if command == 'buy':

        # buy relentlessly until satisfied or currency exhausted
        print(('Bitshares API', command))
        if price is None:
            price = ANTISAT
        print(('buying', amount, 'at', price))
        attempt = 1
        currency = float(ACCOUNT.balance(BitCURRENCY))
        if amount > 0.998 * currency * price:
            amount = 0.998 * currency * price
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.buy(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("buy attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('buy aborted')
                        return
                    pass
        else:
            print('no currency to buy')

    if command == 'sell':

        # sell relentlessly until satisfied or assets exhausted
        expiration = 86400 * 7
        print(('Bitshares API', command))
        if price is None:
            price = SATOSHI
        print(('selling', amount, 'at', price))
        attempt = 1
        assets = float(ACCOUNT.balance(BitASSET))
        if amount > 0.998 * assets:
            amount = 0.998 * assets
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.sell(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("sell attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('sell aborted')
                        return
                    pass
        else:
            print('no assets to sell')

    if command == 'cancel':

        # cancel all orders in this MARKET relentlessly until satisfied
        print(('Bitshares API', command))  
        orders = MARKET.accountopenorders()
        print((len(orders), 'open orders to cancel'))
        if len(orders):
            attempt = 1   
            order_list = []      
            for order in orders:
                order_list.append(order['id'])
            while attempt:
                try:
                    details = MARKET.cancel(order_list)
                    print (details)
                    attempt = 0
                except:
                    print((attempt, 'cancel failed', order_list))
                    attempt += 1
                    if attempt > 10:
                        print ('cancel aborted')
                        return
                    pass    

    if command == 'orders':

        # dictionary of open orders in traditional format:
        # orderNumber, orderType, market, amount, price
        print(('Bitshares API', command))
        orders = []
        for order in MARKET.accountopenorders():
            orderNumber = order['id']
            asset = order['base']['symbol']
            currency = order['quote']['symbol']
            amount = float(order['base'])
            price = float(order['price'])
            orderType = 'buy'
            if asset == BitASSET:
                orderType = 'sell'
                price = 1 / price
            orders.append({'orderNumber': orderNumber,
                           'orderType': orderType,
                           'market': BitPAIR, 'amount': amount,
                           'price': price})
        for o in orders:
            print (o)
        if len(orders) == 0:
            print ('no open orders')
        return orders

    if command == 'market_balances':

        # dictionary of currency and assets in this MARKET
        print(('Bitshares API', command))
        currency = float(ACCOUNT.balance(BitCURRENCY))
        assets = float(ACCOUNT.balance(BitASSET))
        balances = {'currency': currency, 'assets': assets}
        print (balances)
        return balances

    if command == 'complete_balances':

        # dictionary of ALL account balances
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        print (balances)
        return balances

    if command == 'book':

        # dictionary of 4 lists containing bid/ask volume/price
        print(('Bitshares API', command))
        raw = MARKET.orderbook(limit=depth)
        bids = raw['bids']
        asks = raw['asks']
        bidp = [float(bids[i]['price']) for i in range(len(bids))]
        bidv = [float(bids[i]['quote']) for i in range(len(bids))]
        askp = [float(asks[i]['price']) for i in range(len(asks))]
        askv = [float(asks[i]['quote']) for i in range(len(asks))]
        book = {'bidp': bidp, 'bidv': bidv, 'askp': askp, 'askv': askv}
        # print(book)
        print(('ask', ('%.8f' % book['askp'][0])))  # lowest ask price
        print(('bid', ('%.8f' % book['bidp'][0])))  # highest bid price
        # print(book['bidv'][0]) #highest bid volume
        # print(book['askv'][0]) #lowest ask volume
        return book

    if command == 'last':

        # the most recent transation in this MARKET
        print(('Bitshares API', command))
        raw = MARKET.ticker()['latest']
        price = float(raw)
        # print (price)
        return price

    if command == 'account_value':

        # dictionary account value in BTS BTC and USD
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        btc_value = 0
        for asset, amount in list(balances.items()):
            market_pair = 'OPEN.BTC:' + asset
            market = Market(market_pair)
            price = float(market.ticker()['latest'])
            try:
                value = amount / price
            except:
                value = 0
            if value < 0.0001:
                value = 0
            else:
                if asset != 'USD':
                    price = 1 / (price + SATOSHI)
                print((('%.4f' % value), 'OPEN.BTC', ('%.2f' % amount),
                       asset, '@', ('%.8f' % price)))
                btc_value += value

        market_pair = 'OPEN.BTC:USD'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        usd_value = btc_value * price
        market_pair = 'OPEN.BTC:BTS'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        bts_value = btc_value * price
        print((('%.2f' % bts_value), 'BTS',
             ('%.4f' % btc_value), 'OPEN.BTC',
             ('%.2f' % usd_value), 'bitUSD'))
        return bts_value, btc_value, usd_value

    if command == 'blocktime':

        current_block = CHAIN.get_current_block_num()
        blocktime = CHAIN.block_time(current_block)
        blocktimestamp = CHAIN.block_timestamp(current_block) - 18000
        now = time.time()
        latency = now - blocktimestamp
        print(('block               :', current_block))
        # print(('blocktime           :', blocktime))
        # print(('stamp               :', blocktimestamp))
        # print(('ctime(stamp)        :', time.ctime(blocktimestamp)))
        # print(('now                 :', now))
        print(('dex_rate latency    :', ('%.2f' % latency)))
        return current_block, blocktimestamp, latency
Esempio n. 29
0
from bitshares.market import Market
import pandas as pd
import numpy as np
#from bitshares.price import Price


market = Market("BRIDGE.BTC:BTS")
market1 = Market("RUDEX.BTC:BTS")
market2 = Market("GDEX.BTC:BTS")
market3 = Market("EASYDEX.BTC:BTS")
market4 = Market("OPEN.BTC:BTS")

latest = (market.ticker())['latest']
latest1 = (market1.ticker())['latest']
latest2 = (market2.ticker())['latest']
latest3 = (market3.ticker())['latest']
latest4 = (market4.ticker())['latest']

print('CryptoBridge:'+ str(latest))
print('RuDex :'+ str(latest1))
print('GDEX :' + str(latest2))
print('EASYDEX :' + str(latest3))
print('OPENLEDGER :' + str(latest4))
print()

print('Arbitrage RuDex-BRIDGE:', (float(latest1))-(float(latest)), 'BTS')
print('Arbitrage GDEX-RuDex:', (float(latest2))-(float(latest1)), 'BTS')
print('Arbitrage GDEX-EasyDex:', (float(latest2))-(float(latest3)), 'BTS')

print()
data = market.ticker()
Esempio n. 30
0
def dex(  # Public AND Private API Bitshares
        command, amount=ANTISAT, price=None,
        depth=1, expiration=ANTISAT):

    MARKET = Market(BitPAIR, bitshares_instance=BitShares(nodes(), num_retries=0))
    CHAIN = Blockchain(bitshares_instance=BitShares(nodes(), num_retries=0), mode='head')
    #MARKET.bitshares.wallet.unlock(PASS_PHRASE)
    ACCOUNT.refresh()

    if command == 'buy':

        # buy relentlessly until satisfied or currency exhausted
        print(('Bitshares API', command))
        if price is None:
            price = ANTISAT
        print(('buying', amount, 'at', price))
        attempt = 1
        currency = float(ACCOUNT.balance(BitCURRENCY))
        if amount > 0.998 * currency * price:
            amount = 0.998 * currency * price
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.buy(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("buy attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('buy aborted')
                        return
                    pass
        else:
            print('no currency to buy')

    if command == 'sell':

        # sell relentlessly until satisfied or assets exhausted
        expiration = 86400 * 7
        print(('Bitshares API', command))
        if price is None:
            price = SATOSHI
        print(('selling', amount, 'at', price))
        attempt = 1
        assets = float(ACCOUNT.balance(BitASSET))
        if amount > 0.998 * assets:
            amount = 0.998 * assets
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.sell(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("sell attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('sell aborted')
                        return
                    pass
        else:
            print('no assets to sell')

    if command == 'cancel':

        # cancel all orders in this MARKET relentlessly until satisfied
        print(('Bitshares API', command))  
        orders = MARKET.accountopenorders()
        print((len(orders), 'open orders to cancel'))
        if len(orders):
            attempt = 1   
            order_list = []      
            for order in orders:
                order_list.append(order['id'])
            while attempt:
                try:
                    details = MARKET.cancel(order_list)
                    print (details)
                    attempt = 0
                except:
                    print((attempt, 'cancel failed', order_list))
                    attempt += 1
                    if attempt > 10:
                        print ('cancel aborted')
                        return
                    pass    

    if command == 'orders':

        servers = nodes()
        orders_list =[]
        satisfied = 0
        while not satisfied: #while len set triplicate
            for n in servers:
                sorders = [str(i) for i in orders_list]
                if (len(sorders) >= 3) and len(set(sorders[-3:])) == 1:
                    orders = orders_list[-1]
                    satisfied = 1
                else:
                    MARKET = Market(BitPAIR, bitshares_instance=BitShares(n, num_retries=0))
                    MARKET.bitshares.wallet.unlock(PASS_PHRASE)
                    ACCOUNT.refresh()

                    # dictionary of open orders in traditional format:
                    # orderNumber, orderType, market, amount, price
                    print(('Bitshares API', command))
                    orders = []
                    for order in MARKET.accountopenorders():
                        orderNumber = order['id']
                        asset = order['base']['symbol']
                        currency = order['quote']['symbol']
                        amount = float(order['base'])
                        price = float(order['price'])
                        orderType = 'buy'
                        if asset == BitASSET:
                            orderType = 'sell'
                            price = 1 / price
                        orders.append({'orderNumber': orderNumber,
                                       'orderType': orderType,
                                       'market': BitPAIR, 'amount': amount,
                                       'price': price})
                    orders_list.append(orders)


        for o in orders:
            print (o)
        if len(orders) == 0:
            print ('no open orders')
        return orders

    if command == 'market_balances':

        # dictionary of currency and assets in this MARKET
        print(('Bitshares API', command))
        currency = float(ACCOUNT.balance(BitCURRENCY))
        assets = float(ACCOUNT.balance(BitASSET))
        balances = {'currency': currency, 'assets': assets}
        print (balances)
        return balances

    if command == 'complete_balances':

        # dictionary of ALL account balances
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        print (balances)
        return balances

    if command == 'book':

        try:
            opened = 0
            while not opened:
                with open('book.txt', 'r') as f:
                    book = f.read()
                    opened = 1
        except Exception as e:
            print (e)
            print ('book.txt failed, try again...')
            pass
        return literal(book)

    if command == 'last':

        try:
            opened = 0
            while not opened:
                with open('last.txt', 'r') as f:
                    last = f.read()
                    opened = 1
        except Exception as e:
            print (e)
            print ('last.txt failed, try again...')
            pass
        return literal(last)

    if command == 'account_value':

        # dictionary account value in BTS BTC and USD
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        btc_value = 0
        for asset, amount in list(balances.items()):
            market_pair = 'OPEN.BTC:' + asset
            market = Market(market_pair)
            price = float(market.ticker()['latest'])
            try:
                value = amount / price
            except:
                value = 0
            if value < 0.0001:
                value = 0
            else:
                if asset != 'USD':
                    price = 1 / (price + SATOSHI)
                print((('%.4f' % value), 'OPEN.BTC', ('%.2f' % amount),
                       asset, '@', ('%.8f' % price)))
                btc_value += value

        market_pair = 'OPEN.BTC:USD'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        usd_value = btc_value * price
        market_pair = 'OPEN.BTC:BTS'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        bts_value = btc_value * price
        print((('%.2f' % bts_value), 'BTS',
             ('%.4f' % btc_value), 'OPEN.BTC',
             ('%.2f' % usd_value), 'bitUSD'))
        return bts_value, btc_value, usd_value

    if command == 'blocktime':

        current_block = CHAIN.get_current_block_num()
        blocktime = CHAIN.block_time(current_block)
        blocktimestamp = CHAIN.block_timestamp(current_block) - 18000
        now = time.time()
        latency = now - blocktimestamp
        print(('block               :', current_block))
        # print(('blocktime           :', blocktime))
        # print(('stamp               :', blocktimestamp))
        # print(('ctime(stamp)        :', time.ctime(blocktimestamp)))
        # print(('now                 :', now))
        print(('dex_rate latency    :', ('%.2f' % latency)))
        return current_block, blocktimestamp, latency
Esempio n. 31
0
        bbitasset = account.balance(base)
        print(bitasset)

        # подготавливаем переменную вида "1 CNY"
        amount = Amount(bitasset, base)
        print(amount)

        # ставим ордер на откуп нашего МК
        market.sell(0.00001, amount, 8640000, False, our_account) 

else:
    # займов нет, надо брать :)
    # расчитываем сколько юаней можем напечатать

    # получаем цену погашения
    ticker = market.ticker()
    data = ticker.get('quoteSettlement_price')
    feed_price = data.get('price')
    print(feed_price)

    # получаем баланс в шарах на аккаунте
    balance = account.balance(quote)
    # всегда берем целую часть шар для займа. остаток оставляем на комиссии
    collateral = int(balance.get('amount'))
    print(collateral)

    if collateral > 0:
        # находим сколько можно напечатать юаней с нашим перекрытием
        debt = (1/feed_price)/init_ratio*collateral
        print(debt)