Esempio n. 1
0
    def history(self, granularity, count):
        """Retrieve past values of a currency.

       Retrieve a certain number of data points from the currency's past.

      Parameters:
        granularity  The granularity of the historic data to query.
        count        Amount of historic datapoints to retrieve.

      Returns:
        A list of dicts of the form {time: string, open: Decimal, close: Decimal} representing
        values at specific instances in time.

      Notes:
        All valid granularities can be found as the keys of the '_granularities' dict object.
    """
        granularity = _granularities[granularity]
        history = self.__server.history(self.__currency, granularity, count)

        # create our own list of dicts with our own set of indices and a reverse ordering where the newest
        # entries are at the lower indices
        values = []
        for value in history:
            values = [{
                'time': parseDate(value['time']),
                'open': Price(Decimal(value['openMid']), self.__pip),
                'close': Price(Decimal(value['closeMid']), self.__pip)
            }] + values
        return values
Esempio n. 2
0
    def check_sl_tp(self, price):
        """ 
        Checks and validate transaction. If price reached stop loss or take profit
        limits, close the transaction.
        """
        p = price.get('value')
        d = price.get('date')
        sl = self.get('stop_loss_price')
        tp = self.get('take_profit_price')
        ttype = self.get('type')

        if ttype == 'BUY':
            if sl >= p:
                sell_price = Price([d, sl])
                self.close(sell_price, 'SL')
            elif tp <= p:
                sell_price = Price([d, tp])
                self.close(sell_price, 'TP')

        if ttype == 'SELL':
            if sl <= p:
                sell_price = Price([d, sl])
                self.close(sell_price, 'SL')
            elif tp >= p:
                sell_price = Price([d, tp])
                self.close(sell_price, 'TP')
Esempio n. 3
0
    def run(self):
        i = 0
        while not self._destroy.is_set():
            if i % 2 == 0:
                self._queue.put({
                    'instrument': 'XAU_USD',
                    'time': '2014-07-09T00:00:00.000000Z',
                    'ask': '0.1111111',
                    'bid': '0.1111110',
                })
            else:
                self._queue.put({
                    'instrument':
                    'XAU_USD',
                    'time':
                    datetime(2014, 7, 9, 12, 0, 0, 0),
                    'ask':
                    Price(Decimal('0.1111111'), Decimal('0.001')),
                    'bid':
                    Price(Decimal('0.1111110'), Decimal('0.001')),
                    'parsed':
                    True,
                })

            i = i + 1
            sleep(0)
Esempio n. 4
0
 def create(self):
     coordinate = self.coordinate.copy()
     coordinate.setsize(self.coordinate.size.x - 0.1, self.coordinate.size.y - 0.1)
     for idx, nom in enumerate(self.nominal):
         self.coins.append(Coin(self.screen_w, self.screen_h, coordinate, values=Price(nom),
                                number=self.zl_count[idx]))
         self.coins.append(Coin(self.screen_w, self.screen_h, coordinate, values=Price(nom / 100),
                                number=self.gr_count[idx]))
Esempio n. 5
0
    def testDiv(self):
        price = Price(Decimal('12.345678'), Decimal('0.00001'))
        price = price / Decimal('3.918')
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '3.151015')

        price = Price(Decimal('12.345678'), Decimal('0.00001'))
        price = Decimal('3.918') / price
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '0.317358')
Esempio n. 6
0
    def testAdd(self):
        price = Price(Decimal('12.345678'), Decimal('0.01'))
        price = price + Decimal('2')
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '14.346')

        price = Price(Decimal('12.345678'), Decimal('0.01'))
        price = Decimal('2') + price
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '14.346')
Esempio n. 7
0
    def testSub(self):
        price = Price(Decimal('12.345678'), Decimal('1'))
        price = price - Decimal('5')
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '7.3')

        price = Price(Decimal('12.345678'), Decimal('1'))
        price = Decimal('5') - price
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '-7.3')
Esempio n. 8
0
    def testMul(self):
        price = Price(Decimal('12.345678'), Decimal('0.0001'))
        price = price * Decimal('4.12345')
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '50.90679')

        price = Price(Decimal('12.345678'), Decimal('0.0001'))
        price = Decimal('4.12345') * price
        self.assertIsInstance(price, Price)
        self.assertEqual(str(price), '50.90679')
