Пример #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")
Пример #2
0
def cancel(ctx, market, account):
    """
    Cancel Orders in Mkt, (Eg: cancel USD/BTS --account name)

    :param ctx: context
    :param market: market e.g. USD/BTS
    :param account: name of your bitshares acct
    :return: Success or Fail message
    """
    try:
        my_market = Market(market)
        ctx.bitshares.bundle = True
        my_market.cancel(
            [x["id"] for x in my_market.accountopenorders(account)],
            account=account)
        response = ctx.bitshares.txbuffer.broadcast()
        log.info(response)
        if response is not None:
            log.info(
                f'Cancelled all orders on Market: {market} for account: {account}'
            )
        else:
            log.info(f'No orders to cancel! {market} for account: {account}')

    except bitshares.exceptions.AssetDoesNotExistsException:
        log.info(f"Asset does not exist: {market}")
    except graphenecommon.exceptions.AccountDoesNotExistsException:
        log.info(f"Account does not exist: {account}")
Пример #3
0
def orderbook(ctx, market):
    market = Market(market, bitshares_instance=ctx.bitshares)
    orderbook = market.orderbook()
    ta = {}
    ta["bids"] = PrettyTable(["quote", "base", "price"])
    ta["bids"].align = "r"
    for order in orderbook["bids"]:
        ta["bids"].add_row([
            str(order["quote"]),
            str(order["base"]),
            "{:f} {}/{}".format(order["price"],
                                order["base"]["asset"]["symbol"],
                                order["quote"]["asset"]["symbol"]),
        ])

    ta["asks"] = PrettyTable([
        "price",
        "base",
        "quote",
    ])
    ta["asks"].align = "r"
    ta["asks"].align["price"] = "l"
    for order in orderbook["asks"]:
        ta["asks"].add_row([
            "{:f} {}/{}".format(order["price"],
                                order["base"]["asset"]["symbol"],
                                order["quote"]["asset"]["symbol"]),
            str(order["base"]),
            str(order["quote"])
        ])
    t = PrettyTable(["bids", "asks"])
    t.add_row([str(ta["bids"]), str(ta["asks"])])
    click.echo(t)
Пример #4
0
def market_orderbook(market_pair: hug.types.text, api_key: hug.types.text, request, hug_timer=5):
	"""Given a valid market pair (e.g. USD:BTS) and your desired orderbook size limit, output the market pair's orderbook (buy/sell order) information in JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'market_orderbook')

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

		target_market_orderbook_data = target_market.orderbook(limit=50)

		return {'market_orderbook': target_market_orderbook_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)}
Пример #5
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)
Пример #6
0
def test_get_own_last_trade_taker_sell(base_account, ro_worker, other_worker):
    """Test for https://github.com/Codaone/DEXBot/issues/708."""
    worker1 = ro_worker
    worker3 = base_account()
    market1 = Market(worker1.worker["market"])

    # Fill worker's order from different account
    # Note this order is significantly bigger by amount and lower by price than worker's order
    sell_orders1 = worker1.get_own_sell_orders()
    to_buy = sell_orders1[0]['base']['amount'] * 1.5
    buy_price = sell_orders1[0]['price'] * 1.2
    log.debug('Buying {} @ {} by worker3 from worker1'.format(
        to_buy, buy_price))
    tx = market1.buy(buy_price, to_buy, account=worker3)
    log.debug(tx)

    # Bot uses last own trade price and acts as a taker
    worker1.is_center_price_dynamic = True
    worker1.cp_from_last_trade = True
    worker1['bootstrapped'] = True
    time.sleep(1.1)
    worker1.check_orders()

    # Expect correct last trade
    result = worker1.get_own_last_trade()
    assert result['price'] == pytest.approx(
        buy_price, rel=(10**-worker1.market['base']['precision']))
