Esempio n. 1
0
    def setUp(self, annotate=True):
        yield super(TestDatabase, self).setUp(annotate=annotate)

        path = os.path.join(self.getStateDir(), 'sqlite')
        if not os.path.exists(path):
            os.makedirs(path)

        self.database = MarketDB(self.getStateDir())

        self.order_id1 = OrderId(TraderId('3'), OrderNumber(4))
        self.order_id2 = OrderId(TraderId('4'), OrderNumber(5))
        self.order1 = Order(self.order_id1, Price(5,
                                                  'EUR'), Quantity(6, 'BTC'),
                            Timeout(3600), Timestamp.now(), True)
        self.order2 = Order(self.order_id2, Price(5,
                                                  'EUR'), Quantity(6, 'BTC'),
                            Timeout(3600), Timestamp.now(), False)

        self.transaction_id1 = TransactionId(TraderId("0"),
                                             TransactionNumber(4))
        self.transaction1 = Transaction(self.transaction_id1,
                                        Price(100, 'BTC'), Quantity(30, 'MC'),
                                        OrderId(TraderId("0"), OrderNumber(1)),
                                        OrderId(TraderId("1"), OrderNumber(2)),
                                        Timestamp(20.0))

        self.payment1 = Payment(MessageId(TraderId("0"), MessageNumber("4")),
                                self.transaction_id1, Quantity(5, 'MC'),
                                Price(6, 'BTC'), WalletAddress('abc'),
                                WalletAddress('def'), PaymentId("abc"),
                                Timestamp(20.0), False)

        self.transaction1.add_payment(self.payment1)
Esempio n. 2
0
 def get_tx_done_block(ask_amount, bid_amount, traded_amount,
                       ask_total_traded, bid_total_traded):
     ask_pair = AssetPair(AssetAmount(ask_amount, 'BTC'),
                          AssetAmount(ask_amount, 'MB'))
     bid_pair = AssetPair(AssetAmount(bid_amount, 'BTC'),
                          AssetAmount(bid_amount, 'MB'))
     ask = Order(OrderId(TraderId('0' * 40), OrderNumber(1)), ask_pair,
                 Timeout(3600), Timestamp.now(), True)
     ask._traded_quantity = ask_total_traded
     bid = Order(OrderId(TraderId('1' * 40), OrderNumber(1)), bid_pair,
                 Timeout(3600), Timestamp.now(), False)
     bid._traded_quantity = bid_total_traded
     tx = Transaction(
         TransactionId(TraderId('0' * 40), TransactionNumber(1)),
         AssetPair(AssetAmount(traded_amount, 'BTC'),
                   AssetAmount(traded_amount, 'MB')),
         OrderId(TraderId('0' * 40), OrderNumber(1)),
         OrderId(TraderId('1' * 40), OrderNumber(1)), Timestamp(0.0))
     tx.transferred_assets.first += AssetAmount(traded_amount, 'BTC')
     tx.transferred_assets.second += AssetAmount(traded_amount, 'MB')
     tx_done_block = MarketBlock()
     tx_done_block.type = 'tx_done'
     tx_done_block.transaction = {
         'ask': ask.to_status_dictionary(),
         'bid': bid.to_status_dictionary(),
         'tx': tx.to_dictionary(),
         'version': MarketCommunity.PROTOCOL_VERSION
     }
     tx_done_block.transaction['ask']['address'], tx_done_block.transaction[
         'ask']['port'] = "1.1.1.1", 1234
     tx_done_block.transaction['bid']['address'], tx_done_block.transaction[
         'bid']['port'] = "1.1.1.1", 1234
     return tx_done_block
Esempio n. 3
0
    def setUp(self):
        yield super(TestDatabase, self).setUp()

        path = os.path.join(self.getStateDir(), 'sqlite')
        if not os.path.exists(path):
            os.makedirs(path)

        self.database = MarketDB(self.getStateDir(), 'market')

        self.order_id1 = OrderId(TraderId(b'3'), OrderNumber(4))
        self.order_id2 = OrderId(TraderId(b'4'), OrderNumber(5))
        self.order1 = Order(self.order_id1, AssetPair(AssetAmount(5, 'BTC'), AssetAmount(6, 'EUR')),
                            Timeout(3600), Timestamp.now(), True)
        self.order2 = Order(self.order_id2, AssetPair(AssetAmount(5, 'BTC'), AssetAmount(6, 'EUR')),
                            Timeout(3600), Timestamp.now(), False)
        self.order2.reserve_quantity_for_tick(OrderId(TraderId(b'3'), OrderNumber(4)), 3)

        self.transaction_id1 = TransactionId(TraderId(b"0"), TransactionNumber(4))
        self.transaction1 = Transaction(self.transaction_id1, AssetPair(AssetAmount(100, 'BTC'), AssetAmount(30, 'MB')),
                                        OrderId(TraderId(b"0"), OrderNumber(1)),
                                        OrderId(TraderId(b"1"), OrderNumber(2)), Timestamp(20.0))

        self.payment1 = Payment(TraderId(b"0"), self.transaction_id1, AssetAmount(5, 'BTC'),
                                WalletAddress('abc'), WalletAddress('def'), PaymentId("abc"), Timestamp(20.0), False)

        self.transaction1.add_payment(self.payment1)
Esempio n. 4
0
 def test_unitize(self):
     """
     Test the unitize method of a Transaction
     """
     self.assertEqual(Transaction.unitize(1, 1), 1)
     self.assertEqual(Transaction.unitize(0.03, 0.02), 0.04)
     self.assertEqual(Transaction.unitize(50, 0.05), 50)
     self.assertEqual(Transaction.unitize(50.1818, 25), 75)