Esempio n. 9
0
    def price(self) -> Price:
        if self._exact_price is not None:
            return Price(self._exact_price)

        lower = self.lower_bound * self._base.lower
        upper = self.upper_bound * self._base.upper

        if self.sub1:
            return Price(lower, upper, ufilter=lambda f: f - 1)

        return Price(lower, upper)
Esempio n. 10
0
    def balance(self):
        """
        :rtype: Price
        """
        data = json.loads(os.system('electrum getbalance'))

        balance = 0.0
        if 'confirmed' in data:
            return Price(int(float(data['confirmed']) * self.BITCOIN_MULTIPLIER))
        else:
            return Price(0)
Esempio n. 11
0
def price_load(coin: str):
    print("開始載入 %s 之瀏覽器" % coin)
    driver_for_max = setup_driver()
    TW = Price("TW", coin, driver_for_max)
    TW.update_price()
    driver_for_hitbtc = setup_driver()
    US = Price("US", coin, driver_for_hitbtc)
    US.update_price()
    runtimes = 0
    keep_arbitrage(US, TW, coin, runtimes)

    return
Esempio n. 12
0
def parsePrice(currency, price):
    """Parse a price value.

    Parameters:
      price  A dict object containing a 'time' value (string) and two prices, 'ask' and 'bid' (both
             strings).

    Returns:
      A dict object containing 'time' (datetime) and 'ask' and 'bid' (both Price objects).
  """
    return {
        'time': parseDate(price['time']),
        'ask': Price(Decimal(price['ask']), currency.pip()),
        'bid': Price(Decimal(price['bid']), currency.pip())
    }
Esempio n. 13
0
def test_five_differents_books():
    assert price_for(item(reference='A', quantity=1),
                     item(reference='B', quantity=1),
                     item(reference='C', quantity=1),
                     item(reference='D', quantity=1),
                     item(reference='E', quantity=1)) == Price(
                         (8 + 8 + 8 + 8 + 8) * 0.75)
Esempio n. 14
0
 def inner_permutations(cls,
                        initial: int) -> Generator[TripleModel, None, None]:
     for phase1 in range(0, 6 + 1):  # [0, 6] inclusive
         for decay1 in (2, 3):
             for phase2 in range(1, 7 - phase1 +
                                 1):  # [1, 7 - phase1] inclusive
                 yield cls(Price(initial), phase1, decay1, phase2)
Esempio n. 15
0
 def draw(self, price: Price = Price()):
     if self.count == price:
         self.lock = False
         self.widget.setColor((0, 200, 0))
     else:
         self.widget.setColor((200, 0, 0))
     self.widget.draw()
Esempio n. 16
0
 def __init__(self, w: int, h: int, cord: tuple):
     super().__init__(w, h)
     self.par = Rectangle(cord)
     self.counter_cor = Rectangle((0.8, 0.9, 1, 0.99))
     self.price = Price()
     self.resize(w, h)
     pygameAssets.Button.screen = self.screen
     self.elements = []
Esempio n. 17
0
def test_random():
    items = [
        item(reference=any_reference(1, 1, chars="ABCDE"), quantity=1)
        for _ in range(random.randint(10, 400))
    ]
    max_cart_price = Price(8) * len(items)
    min_cart_price = max_cart_price.discount(PercentDiscount.percent(25))
    assert min_cart_price <= price_for(*items) <= max_cart_price
