def test_market_trading_volume(self): # create markets market = MarketFactory() market_response_data = self.client.get(reverse('api:markets'), content_type='application/json') self.assertEqual(market_response_data.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(market_response_data.content).get('results')), 1) self.assertEqual( json.loads( market_response_data.content)['results'][0]['tradingVolume'], "0") market.trading_volume = 12 market.save() market_response_data2 = self.client.get( reverse('api:markets'), content_type='application/json') self.assertEqual(market_response_data2.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(market_response_data2.content).get('results')), 1) self.assertEqual( json.loads( market_response_data2.content)['results'][0]['tradingVolume'], "12")
def test_market_receiver(self): oracle = CentralizedOracleFactory() oracle.event_description.outcomes = ['1', '2', '3'] oracle.event_description.save() event = CategoricalEventFactory(oracle=oracle) market = MarketFactory() event_address = event.address block = { 'number': market.creation_block, 'timestamp': self.to_timestamp(market.creation_date_time) } market_dict = { 'name': 'StandardMarketCreation', 'address': market.factory, 'params': [ { 'name': 'creator', 'value': market.creator }, { 'name': 'centralizedOracle', 'value': oracle.address, }, { 'name': 'marketMaker', 'value': market.market_maker }, { 'name': 'fee', 'value': market.fee }, { 'name': 'eventContract', 'value': event_address }, { 'name': 'fee', 'value': market.fee }, { 'name': 'market', 'value': market.address } ] } market.delete() MarketFactoryReceiver().save(market_dict, block) with self.assertRaises(Market.DoesNotExist): Market.objects.get(event=event_address) market_dict.get('params')[2].update({'value': settings.LMSR_MARKET_MAKER}) MarketFactoryReceiver().save(market_dict, block) saved_market = Market.objects.get(event=event_address) self.assertIsNotNone(saved_market.pk) self.assertEqual(len(market.net_outcome_tokens_sold), 2) self.assertEqual(len(saved_market.net_outcome_tokens_sold), 3)
def test_market_address_getter(self): getter = MarketAddressGetter() self.assertListEqual([], getter.get_addresses()) market = MarketFactory.create() self.assertIsNotNone(market) self.assertTrue(getter.__contains__(market.address)) self.assertListEqual([market.address], getter.get_addresses()) market2 = MarketFactory.create() self.assertListEqual([market.address, market2.address], getter.get_addresses())
def test_decimal_field_frontier_value(self): market = MarketFactory() market.funding = 2**256 market.save() market_response_data = self.client.get(reverse('api:markets'), content_type='application/json') self.assertEqual(market_response_data.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(market_response_data.content).get('results')), 1) self.assertEqual( str(market.funding), json.loads(market_response_data.content)['results'][0]['funding'])
def test_markets_by_resolution_date(self): # test empty events response empty_markets_response = self.client.get( reverse('api:markets'), content_type='application/json') self.assertEqual( len(json.loads(empty_markets_response.content).get('results')), 0) oracle = CentralizedOracleFactory() event = CategoricalEventFactory(oracle=oracle) market = MarketFactory(event=event) from_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') url = reverse('api:markets') + '?resolution_date_time_0=' + from_date correct_date_time_range_response = self.client.get( url, content_type='application/json') self.assertEqual( len( json.loads( correct_date_time_range_response.content).get('results')), 1) url = reverse( 'api:markets' ) + '?resolution_date_time_0=' + from_date + '&resolution_date_time_1=' + from_date empty_date_time_range_response = self.client.get( url, content_type='application/json') self.assertEqual( len( json.loads( empty_date_time_range_response.content).get('results')), 0)
def test_market_participant_history(self): outcome_token = OutcomeTokenFactory() event = outcome_token.event oracle = event.oracle market = MarketFactory(event=event) creation_date_time = datetime.now() sender_address = '{:040d}'.format(100) response = self.client.get(reverse('api:trades-by-owner', kwargs={ 'market_address': market.address, 'owner_address': sender_address }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json.loads(response.content).get('results')), 0) # Buy Order BuyOrderFactory(market=market, sender=sender_address) BuyOrderFactory(market=market, sender=sender_address) response = self.client.get(reverse('api:trades-by-owner', kwargs={ 'market_address': market.address, 'owner_address': sender_address }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json.loads(response.content).get('results')), 2)
def test_outcome_token_purchase_marginal_price(self): categorical_event = CategoricalEventFactory() OutcomeTokenFactory(event=categorical_event, index=0) OutcomeTokenFactory(event=categorical_event, index=1) market = MarketFactory(event=categorical_event, funding=1e18, net_outcome_tokens_sold=[0, 0]) sender_address = '{:040d}'.format(100) outcome_token_purchase_event = { 'name': 'OutcomeTokenPurchase', 'address': market.address, 'params': [ {'name': 'outcomeTokenCost', 'value': 1000000000000000000}, {'name': 'marketFees', 'value': 0}, {'name': 'buyer', 'value': sender_address}, {'name': 'outcomeTokenIndex', 'value': 0}, {'name': 'outcomeTokenCount', 'value': 1584900000000000000}, ] } block = { 'number': 1, 'timestamp': self.to_timestamp(datetime.now()) } self.assertEqual(BuyOrder.objects.all().count(), 0) MarketInstanceReceiver().save(outcome_token_purchase_event, block) buy_orders = BuyOrder.objects.all() self.assertEqual(buy_orders.count(), 1) self.assertListEqual(buy_orders[0].marginal_prices, [Decimal(0.7500), Decimal(0.2500)]) # outcomeTokenCost+fee
def test_shares_by_owner(self): market = MarketFactory() response = self.client.get(reverse('api:shares-by-owner', kwargs={ 'market_address': market.address, 'owner_address': market.creator }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json.loads(response.content).get('results')), 0) outcome_token = OutcomeTokenFactory(event=market.event) outcome_token2 = OutcomeTokenFactory(event=market.event) OutcomeTokenBalanceFactory(owner=market.creator, outcome_token=outcome_token) response = self.client.get(reverse('api:shares-by-owner', kwargs={ 'market_address': market.address, 'owner_address': market.creator }), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(json.loads(response.content).get('results')), 1)
def test_markets_with_event_description(self): # test empty events response empty_markets_response = self.client.get( reverse('api:markets'), content_type='application/json') self.assertEqual( len(json.loads(empty_markets_response.content).get('results')), 0) # create markets oracle = CentralizedOracleFactory() event = CategoricalEventFactory(oracle=oracle) market = MarketFactory(event=event) market_response_data = self.client.get(reverse('api:markets'), content_type='application/json') self.assertEqual(market_response_data.status_code, status.HTTP_200_OK) results = json.loads(market_response_data.content).get('results') self.assertEqual(len(results), 1) self.assertIsNotNone( results[0]['event']['oracle'].get('eventDescription')) self.assertIsNotNone( results[0]['event']['oracle']['eventDescription'].get('ipfsHash')) self.assertEqual( results[0]['event']['oracle']['eventDescription']['ipfsHash'], oracle.event_description.ipfs_hash)
def test_outcome_token_sell(self): categorical_event = CategoricalEventFactory() outcome_token = OutcomeTokenFactory(event=categorical_event, index=0) market = MarketFactory(event=categorical_event) sender_address = '{:040d}'.format(100) outcome_token_sell_event = { 'name': 'OutcomeTokenSale', 'address': market.address, 'params': [ {'name': 'outcomeTokenProfit', 'value': 100}, {'name': 'marketFees', 'value': 10}, {'name': 'seller', 'value': sender_address}, {'name': 'outcomeTokenIndex', 'value': 0}, {'name': 'outcomeTokenCount', 'value': 10}, ] } block = { 'number': 1, 'timestamp': self.to_timestamp(datetime.now()) } self.assertEqual(SellOrder.objects.all().count(), 0) MarketInstanceReceiver().save(outcome_token_sell_event, block) sell_orders = SellOrder.objects.all() self.assertEqual(sell_orders.count(), 1) self.assertEqual(sell_orders[0].profit, 90) # outcomeTokenProfit-fee
def test_collected_fees(self): categorical_event = CategoricalEventFactory() outcome_token = OutcomeTokenFactory(event=categorical_event, index=0) market = MarketFactory(event=categorical_event) sender_address = '{:040d}'.format(100) fees = 10 outcome_token_purchase_event = { 'name': 'OutcomeTokenPurchase', 'address': market.address, 'params': [ {'name': 'outcomeTokenCost', 'value': 100}, {'name': 'marketFees', 'value': fees}, {'name': 'buyer', 'value': sender_address}, {'name': 'outcomeTokenIndex', 'value': 0}, {'name': 'outcomeTokenCount', 'value': 10}, ] } block = { 'number': 1, 'timestamp': self.to_timestamp(datetime.now()) } # Save event MarketInstanceReceiver().save(outcome_token_purchase_event, block) # Check that collected fees was incremented market_check = Market.objects.get(address=market.address) self.assertEqual(market_check.collected_fees, market.collected_fees+fees) block.update({'number': 2}) MarketInstanceReceiver().save(outcome_token_purchase_event, block) market_check = Market.objects.get(address=market.address) self.assertEqual(market_check.collected_fees, market.collected_fees+fees+fees)
def test_market_trades_unknown_market(self): market = MarketFactory() url = reverse('api:trades-by-market', kwargs={'market_address': market.address}) history_data = self.client.get(url, content_type='application/json') self.assertEqual(history_data.status_code, status.HTTP_200_OK) self.assertEqual(len(json.loads(history_data.content).get('results')), 0)
def test_market_outcome_token_purchase_rollback(self): oracle_factory = CentralizedOracleFactory() event_factory = CategoricalEventFactory(oracle=oracle_factory) outcome_token = OutcomeTokenFactory(event=event_factory, index=0) market_without_rollback = MarketFactory(event=event_factory) buyer_address = '{:040d}'.format(100) self.assertIsNotNone(market_without_rollback.pk) block = { 'number': oracle_factory.creation_block, 'timestamp': self.to_timestamp(oracle_factory.creation_date_time) } outcome_token_purchase_event = { 'name': 'OutcomeTokenPurchase', 'address': market_without_rollback.address, 'params': [ { 'name': 'outcomeTokenCost', 'value': 100 }, { 'name': 'marketFees', 'value': 10 }, { 'name': 'buyer', 'value': buyer_address }, { 'name': 'outcomeTokenIndex', 'value': 0 }, { 'name': 'outcomeTokenCount', 'value': 10 }, ] } # Send outcome token purchase event MarketInstanceReceiver().save(outcome_token_purchase_event, block) orders_before_rollback = BuyOrder.objects.filter( creation_block=block.get('number'), sender=buyer_address, market=market_without_rollback) self.assertEqual(len(orders_before_rollback), 1) # Outcome token purchase rollback MarketInstanceReceiver().rollback(outcome_token_purchase_event, block) market_with_rollback = Market.objects.get(event=event_factory.address) orders_after_rollback = BuyOrder.objects.filter( creation_block=block.get('number'), sender=buyer_address, market=market_with_rollback) self.assertEqual(len(orders_after_rollback), 0)
def test_market_factory_rollback(self): oracle = CentralizedOracleFactory() event = CategoricalEventFactory(oracle=oracle) market = MarketFactory() block = { 'number': oracle.creation_block, 'timestamp': self.to_timestamp(oracle.creation_date_time) } market_creation_event = { 'name': 'StandardMarketCreation', 'address': market.factory, 'params': [{ 'name': 'creator', 'value': market.creator }, { 'name': 'centralizedOracle', 'value': oracle.address, }, { 'name': 'marketMaker', 'value': settings.LMSR_MARKET_MAKER }, { 'name': 'fee', 'value': market.fee }, { 'name': 'eventContract', 'value': event.address }, { 'name': 'market', 'value': market.address }] } market.delete() MarketFactoryReceiver().save(market_creation_event, block) market_without_rollback = Market.objects.get(event=event.address) self.assertIsNotNone(market_without_rollback.pk) # Rollback MarketFactoryReceiver().rollback(market_creation_event, block) with self.assertRaises(Market.DoesNotExist): Market.objects.get(event=event.address)
def test_market_closing_receiver(self): market = MarketFactory() closing_event = { 'name': 'MarketClosing', 'address': market.address, 'params': [] } MarketInstanceReceiver().save(closing_event) saved_market = Market.objects.get(address=market.address) self.assertEqual(saved_market.stage, 2)
def test_calc_lmsr_marginal_price(self): # outcomeTokenIndex = 0 # outcomeTokenCount = 1e18 # create markets outcome_token = OutcomeTokenFactory() event = outcome_token.event market = MarketFactory(event=event) net_outcome_tokens_sold = [0, 1] # market.net_outcome_tokens_sold result = calc_lmsr_marginal_price(1, net_outcome_tokens_sold, market.funding) self.assertIsNotNone(result) self.assertTrue(result > 0)
def test_market_marginal_prices(self): oracle = CentralizedOracleFactory() categorical_event = CategoricalEventFactory(oracle=oracle) outcome_token = OutcomeTokenFactory(event=categorical_event) market = MarketFactory(event=categorical_event) sender_address = '{:040d}'.format(100) # Buy Order order_one = BuyOrderFactory(market=market, sender=sender_address) order_two = BuyOrderFactory(market=market, sender=sender_address) market_response = self.client.get(reverse( 'api:markets-by-name', kwargs={'market_address': market.address}), content_type='application/json') market_data = json.loads(market_response.content) self.assertEqual(market_data.get('marginalPrices'), order_two.marginal_prices)
def test_markets(self): # test empty events response empty_markets_response = self.client.get( reverse('api:markets'), content_type='application/json') self.assertEqual( len(json.loads(empty_markets_response.content).get('results')), 0) # create markets markets = [MarketFactory() for x in range(0, 10)] marketsdb = Market.objects.all() self.assertEqual(len(markets), marketsdb.count()) market_response_data = self.client.get(reverse('api:markets'), content_type='application/json') self.assertEqual(market_response_data.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(market_response_data.content).get('results')), len(markets)) market_search_response = self.client.get( reverse('api:markets-by-name', kwargs={'market_address': markets[0].address}), content_type='application/json') self.assertEqual(market_search_response.status_code, status.HTTP_200_OK) self.assertEqual( json.loads( market_search_response.content).get('contract').get('creator'), add_0x_prefix(markets[0].creator)) # test empty response market_empty_search_response = self.client.get( reverse('api:markets-by-name', kwargs={'market_address': "abcdef0"}), content_type='application/json') self.assertEqual(market_empty_search_response.status_code, status.HTTP_404_NOT_FOUND) market_search_response = self.client.get( reverse('api:markets-by-name', kwargs={'market_address': markets[0].address}), content_type='application/json') self.assertEqual(market_search_response.status_code, status.HTTP_200_OK) self.assertEqual( json.loads( market_search_response.content).get('contract').get('address'), add_0x_prefix(markets[0].address))
def test_market_fee_withdrawal_receiver(self): market = MarketFactory() withdraw_event = { 'name': 'FeeWithdrawal', 'address': market.address, 'params': [ { 'name': 'fees', 'value': 10 } ] } MarketInstanceReceiver().save(withdraw_event) saved_market = Market.objects.get(address=market.address) # self.assertEqual(market.stage, 3) self.assertEqual(saved_market.withdrawn_fees, market.withdrawn_fees+10)
def test_market_funding_receiver(self): market = MarketFactory() funding_event = { 'name': 'MarketFunding', 'address': market.address, 'params': [ { 'name': 'funding', 'value': 100 } ] } MarketInstanceReceiver().save(funding_event) saved_market = Market.objects.get(address=market.address) self.assertEqual(saved_market.stage, 1) self.assertEqual(saved_market.funding, 100)
def test_market_outcome_token_sale_rollback(self): categorical_event = CategoricalEventFactory() outcome_token = OutcomeTokenFactory(event=categorical_event, index=0) market = MarketFactory(event=categorical_event) seller_address = '{:040d}'.format(100) block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())} outcome_token_sell_event = { 'name': 'OutcomeTokenSale', 'address': market.address, 'params': [ { 'name': 'outcomeTokenProfit', 'value': 100 }, { 'name': 'marketFees', 'value': 10 }, { 'name': 'seller', 'value': seller_address }, { 'name': 'outcomeTokenIndex', 'value': 0 }, { 'name': 'outcomeTokenCount', 'value': 10 }, ] } MarketInstanceReceiver().save(outcome_token_sell_event, block) orders_before_rollback = SellOrder.objects.filter( creation_block=block.get('number'), sender=seller_address) self.assertEqual(len(orders_before_rollback), 1) # Outcome token sell rollback MarketInstanceReceiver().rollback(outcome_token_sell_event, block) orders_before_rollback = SellOrder.objects.filter( creation_block=block.get('number'), sender=seller_address) self.assertEqual(len(orders_before_rollback), 0)
def test_market_closing_rollback(self): market_factory = MarketFactory() block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())} market_closing_event = { 'name': 'MarketClosing', 'address': market_factory.address, 'params': [] } MarketInstanceReceiver().save(market_closing_event) market_without_rollback = Market.objects.get( address=market_factory.address) self.assertEqual(market_without_rollback.stage, 2) # Rollback MarketInstanceReceiver().rollback(market_closing_event, block) market_with_rollback = Market.objects.get( address=market_factory.address) self.assertEqual(market_with_rollback.stage, 1)
def test_shares_by_account(self): account1 = '{:040d}'.format(13) account2 = '{:040d}'.format(14) url = reverse('api:shares-by-account', kwargs={'account_address': account1}) empty_shares_response = self.client.get( url, content_type='application/json') self.assertEqual( len(json.loads(empty_shares_response.content).get('results')), 0) oracle = CentralizedOracleFactory() event = CategoricalEventFactory(oracle=oracle) market = MarketFactory(event=event, creator=account1) outcome_token = OutcomeTokenFactory(event=market.event) OutcomeTokenBalanceFactory(owner=market.creator, outcome_token=outcome_token) BuyOrderFactory(outcome_token=outcome_token, sender=account1, market=market) url = reverse('api:shares-by-account', kwargs={'account_address': account1}) shares_response = self.client.get(url, content_type='application/json') decoded_response = json.loads(shares_response.content) self.assertEqual(len(decoded_response.get('results')), 1) self.assertEqual( decoded_response.get('results')[0].get('eventDescription').get( 'title'), oracle.event_description.title) self.assertEqual( decoded_response.get('results')[0].get('marginalPrice'), 0.5) url = reverse('api:shares-by-account', kwargs={'account_address': account2}) no_shares_response = self.client.get(url, content_type='application/json') self.assertEqual( len(json.loads(no_shares_response.content).get('results')), 0)
def test_market_fee_withdrawal_rollback(self): market_factory = MarketFactory() block = {'number': 1, 'timestamp': self.to_timestamp(datetime.now())} market_withdraw_event = { 'name': 'FeeWithdrawal', 'address': market_factory.address, 'params': [{ 'name': 'fees', 'value': 10 }] } MarketInstanceReceiver().save(market_withdraw_event) market_without_rollback = Market.objects.get( address=market_factory.address) self.assertEqual(market_without_rollback.withdrawn_fees, market_factory.withdrawn_fees + 10) # Rollback MarketInstanceReceiver().rollback(market_withdraw_event, block) market_with_rollback = Market.objects.get( address=market_factory.address) self.assertEqual(market_with_rollback.withdrawn_fees, market_factory.withdrawn_fees)
def test_market_trades(self): url = reverse('api:trades-by-market', kwargs={'market_address': '{:040d}'.format(1000)}) trades_response = self.client.get(url, content_type='application/json') self.assertEqual(trades_response.status_code, status.HTTP_404_NOT_FOUND) # create markets outcome_token = OutcomeTokenFactory() event = outcome_token.event oracle = event.oracle market = MarketFactory(event=event) creation_date_time = datetime.now() # Create Order order = ShortSellOrder() order.creation_date_time = creation_date_time order.creation_block = 0 order.market = market order.sender = '0x1' order.outcome_token = outcome_token order.outcome_token_count = 1 order.cost = 1 order.net_outcome_tokens_sold = market.net_outcome_tokens_sold order.marginal_prices = ["0.5000", "0.5000"] order.save() url = reverse('api:trades-by-market', kwargs={'market_address': market.address}) trades_response = self.client.get(url, content_type='application/json') trades_data = json.loads(trades_response.content) self.assertEqual(trades_response.status_code, status.HTTP_200_OK) self.assertEqual(len(trades_data.get('results')), 1) self.assertEqual( trades_data.get('results')[0].get('marginalPrices')[0], order.marginal_prices[0]) from_date = (creation_date_time - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') to_date = (creation_date_time + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') url = reverse('api:trades-by-market', kwargs={'market_address': market.address}) url += '?creation_date_time_0=' + from_date + '&creation_date_time_1=' + to_date trades_response = self.client.get(url, content_type='application/json') self.assertEqual(trades_response.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(trades_response.content).get('results')), 1) # test querying date with no orders from_date = (creation_date_time - timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S') to_date = (creation_date_time - timedelta(days=4)).strftime('%Y-%m-%d %H:%M:%S') url = reverse('api:trades-by-market', kwargs={'market_address': market.address}) url += '?creation_date_time_0=' + from_date + '&creation_date_time_1=' + to_date trades_response = self.client.get(url, content_type='application/json') self.assertEqual(trades_response.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(trades_response.content).get('results')), 0) # test querying date passing only the from param from_date = (creation_date_time - timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S') url = reverse('api:trades-by-market', kwargs={'market_address': market.address}) url += '?creation_date_time_0=' + from_date trades_response = self.client.get(url, content_type='application/json') self.assertEqual(trades_response.status_code, status.HTTP_200_OK) self.assertEqual( len(json.loads(trades_response.content).get('results')), 1)