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')
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
def test_load_from_disk(self): prices = {} Price.loadHistoricalPricesFromDisk(prices, "./source/test/price_test_1.txt") self.assertEqual(prices["A",datetime.date(1234,5,6)], 1) self.assertEqual(prices["A",datetime.date(2345,6,7)], 2) self.assertEqual(prices["B",datetime.date(1234,5,6)], 1.1) self.assertEqual(prices["C",datetime.date(2000,1,1)], 1.23)
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)
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]))
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
def test_load_from_disk(self): prices = {} Price.loadHistoricalPricesFromDisk(prices, "./source/test/price_test_1.txt") self.assertEqual(prices["A", datetime.date(1234, 5, 6)], 1) self.assertEqual(prices["A", datetime.date(2345, 6, 7)], 2) self.assertEqual(prices["B", datetime.date(1234, 5, 6)], 1.1) self.assertEqual(prices["C", datetime.date(2000, 1, 1)], 1.23)
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 = []
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')
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')
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')
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')
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
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)
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)
def cacheUrls(tickerList, currencyList, investments, history, startDate, prices, forceReload = False): urls = [] if history: for ticker in history.currentTickers(): urls.append(Price.currentPriceUrl(ticker)) else: for ticker in tickerList: urls.append(Price.currentPriceUrl(ticker)) if not forceReload: lastDates = Price.lastDates(prices, currencyList + tickerList) else: lastDates = {} for ticker in currencyList + tickerList: if ticker not in lastDates: lastDates[ticker] = startDate currencyInfo = [] tickerInfo = [] for currency in currencyList: if date.today() > lastDates[currency]: url = Price.historicalPricesUrl(currency, lastDates[currency], date.today(), currency = True) urls.extend(url) currencyInfo.append((currency, lastDates[currency], url)) for ticker in tickerList: if history: lastHeld = history.lastHeld(ticker) firstHeld = history.firstHeld(ticker) else: lastHeld = date.today() firstHeld = startDate if lastHeld - timedelta(days = 1) > lastDates[ticker]: url = Price.historicalPricesUrl(ticker, max(lastDates[ticker], firstHeld), lastHeld, currency = False) urls.extend(url) tickerInfo.append((ticker, max(lastDates[ticker], firstHeld), lastHeld, url)) urlCache = urlcache(urls) urlCache.cache_urls() return urlCache, currencyInfo, tickerInfo
def test_load_current_from_web(self): urls = [] currentTickers = ["BRK-B", "NWBD.L"] for ticker in currentTickers: urls.append(Price.currentPriceUrl(ticker)) urlCache = urlcache(urls) urlCache.cache_urls() prices = {} prices[('USD', datetime.date.today() - datetime.timedelta(1))] = 1.5 Price.loadCurrentPricesFromWeb(currentTickers, prices, urlCache)
def test_load_current_from_web(self): urls = [] currentTickers = ["BRK-B","NWBD.L"] for ticker in currentTickers: urls.append(Price.currentPriceUrl(ticker)) urlCache = urlcache(urls) urlCache.cache_urls() prices = {} prices[('USD', datetime.date.today() - datetime.timedelta(1))] = 1.5 Price.loadCurrentPricesFromWeb(currentTickers, prices, urlCache)
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()) }
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)
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()
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)
class TestHelpers(TestCase): def setUp(self): self.pricing = Price() def test_get_price(self): date = get_random_date() response = self.pricing.get_price_at_date(date) self.assertTrue(type(response["price"]) is float)
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
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
def test_load_currency_from_web(self): urls = [] currentTickers = ["EUR","USD"] for ticker in currentTickers: urls.extend(Price.historicalPricesUrl(ticker, datetime.datetime(2011, 1, 1), datetime.datetime(2018, 1, 1), currency = True)) urlCache = urlcache(urls) urlCache.cache_urls() prices = {} for ticker in currentTickers: Price.getCurrencyHistory(ticker, datetime.datetime(2011, 1, 1), datetime.datetime(2018, 1, 1), prices, urlCache)
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
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
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)
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])
class Counter(Object_display): 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 = [] def draw(self) -> None: pygame.draw.rect(Object_display.screen, (0, 153, 153), self.position.to_rectangle()) self.counter.draw() def resize(self, w: int, h: int) -> None: self.position = self.par.copy() * Point((w, h)) self.counter_pos = self.counter_cor.copy() * Point((w, h)) self.counter = pygameAssets.Button(self.counter_pos[0], self.counter_pos[1], self.counter_pos[2], self.counter_pos[3], color=(0, 0, 0), text=str(self.price)) def test_product(self, element: Element, lay: bool = None) -> None: if self.position.is_in_area(element.current_image.position.point): if lay is True: self.elements.append(element.current_image) element.current_image.on_counter = True element.lay() elif lay is False: element.current_image.on_counter = False self.elements.remove(element.current_image) self.price.clear() for i in self.elements: if i.on_counter: self.price += i.price self.counter.setText(str(self.price)) else: element.current_image.on_counter = False if lay is True: element.lay()
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')
def test_load_currency_from_web(self): urls = [] currentTickers = ["EUR", "USD"] for ticker in currentTickers: urls.extend( Price.historicalPricesUrl(ticker, datetime.datetime(2011, 1, 1), datetime.datetime(2018, 1, 1), currency=True)) urlCache = urlcache(urls) urlCache.cache_urls() prices = {} for ticker in currentTickers: Price.getCurrencyHistory(ticker, datetime.datetime(2011, 1, 1), datetime.datetime(2018, 1, 1), prices, urlCache)
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)
def compareShare(ticker): global newHistory global newInvestments global newPortfolio # Get price info about the ticker newPrices = {} Price.loadHistoricalPricesFromDisk(newPrices) urlCache, currencyInfo, tickerInfoList = cacheUrls([ticker], [], [], None, history.transactions[0].date, newPrices, forceReload = True) Price.loadCurrentPricesFromWeb([ticker], newPrices, urlCache) for tickerInfo in tickerInfoList: Price.loadHistoricalPricesFromWeb(tickerInfo[0], tickerInfo[1], tickerInfo[2], newPrices, urlCache) Price.fixPriceGaps(newPrices) #urlCache.clean_urls() # Generate a new portfolio file with all tickers replaced with this one. newTransactions = [] for tran in history.transactions: if tran.action == "BUY" or tran.action == "SELL": newTran = copy.copy(tran) newTran.ticker = ticker value = newTran.number * newTran.price newTran.price = newPrices[(ticker, tran.date)] newTran.number = value / newTran.price newTransactions.append(newTran) transaction.writeTransactions(newTransactions, TEMP_PORTFOLIO) # Now build an alternate history based on these new transactions print "Building portfolio history..." newHistory, newInvestments = createHistory(TEMP_PORTFOLIO, forceReload = True) print "Done" print "" newPortfolio = newHistory.getPortfolio(date.today()) # And print some info print u"Hypothetical / real capital gain: \N{pound sign}%.2f / \N{pound sign}%.2f"%(newPortfolio.capitalGain() / 100, portfolio.capitalGain() / 100) print u"Real portfolio dividends received: \N{pound sign}%.2f"%(portfolio.totalDividends() / 100) print "Real portfolio yield: %.2f%%"%(((portfolio.totalDividends() * 365.0 / (history.endDate() - history.startDate()).days)) * 100 / history.averageValue(history.startDate(), history.endDate()))
def createHistory(portfolioFile = None, forceReload = False): # Read all transactions from disk transactions = transaction.readTransactions(portfolioFile) startDate = transactions[0].date # And all investments investments = investment.learn_investments(transactions) # Build a list of all mentioned tickers tickerList = [] for trans in transactions: if trans.ticker not in tickerList: tickerList.append(trans.ticker) # Hard code currency list. !! Should pick these out of investments really. currencyList = ["USD", "Euro", "NOK"] # Build a history of our transactions history = History(transactions) # Load what we've got from disk prices = {} Price.loadHistoricalPricesFromDisk(prices) # Start reading all the HTML we're going to need now. urlCache, currencyInfo, tickerInfo = cacheUrls(tickerList, currencyList, investments, history, startDate, prices, forceReload) # Load currency histories for currency in currencyInfo: Price.getCurrencyHistory(currency[0], currency[1], date.today(), prices, urlCache) # Load current prices from the Web Price.loadCurrentPricesFromWeb(history.currentTickers(), prices, urlCache) # Now load historical prices from the Web for ticker in tickerInfo: Price.loadHistoricalPricesFromWeb(ticker[0], ticker[1], ticker[2], prices, urlCache) # Fill in any gaps Price.fixPriceGaps(prices) # Now save any new data to disk Price.savePricesToDisk(prices) # And fill in any gaps between the last noted price and today Price.fixLastPrices(prices, history.currentTickers()) # Give the prices to our history history.notePrices(prices) # Done with all the HTML that we read #urlCache.clean_urls() return (history, investments)
def run_level(n): level_path = 'level' + str(LEVEL_PATHS[n]) response_text = send_request(BASE_URL + level_path).text price = Price.parse(response_text) print "NIVEL {!s}: {}\nTexto: {}\nPreco: R${}\n\n".format(n+1, BASE_URL + level_path, response_text, price)
from price import Price import unittest parsing_tests = { "no symbol": ["1.00", None], "standard price": ["R$1,99", Price(1, 99)], "no cents": ["R$500", Price(500)], "whitespace": ["R $4 12,53", Price(412, 53)], "point": ["R$ 9.000,50", Price(9000, 50)], "point and whitespace": ["R$ 1. 20 0,2 5", Price(1200, 25)], "even more whitespace": ["R$ 7 02 1 , 0 9", Price(7021, 9)], "line break": ["Terno e gravata por R$ 35\n0, 99", Price(350, 99)], "html tags": ["Geladeira Brastemp <b>super oferta: <u>R$ 799,99</u></b><br>", Price(799,99)], "numbers before price": ["Desconto 35%: Côtes du Rhone 2009 só R$15,90/garrafa", Price(15, 90)]} class TestPrice(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a, b) return test if __name__ == '__main__': for test_name in parsing_tests.keys(): test_method_name = "test_" + test_name.replace(" ", "_") parsing_test = test_generator(Price.parse(parsing_tests[test_name][0]), parsing_tests[test_name][1]) parsing_test.__doc__ = "Testing parsing of string '%s'" % parsing_tests[test_name][0] setattr(TestPrice, test_method_name, parsing_test) unittest.main()
def tidy(): # Sorts the local price database into a sensible order Price.writeSorted(history.prices)