Esempio n. 5
0
    def setUp(self, annotate=True):
        yield super(TestMarketBlock, self).setUp(annotate=annotate)

        self.ask = Ask(
            OrderId(TraderId('0' * 40), OrderNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            Timeout(30), Timestamp(0.0), True)
        self.bid = Ask(
            OrderId(TraderId('1' * 40), OrderNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            Timeout(30), Timestamp(0.0), False)
        self.transaction = Transaction(
            TransactionId(TraderId('0' * 40), TransactionNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            OrderId(TraderId('0' * 40), OrderNumber(1)),
            OrderId(TraderId('1' * 40), OrderNumber(1)), Timestamp(0.0))

        ask_tx = self.ask.to_block_dict()
        ask_tx["address"], ask_tx["port"] = "127.0.0.1", 1337
        bid_tx = self.bid.to_block_dict()
        bid_tx["address"], bid_tx["port"] = "127.0.0.1", 1337

        self.tick_block = MarketBlock()
        self.tick_block.type = 'tick'
        self.tick_block.transaction = {'tick': ask_tx}

        self.cancel_block = MarketBlock()
        self.cancel_block.type = 'cancel_order'
        self.cancel_block.transaction = {
            'trader_id': 'a' * 40,
            'order_number': 1
        }

        self.tx_block = MarketBlock()
        self.tx_block.type = 'tx_init'
        self.tx_block.transaction = {
            'ask': ask_tx,
            'bid': bid_tx,
            'tx': self.transaction.to_dictionary()
        }

        payment = {
            'trader_id': 'a' * 40,
            'transaction_number': 3,
            'transferred': {
                'amount': 3,
                'type': 'BTC'
            },
            'payment_id': 'a',
            'address_from': 'a',
            'address_to': 'b',
            'timestamp': 1234.3,
            'success': True
        }
        self.payment_block = MarketBlock()
        self.payment_block.type = 'tx_payment'
        self.payment_block.transaction = {'payment': payment}
Esempio n. 6
0
    def create_from_start_transaction(self, start_transaction, match_id):
        """
        :type start_transaction: StartTransaction
        :type match_id: str
        :rtype: Transaction
        """
        transaction = Transaction(start_transaction.transaction_id, start_transaction.assets,
                                  start_transaction.recipient_order_id, start_transaction.order_id, Timestamp.now())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info("Transaction created with id: %s, asset pair %s",
                          transaction.transaction_id, transaction.assets)

        return transaction
Esempio n. 7
0
    def setUp(self):
        # Object creation
        self.transaction_id = TransactionId(TraderId("0"),
                                            TransactionNumber(1))
        self.transaction = Transaction(self.transaction_id, Price(100, 'BTC'),
                                       Quantity(30, 'MC'),
                                       OrderId(TraderId('0'), OrderNumber(2)),
                                       OrderId(TraderId('1'), OrderNumber(1)),
                                       Timestamp(0.0))
        self.proposed_trade = Trade.propose(
            MessageId(TraderId('0'), MessageNumber('1')),
            OrderId(TraderId('0'), OrderNumber(2)),
            OrderId(TraderId('1'), OrderNumber(3)), Price(100, 'BTC'),
            Quantity(30, 'MC'), Timestamp(0.0))

        self.tick = Tick(
            MessageId(TraderId('0'), MessageNumber('message_number')),
            OrderId(TraderId('0'), OrderNumber(1)), Price(100, 'BTC'),
            Quantity(5, 'MC'), Timeout(0.0), Timestamp(float("inf")), True)
        self.tick2 = Tick(
            MessageId(TraderId('0'), MessageNumber('message_number')),
            OrderId(TraderId('0'), OrderNumber(2)), Price(100, 'BTC'),
            Quantity(100, 'MC'), Timeout(0.0), Timestamp(float("inf")), True)
        self.order = Order(OrderId(TraderId("0"), OrderNumber(3)),
                           Price(100, 'BTC'), Quantity(30, 'MC'),
                           Timeout(5000), Timestamp(time.time()), False)
        self.order2 = Order(OrderId(TraderId("0"), OrderNumber(4)),
                            Price(100, 'BTC'), Quantity(30, 'MC'), Timeout(5),
                            Timestamp(time.time() - 1000), True)
Esempio n. 8
0
 def test_from_proposed_trade(self):
     """
     Test creating a transaction from a proposed trade
     """
     transaction = Transaction.from_proposed_trade(self.proposed_trade,
                                                   self.transaction_id)
     self.assertEqual(transaction.assets, self.transaction.assets)
Esempio n. 9
0
    def setUp(self):
        # Object creation
        self.transaction_id = TransactionId(TraderId("0"),
                                            TransactionNumber(1))
        self.transaction = Transaction(
            self.transaction_id,
            AssetPair(AssetAmount(100, 'BTC'), AssetAmount(30, 'MC')),
            OrderId(TraderId('0'), OrderNumber(2)),
            OrderId(TraderId('1'), OrderNumber(1)), Timestamp(0.0))
        self.proposed_trade = Trade.propose(
            TraderId('0'), OrderId(TraderId('0'), OrderNumber(2)),
            OrderId(TraderId('1'), OrderNumber(3)),
            AssetPair(AssetAmount(100, 'BTC'), AssetAmount(30, 'MC')),
            Timestamp(0.0))

        self.tick = Tick(
            OrderId(TraderId('0'), OrderNumber(1)),
            AssetPair(AssetAmount(5, 'BTC'), AssetAmount(5, 'MC')), Timeout(0),
            Timestamp(float("inf")), True)
        self.tick2 = Tick(
            OrderId(TraderId('0'), OrderNumber(2)),
            AssetPair(AssetAmount(500, 'BTC'), AssetAmount(5, 'MC')),
            Timeout(0), Timestamp(float("inf")), True)

        self.order_timestamp = Timestamp.now()
        self.order = Order(
            OrderId(TraderId("0"), OrderNumber(3)),
            AssetPair(AssetAmount(50, 'BTC'), AssetAmount(5, 'MC')),
            Timeout(5000), self.order_timestamp, False)
        self.order.set_verified()
        self.order2 = Order(
            OrderId(TraderId("0"), OrderNumber(4)),
            AssetPair(AssetAmount(50, 'BTC'), AssetAmount(5, 'MC')),
            Timeout(5), Timestamp(time.time() - 1000), True)
        self.order2.set_verified()
Esempio n. 10
0
    def create_from_start_transaction(self, start_transaction, match_id):
        """
        :type start_transaction: StartTransaction
        :type match_id: str
        :rtype: Transaction
        """
        transaction = Transaction(start_transaction.transaction_id,
                                  start_transaction.assets,
                                  start_transaction.recipient_order_id,
                                  start_transaction.order_id, Timestamp.now())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info("Transaction created with id: %s, asset pair %s",
                          transaction.transaction_id, transaction.assets)

        return transaction
Esempio n. 11
0
 def test_from_proposed_trade(self):
     # Test from proposed trade
     transaction = Transaction.from_proposed_trade(self.proposed_trade,
                                                   self.transaction_id)
     self.assertEqual(transaction.price, self.transaction.price)
     self.assertEqual(transaction.total_quantity,
                      self.transaction.total_quantity)
     self.assertEqual(transaction.timestamp, self.transaction.timestamp)
Esempio n. 12
0
 def setUp(self):
     # Object creation
     self.transaction_id = TransactionId(TraderId("0"),
                                         TransactionNumber(1))
     self.transaction = Transaction(
         self.transaction_id,
         AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
         OrderId(TraderId('3'), OrderNumber(2)),
         OrderId(TraderId('2'), OrderNumber(1)), Timestamp(0.0))
     self.proposed_trade = Trade.propose(
         TraderId('0'), OrderId(TraderId('0'), OrderNumber(2)),
         OrderId(TraderId('1'), OrderNumber(3)),
         AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
         Timestamp(0.0))
     self.payment = Payment(
         TraderId("0"), TransactionId(TraderId('2'), TransactionNumber(2)),
         AssetAmount(3, 'MB'), WalletAddress('a'), WalletAddress('b'),
         PaymentId('aaa'), Timestamp(4.0), True)
Esempio n. 13
0
 def get_all_transactions(self):
     """
     Return all transactions in the database.
     """
     db_result = self.execute(u"SELECT * FROM transactions")
     return [Transaction.from_database(db_item,
                                       self.get_payments(TransactionId(TraderId(str(db_item[0])),
                                                                       TransactionNumber(db_item[1]))))
             for db_item in db_result]
Esempio n. 14
0
 def setUp(self):
     # Object creation
     self.transaction_id = TransactionId(TraderId("0"),
                                         TransactionNumber(1))
     self.transaction = Transaction(self.transaction_id, Price(100, 'BTC'),
                                    Quantity(30, 'MC'),
                                    OrderId(TraderId('3'), OrderNumber(2)),
                                    OrderId(TraderId('2'), OrderNumber(1)),
                                    Timestamp(0.0))
     self.proposed_trade = Trade.propose(
         MessageId(TraderId('0'), MessageNumber('1')),
         OrderId(TraderId('0'), OrderNumber(2)),
         OrderId(TraderId('1'), OrderNumber(3)), Price(100, 'BTC'),
         Quantity(30, 'MC'), Timestamp(0.0))
     self.payment = Payment(
         MessageId(TraderId("0"), MessageNumber("1")),
         TransactionId(TraderId('2'), TransactionNumber(2)),
         Quantity(3, 'MC'), Price(2, 'BTC'), WalletAddress('a'),
         WalletAddress('b'), PaymentId('aaa'), Timestamp(4.0), True)
Esempio n. 15
0
 def setUp(self):
     # Object creation
     self.memory_transaction_repository = MemoryTransactionRepository("0")
     self.transaction_id = TransactionId(TraderId(b"0"),
                                         TransactionNumber(1))
     self.transaction = Transaction(
         self.transaction_id,
         AssetPair(AssetAmount(10, 'BTC'), AssetAmount(10, 'MB')),
         OrderId(TraderId(b"0"), OrderNumber(1)),
         OrderId(TraderId(b"2"), OrderNumber(2)), Timestamp(0.0))
Esempio n. 16
0
 def setUp(self):
     # Object creation
     self.memory_transaction_repository = MemoryTransactionRepository("0")
     self.transaction_id = TransactionId(TraderId("0"),
                                         TransactionNumber(1))
     self.transaction = Transaction(self.transaction_id, Price(100, 'BTC'),
                                    Quantity(30, 'MC'),
                                    OrderId(TraderId("0"), OrderNumber(1)),
                                    OrderId(TraderId("2"), OrderNumber(2)),
                                    Timestamp(0.0))
Esempio n. 17
0
    def test_from_block(self):
        """
        Test the from block method of a transaction
        """
        block = {
            'tx': {
                'payment_complete': False,
                'status': 'pending',
                'partner_trader_id': '1111111111111111111111111111111111111111',
                'trader_id': '0000000000000000000000000000000000000000',
                'timestamp': 0.0,
                'transferred': {
                    'second': {
                        'amount': 0,
                        'type': 'MB'
                    },
                    'first': {
                        'amount': 0,
                        'type': 'BTC'
                    }
                },
                'partner_order_number': 1,
                'order_number': 1,
                'transaction_number': 1,
                'assets': {
                    'second': {
                        'amount': 30,
                        'type': 'MB'
                    },
                    'first': {
                        'amount': 30,
                        'type': 'BTC'
                    }
                }
            }
        }

        transaction = Transaction.from_block(block)

        self.assertEqual(block['tx']['trader_id'], six.text_type(transaction.transaction_id.trader_id))
        self.assertEqual(block['tx']['transaction_number'], int(transaction.transaction_id.transaction_number))
        self.assertEqual(block['tx']['trader_id'], six.text_type(transaction.order_id.trader_id))
        self.assertEqual(block['tx']['transaction_number'], int(transaction.order_id.order_number))
        self.assertEqual(block['tx']['partner_trader_id'], six.text_type(transaction.partner_order_id.trader_id))
        self.assertEqual(block['tx']['partner_order_number'], int(transaction.partner_order_id.order_number))
        self.assertEqual(block['tx']['timestamp'], float(transaction.timestamp))
        self.assertEqual(block['tx']['assets']['first']['amount'], transaction.assets.first.amount)
        self.assertEqual(block['tx']['assets']['first']['type'], transaction.assets.first.asset_id)
        self.assertEqual(block['tx']['assets']['second']['amount'], transaction.assets.second.amount)
        self.assertEqual(block['tx']['assets']['second']['type'], transaction.assets.second.asset_id)
        self.assertEqual(block['tx']['transferred']['first']['amount'], transaction.transferred_assets.first.amount)
        self.assertEqual(block['tx']['transferred']['first']['type'], transaction.transferred_assets.first.asset_id)
        self.assertEqual(block['tx']['transferred']['second']['amount'], transaction.transferred_assets.second.amount)
        self.assertEqual(block['tx']['transferred']['second']['type'], transaction.transferred_assets.second.asset_id)
Esempio n. 18
0
 def get_transaction(self, transaction_id):
     """
     Return a transaction with a specific id.
     """
     try:
         db_result = self.execute(u"SELECT * FROM transactions WHERE trader_id = ? AND transaction_number = ?",
                                  (unicode(transaction_id.trader_id),
                                   unicode(transaction_id.transaction_number))).next()
     except StopIteration:
         return None
     return Transaction.from_database(db_result, self.get_payments(transaction_id))
Esempio n. 19
0
 def get_transaction(self, transaction_id):
     """
     Return a transaction with a specific id.
     """
     db_result = self.execute(
         u"SELECT * FROM transactions WHERE trader_id = ? AND transaction_number = ?",
         (unicode(transaction_id.trader_id),
          unicode(transaction_id.transaction_number))).fetchone()
     return Transaction.from_database(
         db_result,
         self.get_payments(transaction_id)) if db_result else None
Esempio n. 20
0
    def create_from_proposed_trade(self, proposed_trade, match_id):
        """
        :type proposed_trade: ProposedTrade
        :type match_id: str
        :rtype: Transaction
        """
        transaction = Transaction.from_proposed_trade(proposed_trade, self.transaction_repository.next_identity())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info("Transaction created with id: %s, asset pair %s",
                          transaction.transaction_id, transaction.assets)
        return transaction
Esempio n. 21
0
 def get_all_transactions(self):
     """
     Return all transactions in the database.
     """
     db_result = self.execute(u"SELECT * FROM transactions")
     return [
         Transaction.from_database(
             db_item,
             self.get_payments(
                 TransactionId(TraderId(str(db_item[0])),
                               TransactionNumber(db_item[1]))))
         for db_item in db_result
     ]
Esempio n. 22
0
 def get_transaction(self, transaction_id):
     """
     Return a transaction with a specific id.
     """
     try:
         db_result = self.execute(
             u"SELECT * FROM transactions WHERE trader_id = ? AND transaction_number = ?",
             (unicode(transaction_id.trader_id),
              unicode(transaction_id.transaction_number))).next()
     except StopIteration:
         return None
     return Transaction.from_database(db_result,
                                      self.get_payments(transaction_id))
Esempio n. 23
0
 def setUp(self):
     # Object creation
     self.transaction_id = TransactionId(TraderId("0"), TransactionNumber(1))
     self.transaction = Transaction(self.transaction_id, AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
                                    OrderId(TraderId('3'), OrderNumber(2)),
                                    OrderId(TraderId('2'), OrderNumber(1)), Timestamp(0.0))
     self.proposed_trade = Trade.propose(TraderId('0'),
                                         OrderId(TraderId('0'), OrderNumber(2)),
                                         OrderId(TraderId('1'), OrderNumber(3)),
                                         AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')), Timestamp(0.0))
     self.payment = Payment(TraderId("0"), TransactionId(TraderId('2'), TransactionNumber(2)),
                            AssetAmount(3, 'MB'), WalletAddress('a'), WalletAddress('b'),
                            PaymentId('aaa'), Timestamp(4.0), True)
Esempio n. 24
0
    def create_from_start_transaction(self, start_transaction, match_id):
        """
        :type start_transaction: StartTransaction
        :type match_id: str
        :rtype: Transaction
        """
        assert isinstance(start_transaction,
                          StartTransaction), type(start_transaction)

        transaction = Transaction(start_transaction.transaction_id,
                                  start_transaction.price,
                                  start_transaction.quantity,
                                  start_transaction.recipient_order_id,
                                  start_transaction.order_id, Timestamp.now())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info(
            "Transaction created with id: %s, quantity: %s, price: %s",
            str(transaction.transaction_id), str(transaction.total_quantity),
            str(transaction.price))

        return transaction
Esempio n. 25
0
    def create_from_proposed_trade(self, proposed_trade, match_id):
        """
        :type proposed_trade: ProposedTrade
        :type match_id: str
        :rtype: Transaction
        """
        transaction = Transaction.from_proposed_trade(
            proposed_trade, self.transaction_repository.next_identity())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info("Transaction created with id: %s, asset pair %s",
                          transaction.transaction_id, transaction.assets)
        return transaction
Esempio n. 26
0
    def test_insert_or_update_transaction(self):
        """
        Test the conditional insertion or update of a transaction in the database
        """
        # Test insertion
        self.database.insert_or_update_transaction(self.transaction1)
        transactions = self.database.get_all_transactions()
        self.assertEqual(len(transactions), 1)

        # Test try to update with older timestamp
        before_trans1 = Transaction(self.transaction1.transaction_id, self.transaction1.assets,
                                    self.transaction1.order_id, self.transaction1.partner_order_id,
                                    Timestamp(float(self.transaction1.timestamp) - 1.0))
        self.database.insert_or_update_transaction(before_trans1)
        transaction = self.database.get_transaction(self.transaction1.transaction_id)
        self.assertEqual(float(transaction.timestamp), float(self.transaction1.timestamp))

        # Test update with newer timestamp
        after_trans1 = Transaction(self.transaction1.transaction_id, self.transaction1.assets,
                                   self.transaction1.order_id, self.transaction1.partner_order_id,
                                   Timestamp(float(self.transaction1.timestamp) + 1.0))
        self.database.insert_or_update_transaction(after_trans1)
        transaction = self.database.get_transaction(self.transaction1.transaction_id)
        self.assertEqual(float(transaction.timestamp), float(after_trans1.timestamp))
Esempio n. 27
0
 def get_tx_done_block(ask_amount, bid_amount, traded_amount, ask_total_traded, bid_total_traded):
     ask_pair = AssetPair(AssetAmount(ask_amount, 'BTC'), AssetAmount(ask_amount, 'MB'))
     bid_pair = AssetPair(AssetAmount(bid_amount, 'BTC'), AssetAmount(bid_amount, 'MB'))
     ask = Order(OrderId(TraderId('0' * 40), OrderNumber(1)), ask_pair, Timeout(3600), Timestamp.now(), True)
     ask._traded_quantity = ask_total_traded
     bid = Order(OrderId(TraderId('1' * 40), OrderNumber(1)), bid_pair, Timeout(3600), Timestamp.now(), False)
     bid._traded_quantity = bid_total_traded
     tx = Transaction(TransactionId(TraderId('0' * 40), TransactionNumber(1)),
                      AssetPair(AssetAmount(traded_amount, 'BTC'), AssetAmount(traded_amount, 'MB')),
                      OrderId(TraderId('0' * 40), OrderNumber(1)),
                      OrderId(TraderId('1' * 40), OrderNumber(1)), Timestamp(0.0))
     tx.transferred_assets.first += AssetAmount(traded_amount, 'BTC')
     tx.transferred_assets.second += AssetAmount(traded_amount, 'MB')
     tx_done_block = MarketBlock()
     tx_done_block.type = 'tx_done'
     tx_done_block.transaction = {
         'ask': ask.to_status_dictionary(),
         'bid': bid.to_status_dictionary(),
         'tx': tx.to_dictionary(),
         'version': MarketCommunity.PROTOCOL_VERSION
     }
     tx_done_block.transaction['ask']['address'], tx_done_block.transaction['ask']['port'] = "1.1.1.1", 1234
     tx_done_block.transaction['bid']['address'], tx_done_block.transaction['bid']['port'] = "1.1.1.1", 1234
     return tx_done_block
Esempio n. 28
0
    def create_from_proposed_trade(self, proposed_trade, match_id):
        """
        :type proposed_trade: ProposedTrade
        :type match_id: str
        :rtype: Transaction
        """
        assert isinstance(proposed_trade, ProposedTrade), type(proposed_trade)

        transaction = Transaction.from_proposed_trade(
            proposed_trade, self.transaction_repository.next_identity())
        transaction.match_id = match_id
        self.transaction_repository.add(transaction)

        self._logger.info(
            "Transaction created with id: %s, quantity: %s, price: %s",
            str(transaction.transaction_id), str(transaction.total_quantity),
            str(transaction.price))
        return transaction
Esempio n. 29
0
    def setUp(self):
        # Object creation
        self.memory_transaction_repository = MemoryTransactionRepository("0")
        self.transaction_manager = TransactionManager(self.memory_transaction_repository)

        self.transaction_id = TransactionId(TraderId(b"0"), TransactionNumber(1))
        self.transaction = Transaction(self.transaction_id, AssetPair(AssetAmount(100, 'BTC'), AssetAmount(30, 'MB')),
                                       OrderId(TraderId(b'3'), OrderNumber(2)),
                                       OrderId(TraderId(b'2'), OrderNumber(1)), Timestamp(0.0))
        self.proposed_trade = Trade.propose(TraderId(b'0'),
                                            OrderId(TraderId(b'0'), OrderNumber(1)),
                                            OrderId(TraderId(b'1'), OrderNumber(2)),
                                            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
                                            Timestamp(1462224447.117))
        self.start_transaction = StartTransaction(TraderId(b'0'),
                                                  TransactionId(TraderId(b"0"), TransactionNumber(1)),
                                                  OrderId(TraderId(b'0'), OrderNumber(1)),
                                                  OrderId(TraderId(b'1'), OrderNumber(2)), 1235,
                                                  AssetPair(AssetAmount(20, 'BTC'), AssetAmount(20, 'MB')),
                                                  Timestamp(0.0))
    def setUp(self):
        # Object creation
        self.memory_transaction_repository = MemoryTransactionRepository("0")
        self.transaction_manager = TransactionManager(
            self.memory_transaction_repository)

        self.transaction_id = TransactionId(TraderId("0"),
                                            TransactionNumber(1))
        self.transaction = Transaction(self.transaction_id, Price(100, 'BTC'),
                                       Quantity(30, 'MC'),
                                       OrderId(TraderId('3'), OrderNumber(2)),
                                       OrderId(TraderId('2'), OrderNumber(1)),
                                       Timestamp(0.0))
        self.proposed_trade = Trade.propose(
            MessageId(TraderId('0'), MessageNumber('message_number')),
            OrderId(TraderId('0'), OrderNumber(1)),
            OrderId(TraderId('1'), OrderNumber(2)), Price(63400, 'BTC'),
            Quantity(30, 'MC'), Timestamp(1462224447.117))
        self.start_transaction = StartTransaction(
            MessageId(TraderId('0'), MessageNumber('1')),
            TransactionId(TraderId("0"), TransactionNumber(1)),
            OrderId(TraderId('0'), OrderNumber(1)),
            OrderId(TraderId('1'), OrderNumber(2)), 1235, Price(3600, 'BTC'),
            Quantity(20, 'MC'), Timestamp(0.0))
Esempio n. 31
0
class TestMarketBlock(AbstractServer):
    """
    This class contains tests for a TrustChain block as used in the market.
    """
    @inlineCallbacks
    def setUp(self):
        yield super(TestMarketBlock, self).setUp()

        self.ask = Ask(
            OrderId(TraderId('0' * 40), OrderNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            Timeout(30), Timestamp(0.0), True)
        self.bid = Ask(
            OrderId(TraderId('1' * 40), OrderNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            Timeout(30), Timestamp(0.0), False)
        self.transaction = Transaction(
            TransactionId(TraderId('0' * 40), TransactionNumber(1)),
            AssetPair(AssetAmount(30, 'BTC'), AssetAmount(30, 'MB')),
            OrderId(TraderId('0' * 40), OrderNumber(1)),
            OrderId(TraderId('1' * 40), OrderNumber(1)), Timestamp(0.0))

        ask_tx = self.ask.to_block_dict()
        bid_tx = self.bid.to_block_dict()

        self.tick_block = MarketBlock()
        self.tick_block.type = 'ask'
        self.tick_block.transaction = {'tick': ask_tx}

        self.cancel_block = MarketBlock()
        self.cancel_block.type = 'cancel_order'
        self.cancel_block.transaction = {
            'trader_id': 'a' * 40,
            'order_number': 1
        }

        self.tx_block = MarketBlock()
        self.tx_block.type = 'tx_init'
        self.tx_block.transaction = {
            'ask': ask_tx,
            'bid': bid_tx,
            'tx': self.transaction.to_dictionary()
        }

        payment = {
            'trader_id': 'a' * 40,
            'transaction_number': 3,
            'transferred': {
                'amount': 3,
                'type': 'BTC'
            },
            'payment_id': 'a',
            'address_from': 'a',
            'address_to': 'b',
            'timestamp': 1234.3,
            'success': True
        }
        self.payment_block = MarketBlock()
        self.payment_block.type = 'tx_payment'
        self.payment_block.transaction = {'payment': payment}

    def test_tick_block(self):
        """
        Test whether a tick block can be correctly verified
        """
        self.assertTrue(self.tick_block.is_valid_tick_block())

        self.tick_block.type = 'test'
        self.assertFalse(self.tick_block.is_valid_tick_block())

        self.tick_block.type = 'ask'
        self.tick_block.transaction['test'] = self.tick_block.transaction.pop(
            'tick')
        self.assertFalse(self.tick_block.is_valid_tick_block())

        self.tick_block.transaction['tick'] = self.tick_block.transaction.pop(
            'test')
        self.tick_block.transaction['tick'].pop('timeout')
        self.assertFalse(self.tick_block.is_valid_tick_block())

        self.tick_block.transaction['tick']['timeout'] = "300"
        self.assertFalse(self.tick_block.is_valid_tick_block())

        self.tick_block.transaction['tick']['timeout'] = 300
        self.tick_block.transaction['tick']['trader_id'] = 'g' * 40
        self.assertFalse(self.tick_block.is_valid_tick_block())

        # Make the asset pair invalid
        assets = self.tick_block.transaction['tick']['assets']
        self.tick_block.transaction['tick']['trader_id'] = 'a' * 40
        assets['test'] = assets.pop('first')
        self.assertFalse(self.tick_block.is_valid_tick_block())

        assets['first'] = assets.pop('test')
        assets['first']['test'] = assets['first'].pop('amount')
        self.assertFalse(self.tick_block.is_valid_tick_block())

        assets['first']['amount'] = assets['first']['test']
        assets['second']['test'] = assets['second'].pop('amount')
        self.assertFalse(self.tick_block.is_valid_tick_block())

        assets['second']['amount'] = assets['second']['test']
        assets['first']['amount'] = 3.4
        self.assertFalse(self.tick_block.is_valid_tick_block())

        assets['first']['amount'] = 3
        assets['second']['type'] = 4
        self.assertFalse(self.tick_block.is_valid_tick_block())

    def test_cancel_block(self):
        """
        Test whether a cancel block can be correctly verified
        """
        self.assertTrue(self.cancel_block.is_valid_cancel_block())

        self.cancel_block.type = 'cancel'
        self.assertFalse(self.cancel_block.is_valid_cancel_block())

        self.cancel_block.type = 'cancel_order'
        self.cancel_block.transaction.pop('trader_id')
        self.assertFalse(self.cancel_block.is_valid_cancel_block())

        self.cancel_block.transaction['trader_id'] = 3
        self.assertFalse(self.cancel_block.is_valid_cancel_block())

    def test_tx_init_done_block(self):
        """
        Test whether a tx_init/tx_done block can be correctly verified
        """
        self.assertTrue(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.type = 'test'
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.type = 'tx_init'
        self.tx_block.transaction['test'] = self.tx_block.transaction.pop(
            'ask')
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['ask'] = self.tx_block.transaction.pop(
            'test')
        self.tx_block.transaction['ask']['timeout'] = 3.44
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['ask']['timeout'] = 3
        self.tx_block.transaction['bid']['timeout'] = 3.44
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['bid']['timeout'] = 3
        self.tx_block.transaction['tx'].pop('trader_id')
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['tx']['trader_id'] = 'a' * 40
        self.tx_block.transaction['tx']['test'] = 3
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['tx'].pop('test')
        self.tx_block.transaction['tx']['trader_id'] = 'a'
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['tx']['trader_id'] = 'a' * 40
        self.tx_block.transaction['tx']['assets']['first']['amount'] = 3.4
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['tx']['assets']['first']['amount'] = 3
        self.tx_block.transaction['tx']['transferred']['first']['amount'] = 3.4
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

        self.tx_block.transaction['tx']['transferred']['first']['amount'] = 3
        self.tx_block.transaction['tx']['transaction_number'] = 3.4
        self.assertFalse(self.tx_block.is_valid_tx_init_done_block())

    def test_tx_payment_block(self):
        """
        Test whether a tx_payment block can be correctly verified
        """
        self.assertTrue(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.type = 'test'
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.type = 'tx_payment'
        self.payment_block.transaction[
            'test'] = self.payment_block.transaction.pop('payment')
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.transaction[
            'payment'] = self.payment_block.transaction.pop('test')
        self.payment_block.transaction['payment'].pop('address_to')
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.transaction['payment']['address_to'] = 'a'
        self.payment_block.transaction['payment']['test'] = 'a'
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.transaction['payment'].pop('test')
        self.payment_block.transaction['payment']['address_to'] = 3
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

        self.payment_block.transaction['payment']['address_to'] = 'a'
        self.payment_block.transaction['payment']['trader_id'] = 'a' * 39
        self.assertFalse(self.payment_block.is_valid_tx_payment_block())

    def test_is_valid_asset_pair(self):
        """
        Test the method to verify whether an asset pair is valid
        """
        self.assertFalse(MarketBlock.is_valid_asset_pair({'a': 'b'}))
        self.assertFalse(
            MarketBlock.is_valid_asset_pair({
                'first': {
                    'amount': 3,
                    'type': 'DUM1'
                },
                'second': {
                    'amount': 3
                }
            }))
        self.assertFalse(
            MarketBlock.is_valid_asset_pair({
                'first': {
                    'type': 'DUM1'
                },
                'second': {
                    'amount': 3,
                    'type': 'DUM2'
                }
            }))
        self.assertFalse(
            MarketBlock.is_valid_asset_pair({
                'first': {
                    'amount': "4",
                    'type': 'DUM1'
                },
                'second': {
                    'amount': 3,
                    'type': 'DUM2'
                }
            }))
        self.assertFalse(
            MarketBlock.is_valid_asset_pair({
                'first': {
                    'amount': 4,
                    'type': 'DUM1'
                },
                'second': {
                    'amount': "3",
                    'type': 'DUM2'
                }
            }))
        self.assertFalse(
            MarketBlock.is_valid_asset_pair({
                'first': {
                    'amount': -4,
                    'type': 'DUM1'
                },
                'second': {
                    'amount': 3,
                    'type': 'DUM2'
                }
            }))
Esempio n. 32
0
class TestDatabase(AbstractServer):

    @inlineCallbacks
    def setUp(self):
        yield super(TestDatabase, self).setUp()

        path = os.path.join(self.getStateDir(), 'sqlite')
        if not os.path.exists(path):
            os.makedirs(path)

        self.database = MarketDB(self.getStateDir(), 'market')

        self.order_id1 = OrderId(TraderId(b'3'), OrderNumber(4))
        self.order_id2 = OrderId(TraderId(b'4'), OrderNumber(5))
        self.order1 = Order(self.order_id1, AssetPair(AssetAmount(5, 'BTC'), AssetAmount(6, 'EUR')),
                            Timeout(3600), Timestamp.now(), True)
        self.order2 = Order(self.order_id2, AssetPair(AssetAmount(5, 'BTC'), AssetAmount(6, 'EUR')),
                            Timeout(3600), Timestamp.now(), False)
        self.order2.reserve_quantity_for_tick(OrderId(TraderId(b'3'), OrderNumber(4)), 3)

        self.transaction_id1 = TransactionId(TraderId(b"0"), TransactionNumber(4))
        self.transaction1 = Transaction(self.transaction_id1, AssetPair(AssetAmount(100, 'BTC'), AssetAmount(30, 'MB')),
                                        OrderId(TraderId(b"0"), OrderNumber(1)),
                                        OrderId(TraderId(b"1"), OrderNumber(2)), Timestamp(20.0))

        self.payment1 = Payment(TraderId(b"0"), self.transaction_id1, AssetAmount(5, 'BTC'),
                                WalletAddress('abc'), WalletAddress('def'), PaymentId("abc"), Timestamp(20.0), False)

        self.transaction1.add_payment(self.payment1)

    def test_add_get_order(self):
        """
        Test the insertion and retrieval of an order in the database
        """
        self.database.add_order(self.order1)
        self.database.add_order(self.order2)
        orders = self.database.get_all_orders()
        self.assertEqual(len(orders), 2)

    def test_get_specific_order(self):
        """
        Test the retrieval of a specific order
        """
        order_id = OrderId(TraderId(b'3'), OrderNumber(4))
        self.assertIsNone(self.database.get_order(order_id))
        self.database.add_order(self.order1)
        self.assertIsNotNone(self.database.get_order(order_id))

    def test_delete_order(self):
        """
        Test the deletion of an order from the database
        """
        self.database.add_order(self.order1)
        self.assertEqual(len(self.database.get_all_orders()), 1)
        self.database.delete_order(self.order_id1)
        self.assertEqual(len(self.database.get_all_orders()), 0)

    def test_get_next_order_number(self):
        """
        Test the retrieval of the next order number from the database
        """
        self.assertEqual(self.database.get_next_order_number(), 1)
        self.database.add_order(self.order1)
        self.assertEqual(self.database.get_next_order_number(), 5)

    def test_add_delete_reserved_ticks(self):
        """
        Test the retrieval, addition and deletion of reserved ticks in the database
        """
        self.database.add_reserved_tick(self.order_id1, self.order_id2, self.order1.total_quantity)
        self.assertEqual(len(self.database.get_reserved_ticks(self.order_id1)), 1)
        self.database.delete_reserved_ticks(self.order_id1)
        self.assertEqual(len(self.database.get_reserved_ticks(self.order_id1)), 0)

    def test_add_get_transaction(self):
        """
        Test the insertion and retrieval of a transaction in the database
        """
        self.database.add_transaction(self.transaction1)
        transactions = self.database.get_all_transactions()
        self.assertEqual(len(transactions), 1)
        self.assertEqual(len(self.database.get_payments(self.transaction1.transaction_id)), 1)

    def test_insert_or_update_transaction(self):
        """
        Test the conditional insertion or update of a transaction in the database
        """
        # Test insertion
        self.database.insert_or_update_transaction(self.transaction1)
        transactions = self.database.get_all_transactions()
        self.assertEqual(len(transactions), 1)

        # Test try to update with older timestamp
        before_trans1 = Transaction(self.transaction1.transaction_id, self.transaction1.assets,
                                    self.transaction1.order_id, self.transaction1.partner_order_id,
                                    Timestamp(float(self.transaction1.timestamp) - 1.0))
        self.database.insert_or_update_transaction(before_trans1)
        transaction = self.database.get_transaction(self.transaction1.transaction_id)
        self.assertEqual(float(transaction.timestamp), float(self.transaction1.timestamp))

        # Test update with newer timestamp
        after_trans1 = Transaction(self.transaction1.transaction_id, self.transaction1.assets,
                                   self.transaction1.order_id, self.transaction1.partner_order_id,
                                   Timestamp(float(self.transaction1.timestamp) + 1.0))
        self.database.insert_or_update_transaction(after_trans1)
        transaction = self.database.get_transaction(self.transaction1.transaction_id)
        self.assertEqual(float(transaction.timestamp), float(after_trans1.timestamp))

    def test_get_specific_transaction(self):
        """
        Test the retrieval of a specific transaction
        """
        transaction_id = TransactionId(TraderId(b'0'), TransactionNumber(4))
        self.assertIsNone(self.database.get_transaction(transaction_id))
        self.database.add_transaction(self.transaction1)
        self.assertIsNotNone(self.database.get_transaction(transaction_id))

    def test_delete_transaction(self):
        """
        Test the deletion of a transaction from the database
        """
        self.database.add_transaction(self.transaction1)
        self.assertEqual(len(self.database.get_all_transactions()), 1)
        self.database.delete_transaction(self.transaction_id1)
        self.assertEqual(len(self.database.get_all_transactions()), 0)

    def test_get_next_transaction_number(self):
        """
        Test the retrieval of the next transaction number from the database
        """
        self.assertEqual(self.database.get_next_transaction_number(), 1)
        self.database.add_transaction(self.transaction1)
        self.assertEqual(self.database.get_next_transaction_number(), 5)

    def test_add_get_payment(self):
        """
        Test the insertion and retrieval of a payment in the database
        """
        self.database.add_payment(self.payment1)
        payments = self.database.get_payments(self.transaction_id1)
        self.assertEqual(len(payments), 1)

    def test_add_remove_tick(self):
        """
        Test addition, retrieval and deletion of ticks in the database
        """
        ask = Tick.from_order(self.order1)
        self.database.add_tick(ask)
        bid = Tick.from_order(self.order2)
        self.database.add_tick(bid)

        self.assertEqual(len(self.database.get_ticks()), 2)

        self.database.delete_all_ticks()
        self.assertEqual(len(self.database.get_ticks()), 0)

    def test_add_get_trader_identity(self):
        """
        Test the addition and retrieval of a trader identity in the database
        """
        self.database.add_trader_identity(TraderId(b"a"), "123", 1234)
        self.database.add_trader_identity(TraderId(b"b"), "124", 1235)
        traders = self.database.get_traders()
        self.assertEqual(len(traders), 2)

    def test_check_database(self):
        """
        Test the check of the database
        """
        self.assertEqual(self.database.check_database(six.text_type(LATEST_DB_VERSION)), LATEST_DB_VERSION)

    def test_get_upgrade_script(self):
        """
        Test fetching the upgrade script of the database
        """
        self.assertTrue(self.database.get_upgrade_script(1))

    def test_db_upgrade(self):
        self.database.execute(u"DROP TABLE orders;")
        self.database.execute(u"DROP TABLE ticks;")
        self.database.execute(u"CREATE TABLE orders(x INTEGER PRIMARY KEY ASC);")
        self.database.execute(u"CREATE TABLE ticks(x INTEGER PRIMARY KEY ASC);")
        self.assertEqual(self.database.check_database(u"1"), 3)
Esempio n. 33
0
class TestDatabase(AbstractServer):
    @blocking_call_on_reactor_thread
    @inlineCallbacks
    def setUp(self, annotate=True):
        yield super(TestDatabase, self).setUp(annotate=annotate)

        path = os.path.join(self.getStateDir(), 'sqlite')
        if not os.path.exists(path):
            os.makedirs(path)

        self.database = MarketDB(self.getStateDir())

        self.order_id1 = OrderId(TraderId('3'), OrderNumber(4))
        self.order_id2 = OrderId(TraderId('4'), OrderNumber(5))
        self.order1 = Order(self.order_id1, Price(5,
                                                  'EUR'), Quantity(6, 'BTC'),
                            Timeout(3600), Timestamp.now(), True)
        self.order2 = Order(self.order_id2, Price(5,
                                                  'EUR'), Quantity(6, 'BTC'),
                            Timeout(3600), Timestamp.now(), False)

        self.transaction_id1 = TransactionId(TraderId("0"),
                                             TransactionNumber(4))
        self.transaction1 = Transaction(self.transaction_id1,
                                        Price(100, 'BTC'), Quantity(30, 'MC'),
                                        OrderId(TraderId("0"), OrderNumber(1)),
                                        OrderId(TraderId("1"), OrderNumber(2)),
                                        Timestamp(20.0))

        self.payment1 = Payment(MessageId(TraderId("0"), MessageNumber("4")),
                                self.transaction_id1, Quantity(5, 'MC'),
                                Price(6, 'BTC'), WalletAddress('abc'),
                                WalletAddress('def'), PaymentId("abc"),
                                Timestamp(20.0), False)

        self.transaction1.add_payment(self.payment1)

    @blocking_call_on_reactor_thread
    def test_add_get_order(self):
        """
        Test the insertion and retrieval of an order in the database
        """
        self.database.add_order(self.order1)
        orders = self.database.get_all_orders()
        self.assertEqual(len(orders), 1)

    @blocking_call_on_reactor_thread
    def test_get_specific_order(self):
        """
        Test the retrieval of a specific order
        """
        order_id = OrderId(TraderId('3'), OrderNumber(4))
        self.assertIsNone(self.database.get_order(order_id))
        self.database.add_order(self.order1)
        self.assertIsNotNone(self.database.get_order(order_id))

    @blocking_call_on_reactor_thread
    def test_delete_order(self):
        """
        Test the deletion of an order from the database
        """
        self.database.add_order(self.order1)
        self.assertEqual(len(self.database.get_all_orders()), 1)
        self.database.delete_order(self.order_id1)
        self.assertEqual(len(self.database.get_all_orders()), 0)

    @blocking_call_on_reactor_thread
    def test_get_next_order_number(self):
        """
        Test the retrieval of the next order number from the database
        """
        self.assertEqual(self.database.get_next_order_number(), 1)
        self.database.add_order(self.order1)
        self.assertEqual(self.database.get_next_order_number(), 5)

    @blocking_call_on_reactor_thread
    def test_add_delete_reserved_ticks(self):
        """
        Test the retrieval, addition and deletion of reserved ticks in the database
        """
        self.database.add_reserved_tick(self.order_id1, self.order_id2,
                                        self.order1.total_quantity)
        self.assertEqual(len(self.database.get_reserved_ticks(self.order_id1)),
                         1)
        self.database.delete_reserved_ticks(self.order_id1)
        self.assertEqual(len(self.database.get_reserved_ticks(self.order_id1)),
                         0)

    @blocking_call_on_reactor_thread
    def test_add_get_transaction(self):
        """
        Test the insertion and retrieval of a transaction in the database
        """
        self.database.add_transaction(self.transaction1)
        transactions = self.database.get_all_transactions()
        self.assertEqual(len(transactions), 1)
        self.assertEqual(
            len(self.database.get_payments(self.transaction1.transaction_id)),
            1)

    @blocking_call_on_reactor_thread
    def test_get_specific_transaction(self):
        """
        Test the retrieval of a specific transaction
        """
        transaction_id = TransactionId(TraderId('0'), TransactionNumber(4))
        self.assertIsNone(self.database.get_transaction(transaction_id))
        self.database.add_transaction(self.transaction1)
        self.assertIsNotNone(self.database.get_transaction(transaction_id))

    @blocking_call_on_reactor_thread
    def test_delete_transaction(self):
        """
        Test the deletion of a transaction from the database
        """
        self.database.add_transaction(self.transaction1)
        self.assertEqual(len(self.database.get_all_transactions()), 1)
        self.database.delete_transaction(self.transaction_id1)
        self.assertEqual(len(self.database.get_all_transactions()), 0)

    @blocking_call_on_reactor_thread
    def test_get_next_transaction_number(self):
        """
        Test the retrieval of the next transaction number from the database
        """
        self.assertEqual(self.database.get_next_transaction_number(), 1)
        self.database.add_transaction(self.transaction1)
        self.assertEqual(self.database.get_next_transaction_number(), 5)

    @blocking_call_on_reactor_thread
    def test_add_get_payment(self):
        """
        Test the insertion and retrieval of a payment in the database
        """
        self.database.add_payment(self.payment1)
        payments = self.database.get_payments(self.transaction_id1)
        self.assertEqual(len(payments), 1)

    @blocking_call_on_reactor_thread
    def test_add_remove_tick(self):
        """
        Test addition, retrieval and deletion of ticks in the database
        """
        ask = Tick.from_order(
            self.order1,
            MessageId(TraderId('0'), MessageNumber('message_number')))
        self.database.add_tick(ask)
        bid = Tick.from_order(
            self.order2,
            MessageId(TraderId('0'), MessageNumber('message_number')))
        self.database.add_tick(bid)

        self.assertEqual(len(self.database.get_ticks()), 2)

        self.database.delete_all_ticks()
        self.assertEqual(len(self.database.get_ticks()), 0)

    @blocking_call_on_reactor_thread
    def test_add_get_trader_identity(self):
        """
        Test the addition and retrieval of a trader identity in the database
        """
        self.database.add_trader_identity("a", "123", 1234)
        self.database.add_trader_identity("b", "124", 1235)
        traders = self.database.get_traders()
        self.assertEqual(len(traders), 2)
        self.assertEqual(traders, [("a", "123", 1234), ("b", "124", 1235)])

    @blocking_call_on_reactor_thread
    def test_check_database(self):
        """
        Test the check of the database
        """
        self.assertEqual(
            self.database.check_database(unicode(LATEST_DB_VERSION)),
            LATEST_DB_VERSION)
Esempio n. 34
0
    def test_from_block(self):
        """
        Test the from block method of a transaction
        """
        block = {
            'tx': {
                'payment_complete': False,
                'status': 'pending',
                'partner_trader_id':
                '1111111111111111111111111111111111111111',
                'trader_id': '0000000000000000000000000000000000000000',
                'timestamp': 0.0,
                'transferred': {
                    'second': {
                        'amount': 0,
                        'type': 'MB'
                    },
                    'first': {
                        'amount': 0,
                        'type': 'BTC'
                    }
                },
                'partner_order_number': 1,
                'order_number': 1,
                'transaction_number': 1,
                'assets': {
                    'second': {
                        'amount': 30,
                        'type': 'MB'
                    },
                    'first': {
                        'amount': 30,
                        'type': 'BTC'
                    }
                }
            }
        }

        transaction = Transaction.from_block(block)

        self.assertEqual(block['tx']['trader_id'],
                         six.text_type(transaction.transaction_id.trader_id))
        self.assertEqual(block['tx']['transaction_number'],
                         int(transaction.transaction_id.transaction_number))
        self.assertEqual(block['tx']['trader_id'],
                         six.text_type(transaction.order_id.trader_id))
        self.assertEqual(block['tx']['transaction_number'],
                         int(transaction.order_id.order_number))
        self.assertEqual(block['tx']['partner_trader_id'],
                         six.text_type(transaction.partner_order_id.trader_id))
        self.assertEqual(block['tx']['partner_order_number'],
                         int(transaction.partner_order_id.order_number))
        self.assertEqual(block['tx']['timestamp'],
                         float(transaction.timestamp))
        self.assertEqual(block['tx']['assets']['first']['amount'],
                         transaction.assets.first.amount)
        self.assertEqual(block['tx']['assets']['first']['type'],
                         transaction.assets.first.asset_id)
        self.assertEqual(block['tx']['assets']['second']['amount'],
                         transaction.assets.second.amount)
        self.assertEqual(block['tx']['assets']['second']['type'],
                         transaction.assets.second.asset_id)
        self.assertEqual(block['tx']['transferred']['first']['amount'],
                         transaction.transferred_assets.first.amount)
        self.assertEqual(block['tx']['transferred']['first']['type'],
                         transaction.transferred_assets.first.asset_id)
        self.assertEqual(block['tx']['transferred']['second']['amount'],
                         transaction.transferred_assets.second.amount)
        self.assertEqual(block['tx']['transferred']['second']['type'],
                         transaction.transferred_assets.second.asset_id)
Esempio n. 35
0
 def test_from_proposed_trade(self):
     """
     Test creating a transaction from a proposed trade
     """
     transaction = Transaction.from_proposed_trade(self.proposed_trade, self.transaction_id)
     self.assertEqual(transaction.assets, self.transaction.assets)
Esempio n. 36
0
class TransactionTestSuite(unittest.TestCase):
    """Transaction test cases."""

    def setUp(self):
        # Object creation
        self.transaction_id = TransactionId(TraderId("0"), TransactionNumber(1))
        self.transaction = Transaction(self.transaction_id, AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
                                       OrderId(TraderId('3'), OrderNumber(2)),
                                       OrderId(TraderId('2'), OrderNumber(1)), Timestamp(0.0))
        self.proposed_trade = Trade.propose(TraderId('0'),
                                            OrderId(TraderId('0'), OrderNumber(2)),
                                            OrderId(TraderId('1'), OrderNumber(3)),
                                            AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')), Timestamp(0.0))
        self.payment = Payment(TraderId("0"), TransactionId(TraderId('2'), TransactionNumber(2)),
                               AssetAmount(3, 'MB'), WalletAddress('a'), WalletAddress('b'),
                               PaymentId('aaa'), Timestamp(4.0), True)

    def test_from_proposed_trade(self):
        """
        Test creating a transaction from a proposed trade
        """
        transaction = Transaction.from_proposed_trade(self.proposed_trade, self.transaction_id)
        self.assertEqual(transaction.assets, self.transaction.assets)

    def test_add_payment(self):
        """
        Test the addition of a payment to a transaction
        """
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.transferred_assets.first.amount, 0)
        self.assertEqual(self.transaction.transferred_assets.second.amount, 3)
        self.assertTrue(self.transaction.payments)

    def test_next_payment(self):
        """
        Test the process of determining the next payment details during a transaction
        """
        self.assertEqual(self.transaction.next_payment(True), AssetAmount(100, 'BTC'))
        self.assertEqual(self.transaction.next_payment(False), AssetAmount(100, 'MB'))

    def test_is_payment_complete(self):
        """
        Test whether a payment is correctly marked as complete
        """
        self.assertFalse(self.transaction.is_payment_complete())
        self.transaction.add_payment(self.payment)
        self.assertFalse(self.transaction.is_payment_complete())
        self.transaction._transferred_assets = AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB'))
        self.assertTrue(self.transaction.is_payment_complete())

    def test_to_dictionary(self):
        """
        Test the to dictionary method of a transaction
        """
        self.assertDictEqual(self.transaction.to_dictionary(), {
            'trader_id': '0',
            'transaction_number': 1,
            'order_number': 2,
            'partner_trader_id': '2',
            'partner_order_number': 1,
            'payment_complete': False,
            'assets': {
                'first': {
                    'amount': 100,
                    'type': 'BTC',
                },
                'second': {
                    'amount': 100,
                    'type': 'MB'
                }
            },
            'transferred': {
                'first': {
                    'amount': 0,
                    'type': 'BTC',
                },
                'second': {
                    'amount': 0,
                    'type': 'MB'
                }
            },
            'timestamp': 0.0,
            'status': 'pending'
        })

    def test_status(self):
        """
        Test the status of a transaction
        """
        self.assertEqual(self.transaction.status, 'pending')

        self.payment._success = False
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.status, 'error')
Esempio n. 37
0
class TransactionTestSuite(unittest.TestCase):
    """Transaction test cases."""
    def setUp(self):
        # Object creation
        self.transaction_id = TransactionId(TraderId("0"),
                                            TransactionNumber(1))
        self.transaction = Transaction(
            self.transaction_id,
            AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
            OrderId(TraderId('3'), OrderNumber(2)),
            OrderId(TraderId('2'), OrderNumber(1)), Timestamp(0.0))
        self.proposed_trade = Trade.propose(
            TraderId('0'), OrderId(TraderId('0'), OrderNumber(2)),
            OrderId(TraderId('1'), OrderNumber(3)),
            AssetPair(AssetAmount(100, 'BTC'), AssetAmount(100, 'MB')),
            Timestamp(0.0))
        self.payment = Payment(
            TraderId("0"), TransactionId(TraderId('2'), TransactionNumber(2)),
            AssetAmount(3, 'MB'), WalletAddress('a'), WalletAddress('b'),
            PaymentId('aaa'), Timestamp(4.0), True)

    def test_from_proposed_trade(self):
        """
        Test creating a transaction from a proposed trade
        """
        transaction = Transaction.from_proposed_trade(self.proposed_trade,
                                                      self.transaction_id)
        self.assertEqual(transaction.assets, self.transaction.assets)

    def test_add_payment(self):
        """
        Test the addition of a payment to a transaction
        """
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.transferred_assets.first.amount, 0)
        self.assertEqual(self.transaction.transferred_assets.second.amount, 3)
        self.assertTrue(self.transaction.payments)

    def test_next_payment(self):
        """
        Test the process of determining the next payment details during a transaction
        """
        self.assertEqual(self.transaction.next_payment(True),
                         AssetAmount(100, 'BTC'))
        self.assertEqual(self.transaction.next_payment(False),
                         AssetAmount(100, 'MB'))

    def test_is_payment_complete(self):
        """
        Test whether a payment is correctly marked as complete
        """
        self.assertFalse(self.transaction.is_payment_complete())
        self.transaction.add_payment(self.payment)
        self.assertFalse(self.transaction.is_payment_complete())
        self.transaction._transferred_assets = AssetPair(
            AssetAmount(100, 'BTC'), AssetAmount(100, 'MB'))
        self.assertTrue(self.transaction.is_payment_complete())

    def test_to_dictionary(self):
        """
        Test the to dictionary method of a transaction
        """
        self.assertDictEqual(
            self.transaction.to_dictionary(), {
                'trader_id': '0',
                'transaction_number': 1,
                'order_number': 2,
                'partner_trader_id': '2',
                'partner_order_number': 1,
                'payment_complete': False,
                'assets': {
                    'first': {
                        'amount': 100,
                        'type': 'BTC',
                    },
                    'second': {
                        'amount': 100,
                        'type': 'MB'
                    }
                },
                'transferred': {
                    'first': {
                        'amount': 0,
                        'type': 'BTC',
                    },
                    'second': {
                        'amount': 0,
                        'type': 'MB'
                    }
                },
                'timestamp': 0.0,
                'status': 'pending'
            })

    def test_status(self):
        """
        Test the status of a transaction
        """
        self.assertEqual(self.transaction.status, 'pending')

        self.payment._success = False
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.status, 'error')
Esempio n. 38
0
class TransactionTestSuite(unittest.TestCase):
    """Transaction test cases."""
    def setUp(self):
        # Object creation
        self.transaction_id = TransactionId(TraderId("0"),
                                            TransactionNumber(1))
        self.transaction = Transaction(self.transaction_id, Price(100, 'BTC'),
                                       Quantity(30, 'MC'),
                                       OrderId(TraderId('3'), OrderNumber(2)),
                                       OrderId(TraderId('2'), OrderNumber(1)),
                                       Timestamp(0.0))
        self.proposed_trade = Trade.propose(
            MessageId(TraderId('0'), MessageNumber('1')),
            OrderId(TraderId('0'), OrderNumber(2)),
            OrderId(TraderId('1'), OrderNumber(3)), Price(100, 'BTC'),
            Quantity(30, 'MC'), Timestamp(0.0))
        self.payment = Payment(
            MessageId(TraderId("0"), MessageNumber("1")),
            TransactionId(TraderId('2'), TransactionNumber(2)),
            Quantity(3, 'MC'), Price(2, 'BTC'), WalletAddress('a'),
            WalletAddress('b'), PaymentId('aaa'), Timestamp(4.0), True)

    def test_from_proposed_trade(self):
        # Test from proposed trade
        transaction = Transaction.from_proposed_trade(self.proposed_trade,
                                                      self.transaction_id)
        self.assertEqual(transaction.price, self.transaction.price)
        self.assertEqual(transaction.total_quantity,
                         self.transaction.total_quantity)
        self.assertEqual(transaction.timestamp, self.transaction.timestamp)

    def test_unitize(self):
        """
        Test the unitize method of a Transaction
        """
        self.assertEqual(Transaction.unitize(1, 1), 1)
        self.assertEqual(Transaction.unitize(0.03, 0.02), 0.04)
        self.assertEqual(Transaction.unitize(50, 0.05), 50)
        self.assertEqual(Transaction.unitize(50.1818, 25), 75)

    def test_add_payment(self):
        """
        Test the addition of a payment to a transaction
        """
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.transferred_price, Price(2, 'BTC'))
        self.assertEqual(self.transaction.transferred_quantity,
                         Quantity(3, 'MC'))
        self.assertTrue(self.transaction.payments)

    def test_last_payment(self):
        """
        Test the retrieval of the last payment
        """
        self.assertIsNone(self.transaction.last_payment(True))
        self.assertIsNone(self.transaction.last_payment(False))

        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.last_payment(True), self.payment)
        self.assertEqual(self.transaction.last_payment(False), self.payment)

    def test_next_payment(self):
        """
        Test the process of determining the next payment details during a transaction
        """
        def set_transaction_data(trans_price, trans_quantity, payment_price,
                                 payment_quantity):
            self.transaction._transferred_price = trans_price
            self.transaction._transferred_quantity = trans_quantity
            self.payment._transferee_price = payment_price
            self.payment._transferee_quantity = payment_quantity
            self.transaction._payments = [self.payment]

        # No incremental payments
        self.assertEqual(
            self.transaction.next_payment(True, 1, incremental=False),
            Quantity(30, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(False, 2, incremental=False),
            Price(3000, 'BTC'))

        self.assertEqual(
            self.transaction.next_payment(True, 1, incremental=True),
            Quantity(1, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(False, 2, incremental=True),
            Price(2, 'BTC'))

        set_transaction_data(Price(1, 'BTC'), Quantity(1, 'MC'),
                             Price(1, 'BTC'), Quantity(1, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(True, 0.1, incremental=True),
            Quantity(0.2, 'MC'))

        # Test completion of trade
        set_transaction_data(Price(3000, 'BTC'), Quantity(29, 'MC'),
                             Price(1, 'BTC'), Quantity(1, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(True, 1, incremental=True),
            Quantity(1, 'MC'))
        set_transaction_data(Price(2900, 'BTC'), Quantity(30, 'MC'),
                             Price(1, 'BTC'), Quantity(1, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(False, 1, incremental=True),
            Price(100, 'BTC'))

        # Test whether we don't transfer too much
        set_transaction_data(Price(2999, 'BTC'), Quantity(29, 'MC'),
                             Price(2999, 'BTC'), Quantity(1, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(True, 1, incremental=True),
            Quantity(1, 'MC'))
        set_transaction_data(Price(2999, 'BTC'), Quantity(29, 'MC'),
                             Price(1, 'BTC'), Quantity(29, 'MC'))
        self.assertEqual(
            self.transaction.next_payment(False, 1, incremental=True),
            Price(1, 'BTC'))

    def test_to_dictionary(self):
        """
        Test the to dictionary method of a transaction
        """
        self.assertDictEqual(
            self.transaction.to_dictionary(), {
                'trader_id': '0',
                'transaction_number': 1,
                'order_number': 2,
                'partner_trader_id': '2',
                'partner_order_number': 1,
                'payment_complete': False,
                'price': 100.0,
                'price_type': 'BTC',
                'quantity': 30.0,
                'quantity_type': 'MC',
                'transferred_price': 0.0,
                'transferred_quantity': 0.0,
                'timestamp': 0.0,
                'status': 'pending'
            })

    def test_status(self):
        """
        Test the status of a transaction
        """
        self.assertEqual(self.transaction.status, 'pending')

        self.payment._success = False
        self.transaction.add_payment(self.payment)
        self.assertEqual(self.transaction.status, 'error')