Esempio n. 18
0
    def get_rates(self):
        self.price = Price()

        jsonfile = readurl(base_url, ".koinex.json")

        usdinrrate = get_exchangerate()

        #highest_bid is your effective sell price (i.e. someone is ready to buy for that price)
        if cfg.QUOTETYPE == "highest_bid":  #sell
            self.nativePrice.btc = float(
                jsonfile['stats']['inr']['BTC']['highest_bid'])
            self.nativePrice.ltc = float(
                jsonfile['stats']['inr']['LTC']['highest_bid'])
            self.nativePrice.eth = float(
                jsonfile['stats']['inr']['ETH']['highest_bid'])
            if cfg.ENABLEBCH:
                self.nativePrice.bch = float(
                    jsonfile['stats']['inr']['BCHABC']['highest_bid'])
            self.nativePrice.tusd = float(
                jsonfile['stats']['inr']['TUSD']['highest_bid'])
            self.price.btc = self.nativePrice.btc / usdinrrate
            self.price.ltc = self.nativePrice.ltc / usdinrrate
            self.price.eth = self.nativePrice.eth / usdinrrate
            self.price.bch = self.nativePrice.bch / usdinrrate
            self.price.tusd = self.nativePrice.tusd / usdinrrate
            self.store_rates(dbutils.TRANSACTION_SELL)
        elif cfg.QUOTETYPE == "lowest_ask":  #buy
            self.nativePrice.btc = float(
                jsonfile['stats']['inr']['BTC']['lowest_ask'])
            self.nativePrice.ltc = float(
                jsonfile['stats']['inr']['LTC']['lowest_ask'])
            self.nativePrice.eth = float(
                jsonfile['stats']['inr']['ETH']['lowest_ask'])
            if cfg.ENABLEBCH:
                self.nativePrice.bch = float(
                    jsonfile['stats']['inr']['BCHABC']['lowest_ask'])
            self.nativePrice.tusd = float(
                jsonfile['stats']['inr']['TUSD']['lowest_ask'])
            self.price.btc = self.nativePrice.btc / usdinrrate
            self.price.ltc = self.nativePrice.ltc / usdinrrate
            self.price.eth = self.nativePrice.eth / usdinrrate
            self.price.bch = self.nativePrice.bch / usdinrrate
            self.price.tusd = self.nativePrice.tusd / usdinrrate
            self.store_rates(dbutils.TRANSACTION_BUY)
        else:
            self.nativePrice.btc = float(jsonfile['prices']['inr']['BTC'])
            self.nativePrice.ltc = float(jsonfile['prices']['inr']['LTC'])
            self.nativePrice.eth = float(jsonfile['prices']['inr']['ETH'])
            if cfg.ENABLEBCH:
                self.nativePrice.bch = float(
                    jsonfile['prices']['inr']['BCHABC'])
            self.nativePrice.tusd = float(jsonfile['prices']['inr']['TUSD'])
            self.price.btc = self.nativePrice.btc / usdinrrate
            self.price.ltc = self.nativePrice.ltc / usdinrrate
            self.price.eth = self.nativePrice.eth / usdinrrate
            self.price.bch = self.nativePrice.bch / usdinrrate
            self.price.tusd = self.nativePrice.tusd / usdinrrate
Esempio n. 19
0
 def __init__(self, d: dict):
     self.name = d['name']
     self.price = Price(d['price'])
     self.shelf = d['shelf']
     self.number = d['number']
     self.number_lay = 0
     self.number_recipe = 0
     self.is_clicked = False
     self.is_checked = False
Esempio n. 20
0
def price_bundle(bundle):
    discount = [
        PercentDiscount.none(),
        PercentDiscount.none(),
        PercentDiscount.percent(5),
        PercentDiscount.percent(10),
        PercentDiscount.percent(20),
        PercentDiscount.percent(25)
    ]
    return (Price(8) * bundle.size).discount(discount[bundle.size])
Esempio n. 21
0
 def get_rates(self):
    self.price = Price()
    self.price.btc = self.get_price("BTC")
    if cfg.ENABLEBCH:
       self.price.bch = self.get_price("BCH")
    self.price.ltc = self.get_price("LTC")
    self.price.eth = self.get_price("ETH")
    self.price.tusd = 1
    self.store_rates(dbutils.TRANSACTION_SELL)
    self.store_rates(dbutils.TRANSACTION_BUY)