Пример #7
0
def market_24hr_vol(market_pair: hug.types.text,
                    api_key: hug.types.text,
                    hug_timer=5):
    """Given a valid market_pair (e.g. USD:BTS), output their 24hr market volume in JSON."""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        try:
            target_market = Market(market_pair)
        except:
            # Market is not valid
            return {
                'valid_market': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        return {
            'market_volume_24hr': target_market.volume24h(),
            '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)}
Пример #8
0
    def mergeMarket_before(self, iso, pair, tag, start, stop):

        asset_a = pair[0]
        asset_b = pair[1]
        rpc = iso.bts.rpc
        if not self.subscribed:
            s_id = rpc.get_subscription_id()
            subs = rpc.subscribe_to_market(s_id, asset_a["id"], asset_b["id"])
            self._s_id = s_id
            self._tags.append("!" + str(s_id))
            self.subscribed = True

        from bitshares.market import Market
        self.market = Market(base=asset_b,
                             quote=asset_a,
                             blockchain_instance=iso.bts)

        orders = self.market.orderbook()
        if self.initfetch:
            trades = self.market.trades(limit=100, start=start, stop=stop)
        else:
            trades = iso.getMarketBuckets(self.market["base"],
                                          self.market["quote"],
                                          start=start,
                                          stop=stop)

        return (
            orders,
            trades,
        )
Пример #9
0
    def mergeMarket_before(self, iso, pair, tag):

        #iso._wait_online(timeout=3) # will raise exception
        #if not(iso.is_connected()):
        #	raise Exception

        asset_a = pair[0]
        asset_b = pair[1]
        rpc = iso.bts.rpc
        if not self.subscribed:
            s_id = rpc.get_subscription_id()
            subs = rpc.subscribe_to_market(s_id, asset_a["id"], asset_b["id"])
            self._s_id = s_id
            self._tags.append("!" + str(s_id))
            self.subscribed = True

        from bitshares.market import Market
        self.market = Market(tag, bitshares_instance=iso.bts)

        orders = self.market.orderbook()
        trades = self.market.trades(limit=100, raw=True)

        return (
            orders,
            trades,
        )
Пример #10
0
    def __init__(self, sett, **kwargs):
        """
        Инициализация класса, рынков и получение цены BTS

        :param set sett: настройки класса
            str quote - актив, стоимость которого считаем
            str base - актив, в котором считаем стоимость
            list additional_assets - дополнительные рынки для расчета, кроме BTS
            list usdt_assets - дополнительные рынки, стоимость которых равна 
                               стоимости актива base
            float base_depth - глубина расчета цены в стаканах в активе base
            float history_depth - глубина расчета цены совершенных сделок в 
                                  активе base
            int price_precision - количество знаков после запятой, для
                                  отображения цен
            int orderbook_limit - максимальное количество сделок из стакана
                                  получаемое от ноды
            int history_limit - максимальное количество сделок получаемое из
                                истории от ноды
            int history_period - максимальное количество дней, за которые
                                 берется история
            set viz_account - данные аккаунта для публикации в блокчейне VIZ
        """
        self.sett = sett
        self.quote_market = Market(self.sett['quote'] + ':BTS')
        self.base_market = Market('BTS:' + self.sett['base'])
        book = self.base_market.orderbook(limit=1)
        self.price = {}
        self.price['BTS'] = (book['asks'][0]['price'] + 
                             book['bids'][0]['price']) / 2
        self.bids = []
        self.asks = []
Пример #11
0
    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')
Пример #12
0
    def get_usdt_orderbook(self):
        """
        Функция для проверки ордеров в стаканах пар указанные в параметре
        self.sett['usdt_assets']

        Функция получает из сети BitShares данные из всех стаканов указанных в
        параметре self.sett['usdt_assets'] и формирует выборку на основе этих
        данных. Результаты ее работы сохраняются в переменных класса self.bids и
        self.asks
        """
        for asset in self.sett['usdt_assets']:
            market = Market(self.sett['quote'] + ':' + asset)
            book = market.orderbook(
                limit=self.sett['orderbook_limit']
            )
            for bid in book['bids']:
                amount = bid['base']['amount']
                bid = Order(
                    bid['quote'], 
                    Amount(amount / self.price['BTS'], 'BTS')
                )
                if not self.create_bids([bid]):
                    break
            for ask in book['asks']:
                amount = ask['base']['amount']
                ask = Order(
                    ask['quote'], 
                    Amount(amount / self.price['BTS'], 'BTS')
                )
                if not self.create_asks([ask]):
                    break
Пример #13
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)}
Пример #14
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))
Пример #16
0
def cancelall(ctx, market, account):
    """ Cancel all orders of an account in a market
    """
    market = Market(market)
    ctx.bitshares.bundle = True
    market.cancel([x["id"] for x in market.accountopenorders(account)],
                  account=account)
    print_tx(ctx.bitshares.txbuffer.broadcast())