Esempio n. 22
0
    def get_rates(self):
        self.price = Price()
        jsonfile = readurl(base_url, ".koinex.json")

        usdinrrate = get_exchangerate()

        self.price.btc = float(jsonfile['prices']['BTC']) / usdinrrate
        self.price.ltc = float(jsonfile['prices']['LTC']) / usdinrrate
        self.price.eth = float(jsonfile['prices']['ETH']) / usdinrrate
        self.price.bch = float(jsonfile['prices']['BCH']) / usdinrrate
Esempio n. 23
0
def test_random():
    items = [
        item(label=any_label(1, 1, chars="ABCDE"), quantity=1)
        for _ in range(random.randint(10, 400))
    ]
    max_cart_price = Price(8) * len(items)
    min_cart_price = max_cart_price.discount(PercentDiscount.percent(25))
    card_price = price_for(*items)
    print(items)
    print(min_cart_price, card_price, max_cart_price)
    assert min_cart_price <= card_price <= max_cart_price
Esempio n. 24
0
class Exchange:
    price = Price()
    nativePrice = Price()
    native = True  #If this exchange is not in USD, then assign it to false.
    name = "Exchange"
    dbutil = DatabaseUtils()

    def __init__(self):
        pass

    def __str__(self):
        return self.name

    def get_rates(self):
        "Default rates. This method is supposed to be overridden by derived class and price should be set based on live quote for the exchange."
        self.price.btc = 1
        self.price.ltc = 2
        self.price.eth = 3
        self.price.bch = 4
        self.price.tusd = 1

    def print_price(self):
        print("\n")
        print("btc:" + str(self.price.btc))
        print("ltc:" + str(self.price.ltc))
        print("eth:" + str(self.price.eth))
        print("bch:" + str(self.price.bch))
        print("tusd:" + str(self.price.tusd))

    def store_rates(self, transactionType):
        self.dbutil.set_current_price(self.name, transactionType, "BTC",
                                      self.price.btc)
        self.dbutil.set_current_price(self.name, transactionType, "LTC",
                                      self.price.ltc)
        self.dbutil.set_current_price(self.name, transactionType, "ETH",
                                      self.price.eth)
        self.dbutil.set_current_price(self.name, transactionType, "BCH",
                                      self.price.bch)
        self.dbutil.set_current_price(self.name, transactionType, "TUSD",
                                      self.price.tusd)
Esempio n. 25
0
    def determine_incremental_price_list(price, incremental_quantities):
        """
        Determines an incremental price list parallel to the incremental quantity list

        :type price: Price
        :type incremental_quantities: List[Quantity]
        :return: Incremental price list
        :rtype: List[Price]
        """
        incremental_prices = []

        for incremental_quantity in incremental_quantities:
            incremental_prices.append(Price(int(price) * int(incremental_quantity)))

        return incremental_prices
Esempio n. 26
0
 def getPricesFromDate(self, date):
     r = requests.get('http://pricewatch.northeurope.cloudapp.azure.com/api/price/' + date)
     result = json.loads(r.text)
     
     prices = []
     for prPrice in result:
         price = Price(
             prPrice["Id"],
             prPrice["Price"],
             prPrice["InsteadOfPrice"],
             prPrice["Date"],
             prPrice["Productid"]
         )
         prices.append(price)
     return prices