Пример #17
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)
Пример #18
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))
Пример #19
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
Пример #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":
            # 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,
        }
Пример #21
0
def dummy():
    btseth = (Market("BTS:" + str(sys.argv[1])).orderbook(
        limit=50)['asks'])[1:-1]  #ask selling
    btssmoke = (Market("BTS:" + str(sys.argv[2])).orderbook(limit=50)['bids']
                )  #bid buying
    print(btssmoke)
    amt = float(sys.argv[3])
    eth = str(btseth)[1:int(i1)]
    smoke = str(btssmoke)[1:int(i2)]
    print(eth)
    print(smoke)
    print(out)
    sys.stdout.flush()
Пример #22
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']
Пример #23
0
def trades(ctx, market, limit, start, stop):
    market = Market(market, bitshares_instance=ctx.bitshares)
    t = PrettyTable(["time", "quote", "base", "price"])
    t.align = 'r'
    for trade in market.trades(limit, start=start, stop=stop):
        t.add_row([
            str(trade["time"]),
            str(trade["quote"]),
            str(trade["base"]),
            "{:f} {}/{}".format(trade["price"],
                                trade["base"]["asset"]["symbol"],
                                trade["quote"]["asset"]["symbol"]),
        ])
    click.echo(str(t))
Пример #24
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)
Пример #25
0
def orderbook(ctx, market):
    """ Show the orderbook of a particular market
    """
    market = Market(market, bitshares_instance=ctx.bitshares)
    orderbook = market.orderbook()
    ta = {}
    ta["bids"] = PrettyTable(
        ["quote", "sum quote", "base", "sum base", "price"])
    ta["bids"].align = "r"
    cumsumquote = Amount(0, market["quote"])
    cumsumbase = Amount(0, market["base"])
    for order in orderbook["bids"]:
        cumsumbase += order["base"]
        cumsumquote += order["quote"]
        ta["bids"].add_row([
            str(order["quote"]),
            str(cumsumquote),
            str(order["base"]),
            str(cumsumbase),
            "{:f} {}/{}".format(order["price"],
                                order["base"]["asset"]["symbol"],
                                order["quote"]["asset"]["symbol"]),
        ])

    ta["asks"] = PrettyTable([
        "price",
        "base",
        "sum base",
        "quote",
        "sum quote",
    ])
    ta["asks"].align = "r"
    ta["asks"].align["price"] = "l"
    cumsumquote = Amount(0, market["quote"])
    cumsumbase = Amount(0, market["base"])
    for order in orderbook["asks"]:
        cumsumbase += order["base"]
        cumsumquote += order["quote"]
        ta["asks"].add_row([
            "{:f} {}/{}".format(order["price"],
                                order["base"]["asset"]["symbol"],
                                order["quote"]["asset"]["symbol"]),
            str(order["base"]),
            str(cumsumbase),
            str(order["quote"]),
            str(cumsumquote),
        ])
    t = PrettyTable(["bids", "asks"])
    t.add_row([str(ta["bids"]), str(ta["asks"])])
    click.echo(t)