Esempio n. 27
0
def price():
    price = Price(request.form.get("price"), request.form.get("Currency"))
    incity = Place(request.form.get("incity")).name
    outcity = Place(request.form.get("outcity")).name
    date = "{}/{}/{}".format(request.form.get("day"),
                             request.form.get("month"),
                             request.form.get("year"))
    ids = cities_ids(incity, outcity, "files\\ids.txt")
    #coefficient = price.currency_coefficient("USD")
    coefficient = 0.037216
    while True:
        try:
            search_id = get_search_id(ids[0], ids[1], date=date)
            break
        except:
            pass
    while True:
        try:

            get_tickets_json("files\\initial_tickets.json", search_id)
            dct = tickets_info(inpath="files\\initial_tickets.json",
                               search_id=search_id,
                               outpath="files\\final_tickets.json")
            break
        except:
            pass
    info = []
    place_in = Place(incity)
    place_out = Place(outcity)
    place_in.get_coordinates()
    place_out.get_coordinates()
    get_map([place_in, place_out],
            "templates\\map.html",
            location=list(place_out.coordinates))
    for num in dct.values():
        info.append([
            "Departure time: {}".format(num["departureTime"]),
            "Arrival time: {}".format(num["ar_time"]),
            "Number of stops: {}".format(num["stops"]),
            "Company: {}".format(num["companyName"]), "Price: {}".format(
                str(round(num["price"] / coefficient,
                          2))), "Transport: {}".format(num["mode"]),
            "Departure station: {}".format(num["stations_dep"][0]["name"]),
            "Arrival station: {}".format(num["stattions_ar"][0]["name"]),
            num["url"]
        ])
    new_price = price.price * coefficient
    return render_template("price.html", new_price=new_price, info=info)
Esempio n. 28
0
    def __init__(self, ticker, quantity=0, price=None):
        """
        Initialization.
        Args:
            ticker (str): Ticker of the asset.
            quantity (int, optional): Number of units of the asset. Default is zero.
        """

        assert ticker is not None, "ticker symbol is a mandatory argument."
        assert isinstance(quantity, int), "quantity must be integer."

        self._ticker = ticker
        self._quantity = quantity

        # if price is None:
        price_db = PriceDB.instance().data
        price = price_db.loc[(price_db.date == price_db.loc[
            price_db.itemcode == ticker, 'date'].max()) &
                             (price_db.itemcode == ticker), 'price'].values[0]
        self._price = Price(price, 'KRW')
Esempio n. 29
0
    def updatePrices(self):
        if len(self.symbols) < 1:
            return
        params = dict(symbols=','.join(self.symbols))
        c = CONFIG["TradeKing"]
        r = Session()
        r.auth = OAuth1(c["CONSUMER_KEY"], c["CONSUMER_SECRET"],
                        c["OAUTH_TOKEN"], c["OAUTH_SECRET"])
        try:
            r = r.get(self.url, params=params)
        except Exception:
            return False
        if CONFIG["debug"]:
            print(self.symbols)
            print(params)
        try:
            prices = r.json()["response"]["quotes"]["quote"]
        except Exception:
            return False
        if len(self.symbols) == 1:
            prices = [prices]

        for price in prices:
            ticker = price["symbol"]

            sign = price["chg_sign"]

            percent = price["pchg"]
            try:
                movement = '{:.2f}'.format(round(float(price["chg"]), 2))
                last_price = '{:.2f}'.format(round(float(price["last"]), 2))
            except ValueError:
                movement = price["chg"]
                last_price = price["last"]

            price_obj = Price(ticker, last_price, sign, movement, percent)
            self.updatePrice(price_obj)
        return True
Esempio n. 30
0
def fluctuation_notify(coin: str, exchange_name, Maxlen=120, amplitude=0.02):
    ring = deque(maxlen=Maxlen)

    driver_for_max = setup_driver()
    exchange = Price(exchange_name, coin, driver_for_max)
    exchange.update_price()
    new_value = float(exchange.price_list[1][0][0])
    ring.append(new_value)
    while True:
        new_value = float(exchange.price_list[1][0][0])
        top = max(ring)
        bottom = min(ring)

        if new_value < top * (1 - amplitude):
            rate = (top - new_value) / top
            send_line_fluc(coin, exchange.host, amplitude, rate)

        if new_value > bottom * (1 + amplitude):
            rate = (bottom - new_value) / bottom
            send_line_fluc(coin, exchange.host, amplitude, rate)
        ring.append(new_value)
        print("新增價格", coin, exchange.host, new_value)
        exchange.update_price()