Пример #26
0
def market_trade_history(market_pair: hug.types.text,
                         api_key: hug.types.text,
                         hug_timer=5):
    """Given a valid market_pair (e.g. USD:BTS) & a TX limit, output the market's trade history in JSON."""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        try:
            target_market = Market(market_pair)
        except:
            # Market is not valid
            return {
                'valid_market': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        temp_market_history = list(target_market.trades(limit=100))

        #print(temp_market_history)
        # (2017-12-24 15:37:21) 55.8699 USD 106.84792 BTS @ 1.912441583 BTS/USD
        market_history_json_list = []
        for market_trade in temp_market_history:
            str_market_trade = str(market_trade).split(
                " @ "
            )  # ["(2017-12-24 15:37:21) 55.8699 USD 106.84792 BTS", "1.912441583 BTS/USD"]
            trade_rate = str_market_trade[1]  # "1.912441583 BTS/USD"
            trade_time = (str_market_trade[0].split(") ")[0]).replace("(", "")
            trade_details = str_market_trade[0].split(") ")[1]
            split_trade = trade_details.split(" ")
            market_history_json_list.append({
                "datetime":
                trade_time.replace(" ", "T"),
                "bought":
                split_trade[0] + " " + split_trade[1],
                "sold":
                split_trade[2] + " " + split_trade[3],
                "rate ":
                trade_rate
            })

        return {
            'market_trade_history': market_history_json_list,
            '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)}
Пример #27
0
def trades(ctx, market, limit, start, stop):
    """ List trades in a market
    """
    market = Market(market, bitshares_instance=ctx.bitshares)
    t = [["time", "quote", "base", "price"]]
    for trade in market.trades(limit, start=start, stop=stop):
        t.append([
            str(trade["time"]),
            str(trade["quote"]),
            str(trade["base"]),
            "{:f} {}/{}".format(trade["price"],
                                trade["base"]["asset"]["symbol"],
                                trade["quote"]["asset"]["symbol"]),
        ])
    print_table(t)
Пример #28
0
def spread(ctx, market, side, min, max, num, total, order_expiration, account):
    """ Place multiple orders

        \b
        :param str market: Market pair quote:base (e.g. USD:BTS)
        :param str side: ``buy`` or ``sell`` quote
        :param float min: minimum price to place order at
        :param float max: maximum price to place order at
        :param int num: Number of orders to place
        :param float total: Total amount of quote to use for all orders
        :param int order_expiration: Number of seconds until the order expires from the books

    """
    from tqdm import tqdm
    from numpy import linspace
    market = Market(market)
    ctx.bitshares.bundle = True

    if min < max:
        space = linspace(min, max, num)
    else:
        space = linspace(max, min, num)

    func = getattr(market, side)
    for p in tqdm(space):
        func(p,
             total / float(num),
             account=account,
             expiration=order_expiration)
    print_tx(ctx.bitshares.txbuffer.broadcast())
Пример #29
0
 def _fetch(self):
     from bitshares.market import Market
     feed = {}
     try:
         for base in self.bases:
             for quote in self.quotes:
                 if quote == base:
                     continue
                 ticker = Market("%s:%s" % (quote, base)).ticker()
                 if hasattr(self,
                            "quoteNames") and quote in self.quoteNames:
                     quote = self.quoteNames[quote]
                 feed[base] = {}
                 if (float(ticker["latest"])) > 0 and float(
                         ticker["quoteVolume"]) > 0:
                     feed[base][quote] = {
                         "price": (float(ticker["latest"])),
                         "volume":
                         (float(ticker["quoteVolume"]) * self.scaleVolumeBy)
                     }
     except Exception as e:
         raise Exception("\nError fetching results from {1}! ({0})".format(
             str(e),
             type(self).__name__))
     return feed
Пример #30
0
def reconnect(BitPAIR, USERNAME, PASS_PHRASE):

    # create fresh websocket connection
    connected = 0
    while not connected:
        # fetch fresh nodes list from subprocess and shuffle it
        nds = race_read('nodes.txt')
        if isinstance(nds, list):
            nodes = nds
        shuffle(nodes)
        node = nodes[0]
        try:
            account = Account(USERNAME,
                              bitshares_instance=BitShares(node,
                                                           num_retries=0))
            market = Market(BitPAIR,
                            bitshares_instance=BitShares(node,
                                                         num_retries=0),
                            mode='head')
            chain = Blockchain(
                bitshares_instance=BitShares(node, num_retries=0), mode='head')
            if chain.get_network()['chain_id'] != ID:
                raise ValueError('Not Mainnet Chain')
            connected = 1
        except:
            pass
    try:
        market.bitshares.wallet.unlock(PASS_PHRASE)
    except:
        pass
    return account, market, nodes, chain
Пример #31
0
# наш коэф. перекрытия
init_ratio = 2.00
max_ratio = 2.10
margin_ratio = 1.75

# наш аккаунт
our_account = "id-b0t"
our_symbol = "CNY"
current_ratio = 0

# наша пара
base = Asset(our_symbol)
quote = Asset("BTS")

# выбираем рынок
market = Market(base, quote)

# открываем свой локальный кошелек
market.bitshares.wallet.unlock("secret_wallet_password")

# получаем аккаунт для работы бота
account = Account(our_account)
print(account)

# проверяем есть ли займы по нашему битассету
cp = account.callpositions
# если есть любые займы
if len(cp) > 0:
    print(cp)
    # проверяем есть ли по юаню
    cp2 = cp.get(our_symbol)