示例#1
0
    def __init__(self, name, product, wallet):
        self.name = name
        self.product = product
        self.wallet = wallet
        logging.info ("[Seller]:Seller %s Created",self.name)
        # register the seller in market
        Market.register_seller(self, product)

        # metrics tracker
        self.sales_history = []
        self.revenue_history = []
        self.profit_history = []
        self.expense_history = [0]
        self.sentiment_history = []
        self.item_sold = 0
        self.total_item_sold=0
        self.quater=[]
        self.tickcount=0
        # Flag for thread
        self.STOP = False

        self.lock = Lock()

        # start this seller in separate thread
        self.thread = Thread(name=name, target=self.loop)
        self.thread.start()
示例#2
0
    def market_init(self, product):
        #         usd_acc = self.binance_accounts['USD']
        #         crypto_acc = self.binance_accounts.get(product['base_currency'])
        #         if (usd_acc == None or crypto_acc == None):
        #             log.error ("No account available for product: %s"%(product['id']))
        #             return None
        #Setup the initial params
        #         log.debug ("product: %s"%product)
        market = Market(product=product, exchange=self)
        market.fund.set_initial_value(Decimal(0))  #usd_acc['available']))
        market.fund.set_hold_value(Decimal(0))  #usd_acc['hold']))
        market.fund.set_fund_liquidity_percent(10)  #### Limit the fund to 10%
        market.fund.set_max_per_buy_fund_value(100)
        market.asset.set_initial_size(Decimal(0))  #crypto_acc['available']))
        market.asset.set_hold_size(0)  #Decimal(crypto_acc['hold']))

        ## Feed Cb
        market.consume_feed = self._binance_consume_feed

        ## Init Exchange specific private state variables
        market.O = market.H = market.L = market.C = market.V = 0
        market.candle_interval = self.candle_interval
        log.info("Market init complete: %s" % (product['id']))

        #set whether primary or secondary
        market.primary = self.primary

        return market
示例#3
0
    def trade_a_priced(self, environment, time):
        # We find the market price of A shares
        # given supply and demand of the agents
        # and tolerance of error, resolution of search
        # and amplification factor for exponential search
        suppliers = []
        for agent in environment.firms:
            if agent.domicile == 0:
                # print agent.get_account("number_of_shares"), agent.identifier
                suppliers.append([agent, agent.supply_of_shares])
        # And the list of buyers and their demand functions
        buyers = []
        for agent in environment.funds:
            buyers.append([agent, agent.demand_a])
        price_dummy = 75

        from market import Market
        # Put the appropriate settings, i.e. desired identifier
        market = Market("market")
        price = market.tatonnement(suppliers, buyers, price_dummy, 0.001, 0.01,
                                   1.1)
        environment.variable_parameters["price_of_a"] = price
        # print price
        # now we use rationing to find the actual transactions between agents
        for_rationing = []
        for firm in environment.firms:
            if firm.domicile == 0:
                for_rationing.append([firm, firm.supply_of_shares(price)])
        for fund in environment.funds:
            for_rationing.append([fund, -fund.demand_a(price)])

        # And we find the rationing, ie the amounts
        # of shares sold between pairs of agents
        rationed = market.rationing_proportional(for_rationing)
示例#4
0
文件: team.py 项目: vmgarcia/CSGOSim
def test():
  player = Player(1, Team("Na'Vi", Sides.CT), .5, .2)
  Market.loadout_player(player, True)
  print player.loadout
  player.money += 4400
  Market.loadout_player(player, False)
  print player.loadout
示例#5
0
class Manager:
    # __init___
    # this constructs the Manager object
    def __init__(self):
        self.world = {}
        self.market = Market()
        self.players = []
        self.miningQueue = []

    # addPlayer
    # @player(object): a player object. See player.py for details
    # @initialState(dict): the initial state of the given player
    def addPlayer(self, player, initialState: dict):
        self.players.append(player)
        self.world[player.name] = initialState

    # playOneRound
    # run one round of the game and apply the actions proposed by each player
    # this is the "event loop" of the game
    def playOneRound(self):
        for player in self.players:
            if player.free:
                print("-------" + player.name + "'s turn-------")
                actions = player.generateActions(self.world, self.market)
                print(player.name, "proposed:")
                for action in actions:
                    print(action.toString())
                    if isinstance(action, Mine):
                        player.free = False
                        heapq.heappush(self.miningQueue,
                                       [action.difficulty, action])
                    else:
                        action.execute(self.world)
                print("-" * (len(player.name) + 21))
                print()
        self.runMiningQueue()
        self.market.settle(self.world)

    # runMiningQueue
    # update the mining queue
    def runMiningQueue(self):
        for pairs in self.miningQueue:
            pairs[0] = pairs[0] - 1
        while self.miningQueue and self.miningQueue[0][0] == 0:
            self.miningQueue[0][1].execute(self.world)
            heapq.heappop(self.miningQueue)

    # run
    # run the game with the given round limit
    # @rounds: the round limit
    def run(self, rounds: int):
        for i in range(0, rounds):
            print("-----------Round " + str(i + 1) + "-----------")
            self.playOneRound()
            print("-------End of Round " + str(i + 1) + "--------")
            print("World State:", self.world)
            print()
            print("------------Market------------")
            self.market.printOrderBook()
            print()
示例#6
0
def run(args):
    market = Market(args.market)
    with Inventory(args.inventory) as inventory:
        items = [{
            "name": item["name"],
            "count": item["count"],
            "market": market.item(item["name"])
        } for item in inventory.get_items()]

        for item in items:
            if not item["market"]["ducats"]:
                item["market"]["ducats"] = 0

        if args.ducats:
            items = sorted(items,
                           key=lambda a: -a["market"]["ducats"] / a["market"][
                               "stats"][-1]["median"])
        elif args.plats:
            items = sorted(items,
                           key=lambda a: -a["market"]["stats"][-1]["median"])
        else:
            items = sorted(items, key=lambda a: a["name"])

        print(f'{"Ducats/Price":>60} {"Volume":>9} {"Price":>9}')
        for item in items:
            label = f'{item["count"]}x {item["name"].replace("_", " ").title()}'
            market_stats = item["market"]["stats"][-1]
            ducats = item["market"]["ducats"] / market_stats["median"]
            print(
                f'{label:50} {ducats:9.2f} {market_stats["volume"]:9} {market_stats["median"]:9.2f}'
            )
示例#7
0
def main():
    # Parse Input
    if len(sys.argv) != 2:
        print('Usage: python main.py <path-to-data>')
        return
    data_dir = sys.argv[1]

    # Load Data
    trade_dates, market_data = data.load_data(data_dir)
    market = Market(market_data)
    trade_dates = _find_range(trade_dates)

    # Output Starting Conditions
    print(f'Starting cash: ${STARTING_CASH:,.2f}')
    print(f'Monthly cash: ${MONTHLY_CASH:,.2f}')
    print(f'Trading Start: {trade_dates[0]}')
    print(f'Trading End: {trade_dates[-1]}')
    print('')
    print('Strategies:')
    for strat in STRATEGIES:
        print(f'    {strat.name()}')
    print('')

    # Run Backtest
    for trade_date in trade_dates:
        market.set_date(trade_date)
        for strat in STRATEGIES:
            strat.notify_day(trade_date, market)

    # Output Results
    for strat in STRATEGIES:
        name = strat.name()
        result = strat.total_balance(market)
        contribs = strat.total_contributions()
        print(f'{name} ended with ${result:,.2f} from ${contribs:,.2f} in contributions')
示例#8
0
class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_mode=0, dev_mode=False):

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        if seed_mode == 0:
            self.transport.join_network(dev_mode=dev_mode)

        self.market = Market(self.transport)
        self.market.republish_contracts()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport
示例#9
0
def market():
    player = game.get_player()
    techlevels = game.get_techlevels()

    is_winning_region = game.get_universe().get_winningitem_region(
    ) == game.get_universe().get_currentregion()

    #admin cheats :)
    print("ADMIN CHEATS")
    print(game.get_universe().get_winningitem_region().get_name())
    print(game.get_universe().get_currentregion().get_name())
    print(is_winning_region)

    market = Market(techlevels.index(request.form['techlevel']),
                    player.get_merchant_skills(), player.get_name(),
                    is_winning_region)
    game.set_market(market)

    print(player.get_inventory())

    empty_inventory = False
    if player.get_inventory() == {}:
        empty_inventory = True

    return render_template('market.html',
                           market=json.dumps(market.intoarrayjsonform()),
                           techlevel=request.form['techlevel'],
                           credits=player.get_credits(),
                           inventory=json.dumps(
                               player.get_inventory_array_json()),
                           inventory_status=empty_inventory)
示例#10
0
def get_offers():
    response = requests.get(
        "https://www.edeka.de/eh/service/eh/ods/offers?marketId=8001350&limit=89899"
    )
    jsonData = json.loads(response.text)

    market = Market("edeka")
    market.valid_from = datetime.utcfromtimestamp(jsonData['gueltig_von'] /
                                                  1000)
    market.valid_until = datetime.utcfromtimestamp(jsonData['gueltig_bis'] /
                                                   1000)

    for jsonArticle in jsonData['docs']:
        article = Article()
        article.label = jsonArticle['titel']
        article.price = jsonArticle['preis']
        article.url = jsonArticle['bild_app']

        result = re.search('\((.*)\)', jsonArticle['beschreibung'])
        if result != None:
            unit = result.group(1).split('=')
            article.unit = unit[0]
            article.price_unit = unit[1]

        market.articles.append(article)

    return market
示例#11
0
def createmarket(numagents=15):
    agents = []
    market = Market()
    initbaseprices(market.marketprices)
    for x in range(numagents):
        agents.append(makerandomagent(market))
        market.addagent(agents[-1])
    return agents, market
示例#12
0
文件: team.py 项目: vmgarcia/CSGOSim
  def respawn_players(self, env, pistol):

    for player in self.players:
      if (pistol):
        player.reset_money()

      player.respawn(env, pistol)
      Market.loadout_player(player, pistol)
def deadw(m):
    "Computes deadweight loss for market m."
    # == Create analogous market with no tax == #
    m_no_tax = Market(m.ad, m.bd, m.az, m.bz, 0)   
    # == Compare surplus, return difference == #
    surp1 = m_no_tax.consumer_surp() + m_no_tax.producer_surp()  
    surp2 = m.consumer_surp() + m.producer_surp() + m.taxrev()
    return surp1 - surp2
示例#14
0
    def init(self):
        self.citizens = []
        for i in range(self.default_population):
            self.citizens.append(Citizen(self, self.data_path))

        self.market = Market(self.data_path)

        self.day = 0
示例#15
0
文件: main.py 项目: nanojack/fx
class FxSystem(object):
    def __init__(self, pair, period, data_file):
        self.market = Market(pair, period)
        self.market.load_data(data_file)
        self.account = Account(self.market)

    def __repr__(self):
        out = "Fx System Trading {0} {1}.".format(self.market, self.account)
        return out
示例#16
0
    def evaluate_strategy(self, strategy, mode=None):
        for dp in self.dp_timeslots:
            # Run a market sequence with all the bids of the corresponding dp
            strdp                                     = str(dp) if dp>9 else "0"+str(dp)
            bid_file_tag                             = "dp" + strdp + "d1"
            customer_bid_file_tag                     = "dp" + strdp + "d1cc"
            delivery_product                         = self.initiate_dps([dp])[0]
            market                                     = Market(delivery_product, bid_file_tag, customer_bid_file_tag, printing_mode=False)
            market.main()

        return 0
示例#17
0
def main_menu(session, base_url):
    """
    Provides the different options for the sample application: Market Quotes, Account List

    :param session: authenticated session
    """

    market = Market(session, base_url)
    accounts = Accounts(session, base_url)
    order = Order(session, {}, base_url)

    # ret = market.quoteCommon("vsat")
    # print ("MARKET FOR VST", ret)

    accountsObj = accounts.printPorfolio(PERCENT)
    accountsList = accountsObj['acct']
    accountsPort = accountsObj['port']
    ordersAcct = {}
    for account in accountsList:
        ordersAcct[account['accountId']] = order.viewOpenOrder(account, False)
    checkAccountOrder(accountsPort, ordersAcct)
    menu_items = {"1": "Market Quotes",
                  "2": "Account List",
                  "3": "Place File order", 
                  "4": "Cancel all open orders",
                  "5": "Cancel ALL orders and redo on current price",
                  "6": "redo diff orders",
                  "7": "Exit"}

    while True:
        print("")
        options = menu_items.keys()
        for entry in options:
            print(entry + ")\t" + menu_items[entry])
        selection = input("Please select an option: ")
        if selection == "1":
            market.quotes()
        elif selection == "2":
            accounts.account_list()
        elif selection == "3":
            order.readCSV(False)
        elif selection == "4":
            for account in accountsList:
                order.viewOpenOrder(account, True)
        elif selection == "5":
            for account in accountsList:
                order.viewOpenOrder(account, True)
            order.readCSV(True)
        elif selection == "6":
            order.dodiff()
        elif selection == "7":
            break
        else:
            print("Unknown Option Selected!")
示例#18
0
 def __init__(self):
     super(StockSimApp, self).__init__()
     self.market = Market()
     self.ais = generate_ai()
     self.market.add_ais(self.ais)
     for each in self.market.ais:
         each.market = copy(self.market.basic)
     self.user = User(self.market)
     self.current_company = "AAPL"
     self.current_price = str(float(self.market.basic["AAPL"][-1]))
     self.generate_graph(self.current_company)
示例#19
0
    def buy(self, product):
        # if not enough money in wallet, don't proceed
        if self.wallet < product.price:
            return

        # purchase the product from market
        
        Market.buy(self, product)

        # add product to the owned products list
        self.owned_products.add(product)
示例#20
0
文件: test_suite.py 项目: cfalz/Kitch
def testSamePlateOffer():
    carl = Chef("carl")
    fred = Chef("fred")
    carl.kitch.add_plate(plate_name="Wings")
    carl.kitch.add_plate(plate_name="Tacos")
    fred.kitch.add_plate(plate_name="Wings")
    fred.kitch.add_plate(plate_name="Tacos")
    market = Market()
    market.offer(carl, carl.kitch.get_plate("Wings"))
    market.offer(fred, fred.kitch.get_plate("Wings"))
    assert (market.itemsOnMarket[carl][0].name == "Wings")
    assert (market.itemsOnMarket[fred][0].name == "Wings")
示例#21
0
def hist_test(rounds=1):
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(100)] # 100 random angets
    agents = {agent.id: agent for agent in agents}

    market = Market()
    market.agents = agents

    for i in range(rounds): #10 rounds of market simulation   
        market.simulate()

    return market.history.export()
示例#22
0
def build_market(num_agents):
    """ This returns a market with the number of agents from the parameter
    right now, 100,000 agents is about the most it can handle.  I was able to create a market with 500,000
    but one round of market.simulate() took over a minute.  1,000,000 agents couldn't even be created."""
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(num_agents)] # 100 random angets
    agents = {agent.id: agent for agent in agents}

    market = Market()
    market.agents = agents
    
    return market
示例#23
0
    def make_reservation(self, market_name, participant):
        if self.has_market(market_name):
            market = self.markets[market_name]
            market.make_reservation(participant)
        else:
            market = Market(market_name, participant, self.publish,
                            self.verbose_logging)
            self.markets[market_name] = market

            # Set price for the market
            parts = market_name.split('_')
            forecast_hour = int(parts[-1])
            market.set_price(self.prices[forecast_hour])
示例#24
0
 def test_get_stored_market_names__contains_files(self, mock_os):
     market = Market('market')
     DummyFile('a')
     filename_list = ['a', 'b', 'c', 'd']
     dummyfile_list = [
         DummyFile('a'),
         DummyFile('b'),
         DummyFile('c'),
         DummyFile('d')
     ]
     iterator_filelist = iter(dummyfile_list)
     mock_os.scandir.return_value = iterator_filelist
     self.assertEqual(market.get_stored_market_names(), filename_list)
示例#25
0
    def __init__(self, interval="day", market_wrapper: Market = None, verbose=False):
        self._data = pd.DataFrame()
        self._tickers = []
        self._etfs = None

        self.market = Market() if market_wrapper is None else market_wrapper
        self.interval = interval
        self.data_file = MAIN_FOLDER / f"ETFs_history_i={interval}.csv"
        self.tickers_file = MAIN_FOLDER / f"tickers_i={interval}.dat"
        self.verbose = verbose

        # Update
        self._load_data()
示例#26
0
    def __init__(self, name, products_list, wallet):
        """
        A class to represent the seller
        :param name: seller name string, eg. apple
        :param products_list: list of products sold by the seller
        :param wallet: total money owned by the seller
        """
        self.name = name
        # Each seller can sell multiple products in products_list
        self.products_list = products_list
        # self.product = product
        self.wallet = wallet

        # register the seller with each product it owns in market
        if products_list is not None:
            for product in products_list:
                Market.register_seller(self, product)

        # metrics tracker:
        # item_sold is total number of items of each product sold by seller.
        # A dictionary with each product as key and value is no. of items sold.eg.{iphone: 0, airpods: 0}
        self.item_sold = {key: 0 for key in products_list}

        # inventory is a list of dictionary with product as key and inventory number as value for each quarter
        # assume initial inventory is 1000 items for each product. Eg.{iphone: 1000, airpods: 1000}
        self.inventory = {key: 1000 for key in products_list}

        # sales, revenue, profit, expense and sentiment history start with zero for each product
        # Eg.[{iphone: 0, airpods: 0}] {key: 0 for key in products_list}
        self.sales_history = []
        self.revenue_history = []
        self.profit_history = []
        self.expense_history = [{key: 0 for key in products_list}]
        self.sentiment_history = []
        # advert_type and scale store data of advertisement strategy and users viewing ads for each product
        self.advert_history = [{key: (GoogleAds.ADVERT_BASIC, 1) for key in products_list}]
        self.promo_history = []
        self.buyer_history = []
        self.total_revenue = []
        self.total_expense = []
        self.total_profit = []
        self.budget = [wallet]

        # Flag for thread
        self.STOP = False

        self.lock = Lock()

        # start this seller in separate thread
        self.thread = Thread(name=name, target=self.loop)
        self.thread.start()
示例#27
0
    def test_new_pricelevel(self):
        """ Add new bid and ask orders and checks price-time priority
        
        """

        market = Market()
        bidprice = np.random.uniform(0.0001, 100000)
        o1 = namedtuple('Order', 'is_buy, qty, price')
        o1 = o1(is_buy=True, qty=10, price=bidprice)
        o2 = namedtuple('Order', 'is_buy, qty, price')
        o2 = o2(is_buy=True, qty=5, price=bidprice)
        o3 = namedtuple('Order', 'is_buy, qty, price')
        o3 = o3(is_buy=True, qty=7, price=bidprice)

        # Check price level creation, heads and tails, uid & order active
        o1uid = market.send(*o1)
        self.assertIn(o1.price, market._bids.book.keys())
        self.assertEqual(market._bids.best.price, o1.price)
        self.assertEqual(market._bids.best.head.uid, o1uid)
        self.assertEqual(market._bids.best.tail.uid, o1uid)
        self.assertEqual(market._orders[o1uid].uid, o1uid)
        self.assertEqual(market.get(o1uid)['active'], True)
        o2uid = market.send(*o2)
        self.assertEqual(market._bids.best.price, bidprice)
        # Check time priority inside PriceLevel
        self.assertEqual(market._bids.best.head.uid, o1uid)
        o3uid = market.send(*o3)
        self.assertEqual(market._bids.best.head.uid, o1uid)
        self.assertEqual(market._bids.best.head.next.uid, o2uid)
        self.assertEqual(market._bids.best.tail.uid, o3uid)
        # Check list of orders

        ### SAME FOR ASKS
        askprice = bidprice + 0.0001
        o4 = namedtuple('Order', 'is_buy, qty, price')
        o4 = o4(is_buy=False, qty=10, price=askprice)
        o5 = namedtuple('Order', 'is_buy, qty, price')
        o5 = o5(is_buy=False, qty=5, price=askprice)
        o6 = namedtuple('Order', 'is_buy, qty, price')
        o6 = o6(is_buy=False, qty=7, price=askprice)

        # Check price level creation, heads and tails
        o4uid = market.send(*o4)
        self.assertIn(askprice, market._asks.book.keys())
        self.assertEqual(market._asks.best.price, o4.price)
        self.assertEqual(market._asks.best.head.uid, o4uid)
        self.assertEqual(market._asks.best.tail.uid, o4uid)
        self.assertEqual(market._orders[o4uid].uid, o4uid)
        o5uid = market.send(*o5)

        # Check time priority inside PriceLevel
        self.assertIs(market._asks.best.head.uid, o4uid)
        o6uid = market.send(*o6)
        self.assertEqual(market._asks.best.head.uid, o4uid)
        self.assertEqual(market._asks.best.head.next.uid, o5uid)
        self.assertEqual(market._asks.best.tail.uid, o6uid)
示例#28
0
文件: test_suite.py 项目: cfalz/Kitch
def testMarketTransaction():
    market, fred, carl = setUpMarket()
    patron = Chef("patrano")
    platesOnMarket = market.get_plates_for_sale()
    market.buy(patron, platesOnMarket[0])
    printMarket(market)
    assert (patron.cart.get_order()[0].name == "Wings")
    assert (len(fred.kitch.patron_orders) == 1)
    assert (len(carl.kitch.patron_orders) == 0)
    chef1 = Chef()
    chef2 = Chef()
    chef1.name = "Carl"
    chef2.name = "Fred"
    chef1.add_plate(plate_name="Wings")
    chef1.add_plate(plate_name="Tacos")
    chef2.add_plate(plate_name="Boneless Wings")
    chef2.add_plate(plate_name="Burritos")
    chef1.kitch.get_plate("Wings").add_item(Item(name="wing", price=2.50))
    chef1.kitch.get_plate("Wings").add_item(Item(name="wing2", price=2.50))
    chef1.kitch.get_plate("Tacos").add_item(Item(name="wing", price=2.50))
    chef2.kitch.get_plate("Boneless Wings").add_item(
        Item(name="beans", price=2.50))
    chef2.kitch.get_plate("Boneless Wings").add_item(
        Item(name="cheese", price=2.50))
    chef2.kitch.get_plate("Burritos").add_item(Item(name="cheese", price=2.50))
    market = Market()
    market.offer(chef1, chef1.get_plate("Wings"))
    market.offer(chef1, chef1.get_plate("Tacos"))
    market.offer(chef2, chef2.get_plate("Boneless Wings"))
    market.offer(chef2, chef2.get_plate("Burritos"))
    return market, chef1, chef2
示例#29
0
class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport._dht._refreshNode()
            self.market.republish_contracts()

        if seed_mode == 0:
            self.transport.join_network(seed_peers, post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)
        else:
            self.transport.join_network([], post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)




    def get_transport(self):
        return self.transport
示例#30
0
class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport._dht._refreshNode()
            self.market.republish_contracts()

        if seed_mode == 0:
            self.transport.join_network(seed_peers, post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)
        else:
            self.transport.join_network([], post_joined)
            ioloop.PeriodicCallback(self.transport.join_network, 60000)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)




    def get_transport(self):
        return self.transport
示例#31
0
 def __init__(self, access_token=''):
     self.Account = Account(access_token=access_token)
     self.Apps = Apps(access_token=access_token)
     self.Audio = Audio(access_token=access_token)
     self.Auth = Auth(access_token=access_token)
     self.Board = Board(access_token=access_token)
     self.Database = Database(access_token=access_token)
     self.Docs = Docs(access_token=access_token)
     self.Other = Other(access_token=access_token)
     self.Fave = Fave(access_token=access_token)
     self.Friends = Friends(access_token=access_token)
     self.Gifts = Gifts(access_token=access_token)
     self.Groups = Groups(access_token=access_token)
     self.Likes = Likes(access_token=access_token)
     self.Market = Market(access_token=access_token)
     self.Messages = Messages(access_token=access_token)
     self.Newsfeed = Newsfeed(access_token=access_token)
     self.Notes = Notes(access_token=access_token)
     self.Notifications = Notifications(access_token=access_token)
     self.Pages = Pages(access_token=access_token)
     self.Photos = Photos(access_token=access_token)
     self.Places = Places(access_token=access_token)
     self.Polls = Polls(access_token=access_token)
     self.Search = Search(access_token=access_token)
     self.Stats = Stats(access_token=access_token)
     self.Status = Status(access_token=access_token)
     self.Storage = Storage(access_token=access_token)
     self.Users = Users(access_token=access_token)
     self.Utils = Utils(access_token=access_token)
     self.Video = Video(access_token=access_token)
     self.Wall = Wall(access_token=access_token)
     self.Widgets = Widgets(access_token=access_token)
示例#32
0
    def __init__(self, store_file, my_market_ip, my_market_port, my_node_port,
                 my_node_file, seed_uri, market_id):

        self.transport = CryptoTransportLayer(my_market_ip, my_market_port,
                                              market_id, store_file)
        self.transport.join_network(seed_uri)

        data_store = SQLiteDataStore(
        )  # creates in-memory database, should be persistent
        known_nodes = self.known_entangled_nodes(my_node_file, seed_uri,
                                                 my_node_port)
        # initializes node with specified port and an in-memory SQLite database
        self.node = entangled.node.EntangledNode(udpPort=my_node_port,
                                                 dataStore=data_store)

        self.node.joinNetwork(known_nodes)

        self.market = Market(self.transport, self.node, store_file)

        handlers = [(r"/", MainHandler), (r"/main", MainHandler),
                    (r"/html/(.*)", tornado.web.StaticFileHandler, {
                        'path': './html'
                    }),
                    (r"/ws", WebSocketHandler,
                     dict(transport=self.transport, node=self.market))]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
示例#33
0
 def change2market(self):
     self.buildings = Market(world=self.world,
                             village=self.village,
                             root=self.f_screen,
                             resources=self.resources,
                             row_i=3,
                             column_i=1)
示例#34
0
 def __init__(self):
     # Gui.__init__(self)
     # gui
     self.root = Tk()
     # compositions
     self.travian = Travian(self.root)
     self.market = Market(self.root, self.travian)
     self.raiding = Raiding(self.root, self.travian)
     self.info = Info(self.root, self.travian)
     # self.mail = Mail()
     # frames
     self.exit_frame = Frame(self.root, bd=5, relief=GROOVE)
     # items
     self.intvars = self.create_intvars()
     self.msg_var = StringVar()
     self.msg_var.set('Messages')
     self.old_news = self.create_news()
     self.news = self.create_news()
     # widgets
     self.buttons = self.create_buttons()
     self.checkboxes = self.create_checkboxes()
     self.messages = self.create_messages()
     # configure gui
     self.config_root()
     self.make_market_frame()
     self.make_raid_frame()
     self.make_info_frame()
     self.make_exit_frame()
示例#35
0
    def __init__(self, agent, generator):
        """
        Backtest evaluates a trading agent based on a data generator instance
        that yields events based on a set of sources.

        :param agent:
            Agent, trading agent instance
        :param generator
            Generator, data generator instance
        """

        # from arguments
        self.agent = agent
        self.generator = generator

        # data updated chunk-wise by the generator
        self.sources = None
        self.monitor = None

        # identify symbols as market_ids
        symbols = set(source_id.split(".")[0] for source_id
            in self.generator.sources
        )
        # setup market instances
        for market_id in symbols:
            Market(market_id)
        # access market instances
        self.markets = Market.instances
示例#36
0
    def __init__(self, environment):
        if environment.assets[0].identifier == "A":
            self.asset_a = environment.assets[0]
            self.asset_b = environment.assets[1]
        else:
            self.asset_b = environment.assets[0]
            self.asset_a = environment.assets[1]

        self.scenario = "no_QE"
        # self.scenario = "QE"

        from market import Market
        self.market = Market("market", self.scenario)

        self.count_trade_a = []
        self.count_trade_b = []
示例#37
0
 def run_one_market(self, dp):
     try:
         bid_file_tag                                 = dt.strftime(dp, "%Y-%m-%d_%H-%M-%S")
         market                                         = Market(dp, bid_file_tag, "N/A", self.use_dynamic_timestep, printing_mode=False,timeslot_length=self.timestep)
         market.alternative_runner()
         
         # Collect the stats
         self.stats.append(market.get_stats())
         
         # Clean up
         del market
     except:
         print(dp, "Could not run market properly...")
     
     finally:
         return dp
示例#38
0
    def __init__(self, ob_ctx):
        self.shutdown_mutex = Lock()
        self.ob_ctx = ob_ctx
        db = Obdb(ob_ctx.db_path, ob_ctx.disable_sqlite_crypt)
        self.transport = CryptoTransportLayer(ob_ctx, db)
        self.market = Market(self.transport, db)
        self.upnp_mapper = None

        Thread(target=reactor.run, args=(False, )).start()

        peers = ob_ctx.seeds if not ob_ctx.seed_mode else []
        self.transport.join_network(peers)

        handlers = [(r"/", MainHandler), (r"/main", MainHandler),
                    (r"/html/(.*)", OpenBazaarStaticHandler, {
                        'path': './html'
                    }),
                    (r"/ws", WebSocketHandler,
                     dict(transport=self.transport,
                          market_application=self,
                          db=db))]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        super(MarketApplication, self).__init__(handlers, **settings)
示例#39
0
def main(argv):
    """ runtime entrypoint """
    try:
        args = extract_args(argv)
        timestamp = datetime.now()
        print('*** model-goals ***')
        print('  model run time: {}'.format(timestamp))
        print('  goals file: {}'.format(args[0]))
        print('  site file: {}'.format(args[1]))
        print('  exchange file: {}'.format(args[2]))
        print('  exchange id: {}'.format(args[3]))

        goals = load_yaml(args[0])
        sites = load_yaml(args[1])
        exchange = Market(load_yaml(args[2]), args[3])

        report.start()
        report.output_general('Starting State')
        print_state(sites, exchange)
        report.end()

        consumption = execute_goals(goals, sites, exchange)
        report.newline()
        report.start()
        summary = consumption.summarize_inventory(exchange)
        report.output_value_table(summary['inventory'],
                                  "Consumption for all Goals")
        report.end()
        report.newline()
        print(output.getvalue())
        return 0

    except Exception:
        traceback.print_exc()
        return 100
示例#40
0
    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)
        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        if seed_mode == 0:
            self.transport.join_network(seed_peers)

        self.market = Market(self.transport, db)
        self.market.republish_contracts()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
示例#41
0
def main():
    
    clear()
    print('Initializing Test...')
    
    print('Creating Agents...')
    
    agent_types = ['miner', 'farmer', 'refiner', 'woodcutter', 'blacksmith']
    agents = [Agent(random.choice(agent_types)) for i in range(100)] # 100 random angets
    agents = {agent.id: agent for agent in agents}
    
    # Debug Printing
    #print('Sample Agents...')
    #for agent in agents[:10]:
    #    print(agent)
    
    input('Hit any key to continue...')
    print('Creating Market...')
    market = Market()
    market.agents = agents #This needs to be part of the api for Market class
   
    
    for i in range(50): #10 rounds of market simulation    
        clear()
        market.simulate()
        report = market.market_report()    
        print(report)
        report = market.agent_report()
        print(report)
        input('Hit any key to continue...')
def test_market(n, m, t, partial, writer):
    market = Market(n, m, t, partial)
    serialDictatorship.serial_dictatorship(market)
    serial_happy = evaluation.happy(market)
    serial_percent_served = evaluation.percent_served(market)
    serial_avg_time = evaluation.average_time(market)

    market.reset()
    serialDictatorship.modified_serial_dictatorship(market)
    mod_happy = evaluation.happy(market)
    mod_percent_served = evaluation.percent_served(market)
    mod_avg_time = evaluation.average_time(market)

    market.reset()
    minLocations.minimize_locations(market)
    min_loc_happy = evaluation.happy(market)
    min_loc_percent_served = evaluation.percent_served(market)
    min_loc_avg_time = evaluation.average_time(market)

    row = [n, m, t, partial, serial_happy, serial_percent_served,
           serial_avg_time, mod_happy, mod_percent_served, mod_avg_time,
           min_loc_happy, min_loc_percent_served, min_loc_avg_time]
    writer.writerow(row)
示例#43
0
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market_application=self, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)
示例#44
0
class MarketApplication(tornado.web.Application):
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market_application=self, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mappings(self, http_port, p2p_port):
        upnp.PortMapper.DEBUG = False
        print "Setting up UPnP Port Map Entry..."
        # TODO: Add some setting whether or not to use UPnP
        # if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        # TODO: Add some setting whether or not to clean all previous port
        # mappings left behind by us
        # if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()

        # for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings()
        # result_http_port_mapping = self.upnp_mapper.add_port_mapping(http_port,
        #                                                             http_port)
        # print ("UPnP HTTP Port Map configuration done (%s -> %s) => %s" %
        #        (str(http_port), str(http_port), str(result_http_port_mapping)))

        result_tcp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port)
        print ("UPnP TCP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_tcp_p2p_mapping)))

        result_udp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port,
                                                                   'UDP')
        print ("UPnP UDP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_udp_p2p_mapping)))

        result = result_tcp_p2p_mapping and result_udp_p2p_mapping
        if not result:
            print("Warning: UPnP was not setup correctly. Try doing a port forward on %s and start the node again with -j" % p2p_port)

        return result

    def cleanup_upnp_port_mapping(self):
        try:
            if self.upnp_mapper is not None:
                print "Cleaning UPnP Port Mapping -> ", \
                    self.upnp_mapper.clean_my_mappings()
        except AttributeError:
            print "[openbazaar] MarketApplication.clean_upnp_port_mapping() failed!"
            pass

    def shutdown(self, x=None, y=None):
        print "MarketApplication.shutdown!"
        locallogger = logging.getLogger('[%s] %s' % (self.market.market_id, 'root'))
        locallogger.info("Received TERMINATE, exiting...")

        # application.get_transport().broadcast_goodbye()
        self.cleanup_upnp_port_mapping()
        tornado.ioloop.IOLoop.instance().stop()

        self.transport.shutdown()
        os._exit(0)
import matplotlib.pyplot as plt
import numpy as np
from market import Market

# Baseline ad, bd, az, bz, tax
baseline_params = 15, .5, -2, .5, 3
m = Market(*baseline_params)

q_max = m.quantity() * 2
q_grid = np.linspace(0.0, q_max, 100)
pd = m.inverse_demand(q_grid)
ps = m.inverse_supply(q_grid)
psno = m.inverse_supply_no_tax(q_grid)

fig, ax = plt.subplots()
ax.plot(q_grid, pd, lw=2, alpha=0.6, label='demand')
ax.plot(q_grid, ps, lw=2, alpha=0.6, label='supply')
ax.plot(q_grid, psno, '--k', lw=2, alpha=0.6, label='supply without tax')
ax.set_xlabel('quantity', fontsize=14)
ax.set_xlim(0, q_max)
ax.set_ylabel('price', fontsize=14)
ax.legend(loc='lower right', frameon=False, fontsize=14)
plt.show()
示例#46
0
文件: advisors.py 项目: nanojack/fx
    Returns a value between -1 (indicating short signal)
                        and +1 (indicating long signal)

    Return what when required signal unavailable?

    Consider using sigmoid function to determine binary (ternary?) options
    From linear data
    '''
    def __init__(self, market):
        self.market = market


def CrossoverAnalyser(Analyser):
    '''
    Bases signal on crossover of EAC
    '''

'''
    add the indicators
    need to implement indicators.INDICATOR_INFO
    to matche number of columns and names against talib functions
'''

if __name__ == '__main__':
    from market import Market, DATA_FILE
    m = Market("GBPCAD", "10m")
    m.load_data(DATA_FILE)
    a = Advisor(m)
    a.add_analysis(Analyser)
    print a
示例#47
0
from market import Market

YHOO = Market("YHOO")

print YHOO.price

YHOO.pull_prices()

示例#48
0
class TravianGui:
    def __init__(self):
        # Gui.__init__(self)
        # gui
        self.root = Tk()
        # compositions
        self.travian = Travian(self.root)
        self.market = Market(self.root, self.travian)
        self.raiding = Raiding(self.root, self.travian)
        self.info = Info(self.root, self.travian)
        # self.mail = Mail()
        # frames
        self.exit_frame = Frame(self.root, bd=5, relief=GROOVE)
        # items
        self.intvars = self.create_intvars()
        self.msg_var = StringVar()
        self.msg_var.set('Messages')
        self.old_news = self.create_news()
        self.news = self.create_news()
        # widgets
        self.buttons = self.create_buttons()
        self.checkboxes = self.create_checkboxes()
        self.messages = self.create_messages()
        # configure gui
        self.config_root()
        self.make_market_frame()
        self.make_raid_frame()
        self.make_info_frame()
        self.make_exit_frame()

    # ============================================
    # region ITEMS
    @staticmethod
    def create_intvars():
        dic = OrderedDict()
        dic['sitter'] = IntVar()
        return dic

    def create_news(self):
        dic = OrderedDict()
        dic['send'] = self.market.send.news
        dic['offer'] = self.market.offer.news
        dic['raid'] = self.raiding.news
        dic['info'] = self.info.news
        return dic

    # ============================================
    # region WIDGETS
    def create_buttons(self):
        dic = OrderedDict()
        dic['restart'] = Button(self.exit_frame, text='Restart', width=self.info.button_size, command=self.restart)
        dic['quit'] = Button(self.exit_frame, text='Exit', width=self.info.button_size, command=self.root.destroy)
        return dic

    def create_checkboxes(self):
        dic = OrderedDict()
        dic['sitter'] = Checkbutton(self.exit_frame, text='sitter', variable=self.intvars['sitter'], command=self.set_sitter)
        return dic

    def create_messages(self):
        dic = OrderedDict()
        dic['terminal'] = Message(self.market.offer.frame, textvar=self.msg_var, bg='bisque3', font='times 12', relief=SUNKEN, aspect=300)
        return dic

    # ============================================
    # region COMMANDS
    def config_root(self):
        self.root.title('Travian Helper')
        self.root.geometry('+600-80')  # 530x400

    def restart(self):
        self.root.destroy()
        python = executable
        execl(python, python, *argv)

    def set_sitter(self):
        is_sitter = bool(self.intvars['sitter'].get())
        return self.travian.sitter_mode(is_sitter)

    def message_handler(self):
        self.news = self.create_news()
        for key, value in self.news.iteritems():
            if value != self.old_news[key]:
                self.msg_var.set(value)
                self.old_news[key] = value
        self.messages['terminal'].after(100, self.message_handler)
    #  endregion

    # ============================================
    # region FRAMES AND PACKING
    def make_market_frame(self):
        self.market.frame.grid()
        self.market.make_gui()
        self.messages['terminal'].grid(row=6, columnspan=5, sticky='NEWS', pady=2, padx=2)
        self.market.offer.frame.grid_rowconfigure(6, weight=1)

    def make_raid_frame(self):
        self.raiding.frame.grid(row=0, column=1, sticky='NEWS')
        self.raiding.frame.grid_rowconfigure(1, weight=1)
        self.raiding.make_gui()

    def make_info_frame(self):
        self.info.frame.grid(row=1, columnspan=2, sticky='NEWS')
        self.info.make_gui()

    def make_exit_frame(self):
        self.exit_frame.grid(row=2, columnspan=2, sticky='NEWS')
        self.exit_frame.grid_columnconfigure(0, weight=1)
        self.exit_frame.grid_columnconfigure(1, weight=1)
        self.exit_frame.grid_columnconfigure(2, weight=1)
        self.checkboxes['sitter'].grid(row=0)
        self.buttons['restart'].grid(row=0, column=1, pady=6)
        self.buttons['quit'].grid(row=0, column=2)
    # endregion

    def do_nothing(self):
        pass
示例#49
0
class MarketApplication(tornado.web.Application):

    def __init__(self, market_ip, market_port, market_id=1,
                    bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                    seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                               market_port,
                                               market_id,
                                               db,
                                               bm_user,
                                               bm_pass,
                                               bm_port,
                                               seed_mode,
                                               dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport._dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        join_network_loop = ioloop.PeriodicCallback(self.transport.join_network, 60000)
        join_network_loop.start()

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", tornado.web.StaticFileHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mapping(self,internal_port):
        upnp.PortMapper.DEBUG=False
        print "Setting up UPnP Port Map Entry..."
        #TODO: Add some setting whether or not to use UPnP
        #if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        #TODO: Add some setting whether or not to clean all previous port mappings left behind by us
        #if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()
        
        #for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings()
        result = self.upnp_mapper.add_port_mapping(12345, internal_port)
        print "UPnP Port Map configuration finished ("+str(internal_port)+" -> 12345) => " + str(result)
        return result
    
    def cleanup_upnp_port_mapping(self):
        if self.upnp_mapper != None:
            print "Cleaning UPnP Port Mapping -> ", self.upnp_mapper.clean_my_mappings()
示例#50
0
        # profit - buy base / sell quote
        if self.quote > 0.0:
            profit = self.quote / self.market.get_ask()
        else: # loss - sell base / buy quote
            profit = self.quote / self.market.get_bid()

        #print "Opened at {0}, closed at {1}".format(self.position['price'], price)
        #print "PROFIT: {0} = {1}%".format(profit, 100*profit/self.position['price'])
 
        return profit

class Advisor(object):
    '''
    Uses technical indicators to advise on trading decisions
    '''
    def  __init__(self):
        pass



if __name__ == "__main__":
    market = Market("GBPCAD", "10m")
    market.load_data(DATA_FILE)
    account = Account(market)
    '''
    add the indicators
    need to implement indicators.INDICATOR_INFO
    to matche number of columns and names against talib functions
    '''

示例#51
0
文件: main.py 项目: nanojack/fx
 def __init__(self, pair, period, data_file):
     self.market = Market(pair, period)
     self.market.load_data(data_file)
     self.account = Account(self.market)
示例#52
0
 def sell_labour(self,  environment, time):
     # First we find the market equilibrium price
     # Important to note that this currently does
     # not depend on the wealth of the buyers
     # That is their demand may be higher than
     # what they can actually buy, which may be ok
     # We set the values necessary for tatonnement
     # The list of sellers and their supply functions
     sellers = []
     for agent in environment.households:
         sellers.append([agent, agent.supply_of_labour_solow])
     # And the list of buyers and their demand functions
     buyers = []
     for agent in environment.firms:
         buyers.append([agent, agent.demand_for_labour_solow])
     # We may start the search for price at some specific point
     # Here we pass 0, which means it'll start looking at a
     # random point between 0 and 10
     starting_price = 0.0
     # We initialize the price
     price = 0.0
     # Import market clearing class
     from market import Market
     # Put the appropriate settings, i.e. desired identifier
     market = Market("market")
     # And we find the market price of labour
     # given supply and demand of the agents
     # and tolerance of error, resolution of search
     # and amplification factor for exponential search
     price = market.tatonnement(sellers, buyers, starting_price, 0.00000000001, 0.01, 1.1)
     environment.variable_parameters["price_of_labour"] = price
     # now we use rationing to find the actual transactions between agents
     for_rationing = []
     for household in environment.households:
         for_rationing.append([household, household.supply_of_labour_solow(price)])
     for firm in environment.firms:
         for_rationing.append([firm, -firm.demand_for_labour_solow(price)])
     # And we find the rationing, ie the amounts
     # of goods sold between pairs of agents
     rationed = market.rationing(for_rationing)
     #
     #             A (from)    L (to)
     # bank        loan        deposit
     # household   deposit     labour
     # firm        labour      loan
     #
     for ration in rationed:
         # The labour is an asset (production factor) for the firm
         # and a liability (promise to work) for the household
         environment.new_transaction("labour", "",  ration[1].identifier, ration[0].identifier,
                                     ration[2], 0,  0, -1)
         random_bank = random.choice(environment.banks)
         # Deposit is a liability of the bank
         # and an asset of the household
         environment.new_transaction("deposits", "",  ration[0].identifier, random_bank.identifier,
                                     ration[2]*price, random_bank.interest_rate_deposits,  0, -1)
         # Loan is an asset of the bank
         # and a liability of the firm
         environment.new_transaction("loans", "",  random_bank.identifier, ration[1].identifier,
                                     ration[2]*price, random_bank.interest_rate_loans,  0, -1)
         # We print the action of selling to the screen
         print("%s sold %d units of labour at a price %f to %s at time %d.") % (ration[0].identifier,
                                                                                ration[2], price, ration[1].identifier, time)
     logging.info("  labour sold to firms on step: %s",  time)
示例#53
0
    def consume_rationed(self, environment, time):
        # We want the consumption to be done in random pairs
        # We use rationing from market clearing class to do that
        # Price is static for this example, otherwise we can't use rationing
        # and need some other market clearing
        price = 10.0
        environment.variable_parameters["price_of_goods"] = price
        # We need a list of agents and their demand or supply
        # Supply is denoted with positive float, demand with negative float
        for_rationing = []
        # Firms give us their supply, we assume that since the goods are
        # perishable their supply is all they have in stock
        from src.helper import Helper

        helper = Helper()
        for firm in environment.firms:
            # Firms produce based on their capital, for generality
            # we use their net capital, as in their capital stock
            # minus the capital owned of other agents
            capital = 0.0
            for tranx in firm.accounts:
                # This is own capital stock
                if tranx.type_ == "capital" and tranx.from_ == firm:
                    capital = capital + tranx.amount
                # And here is the ownership of other agents' stock
                if tranx.type_ == "capital" and tranx.to == firm:
                    capital = capital - tranx.amount
            # We find the amount produced through the Cobb-Douglas function
            amount = (
                helper.cobb_douglas(
                    firm.get_account("labour"),
                    capital,
                    firm.total_factor_productivity,
                    firm.labour_elasticity,
                    firm.capital_elasticity,
                )
                * price
            )
            # And assume firm wants to sell whole production given the perishable nature of the goods
            for_rationing.append([firm, amount])
        # Households give use their demand, we assume that they want to
        # consume the part of their wealth (cash and deposits) that they
        # do not want to save (determined through propensity to save)
        # We denote demand in units of the goods, so we divide the cash
        # households want to spend by price to get the demand
        for household in environment.households:
            demand = 0.0
            wealth = 0.0
            # For generality we calculate net wealth for this, that is the
            # amount of deposits they carry minus the amount of loans
            for tranx in household.accounts:
                if tranx.type_ == "deposits" and tranx.from_ == household:
                    wealth = wealth + tranx.amount
                if tranx.type_ == "loans" and tranx.to == household:
                    wealth = wealth - tranx.amount
            # Then the demand is determined by the agent's propensity to save
            # and the wealth calculated above
            demand = -((wealth * (1 - household.propensity_to_save)) / price)
            for_rationing.append([household, demand])
        # We import the market clearing class
        from market import Market

        # Put the appropriate settings, i.e.
        # tolerance of error, resolution of search
        # and amplification for exponential search
        # This does not matter for rationing
        # But in principle we need to initialize
        # with these values
        market = Market("market")
        # And we find the rationing, ie the amounts
        # of goods sold between pairs of agents
        # We find the actual trades
        rationed = market.rationing_proportional(for_rationing)
        # Then we go through the rationing
        # and move the goods and cash appropriately
        for ration in rationed:
            #
            #             A (from)    L (to)
            # bank        loan        deposit
            # household   goods       loan
            # firm        deposit     goods
            #
            # TODO: in the new version this may be irrelevant
            environment.new_transaction("goods", "", ration[1].identifier, ration[0].identifier, ration[2], 0, 0, -1)
            # The below makes sure the allocations of loans are correct
            # That is the banks don't allow overdraft for buying
            # consumption goods by the households
            to_finance = ration[2] * price
            itrange = list(range(0, len(environment.banks)))
            # And randomise this list for the purposes of iterating randomly
            random.shuffle(itrange)
            # And we iterate over the agents randomly by proxy of iterating
            # through their places on the list [agents]
            for i in itrange:
                current_bank = self.environment.banks[i]
                # We find how much in deposits the household has
                deposits_available = 0.0
                for tranx in ration[1].accounts:
                    if tranx.type_ == "deposits" and tranx.to == current_bank:
                        deposits_available = deposits_available + tranx.amount
                    # This should be irrelevant, but for completeness:
                    if tranx.type_ == "loans" and tranx.from_ == current_bank:
                        deposits_available = deposits_available - tranx.amount
                # We find the amount of deposits the household can spend for this particular bank
                current_amount = min(to_finance, deposits_available)
                # And add the appropriate transactions
                environment.new_transaction(
                    "deposits",
                    "",
                    ration[0].identifier,
                    current_bank.identifier,
                    current_amount,
                    current_bank.interest_rate_deposits,
                    0,
                    -1,
                )
                environment.new_transaction(
                    "loans",
                    "",
                    current_bank.identifier,
                    ration[1].identifier,
                    current_amount,
                    current_bank.interest_rate_loans,
                    0,
                    -1,
                )
                to_finance = to_finance - current_amount
            # We print the action of selling to the screen
            print("%s sold %d units of goods at a price %f to %s at time %d.") % (
                ration[0].identifier,
                ration[2],
                price,
                ration[1].identifier,
                time,
            )
        logging.info("  goods consumed on step: %s", time)
示例#54
0
    def capitalise(self, environment, time):
        # We will ration the remaining excess deposits
        # and loan as capital ownership transfers
        # to balance books, if books don't need to be
        # balanced the same would work strictly on deposits
        # and loans with no capital explicitly

        # First resolve capital shortfall for firms
        # ie when firm needs to sell existing  capital instead of getting new owners
        for firm in environment.firms:
            # We calculate how much capital the firm has
            capital = 0.0
            for tranx in firm.accounts:
                if tranx.type_ == "capital":
                    if tranx.from_ == firm:
                        capital = capital + tranx.amount
                    if tranx.to == firm:
                        capital = capital - tranx.amount
            # Then find the firm's supply of capital given current books
            supply = -capital - firm.get_account("deposits") + firm.get_account("loans")
            # If there is a shortfall of capital supply
            if supply < 0.0:
                # We go through the books
                for tranx in firm.accounts:
                    # And find capital transactions
                    if tranx.type_ == "capital" and tranx.from_ == firm:
                        # Then we sell the appropriate amount to cover the shortfall
                        # TODO: we may want the sellout to be proportional or at least
                        # going through books at random, though in the current model it shouldn't matter
                        to_remove = min(-supply, tranx.amount)
                        tranx.amount = tranx.amount - to_remove
                        supply = supply + to_remove

        # First, we create the list that will be used for rationing
        # method from Market class, containing agents and their
        # excess supply or demand
        for_rationing = []

        # First we find household's demand for buying capital of the firms
        for household in environment.households:
            # We calculate the demand as the amount of wealth (deposits-loans) minus previously owned capital
            # We calculate capital by hand in case there is some reverse ownership
            deposits = 0.0
            loans = 0.0
            capital = 0.0
            for tranx in household.accounts:
                if tranx.type_ == "deposits":
                    if tranx.from_ == household:
                        deposits = deposits + tranx.amount
                if tranx.type_ == "loans":
                    if tranx.to == household:
                        loans = loans + tranx.amount
                if tranx.type_ == "capital":
                    if tranx.to == household:
                        capital = capital + tranx.amount
                    if tranx.from_ == household:
                        capital = capital - tranx.amount
            # demand = household.get_account("deposits") - household.get_account("loans") - household.get_account("capital")
            demand = deposits - loans - capital
            # And we add the household together with its demand to the list
            for_rationing.append([household, -demand])

        for firm in environment.firms:
            # Supply of the firms is the opposite of the demand of the household
            # that is the loans minus issued capital claims minus deposits
            # We calculate capital by hand in case there is some reverse ownership
            capital = 0.0
            for tranx in firm.accounts:
                if tranx.type_ == "capital":
                    if tranx.from_ == firm:
                        capital = capital + tranx.amount
                    if tranx.to == firm:
                        capital = capital - tranx.amount
            supply = -capital - firm.get_account("deposits") + firm.get_account("loans")
            # supply = -firm.get_account("capital") - firm.get_account("deposits") + firm.get_account("loans")
            # And we add the firm together with its supply to the list
            for_rationing.append([firm, supply])

        # We initialise the market clearing class
        from market import Market

        market = Market("market")

        # We find the pairs of capital ownership transfers
        # We move the capital proportionately with respect to demand
        rationed = market.rationing_proportional(for_rationing)

        # We add these to the books
        for ration in rationed:
            environment.new_transaction("capital", "", ration[0].identifier, ration[1].identifier, ration[2], 0, 0, -1)
            # And print it to the screen for easy greping
            print("%s sold %f worth of capital to %s at time %d.") % (
                ration[0].identifier,
                ration[2],
                ration[1].identifier,
                time,
            )

        # And net the capital transactions, so we don't accumulate
        # them over the course of the transaction
        # Again, we create a proxy list for deleting transactions
        # as deleting them from a list upon which we are looping is bad
        to_delete = []

        # We go through the firms
        for firm in environment.firms:
            # And then pair them with households
            for household in environment.households:
                # We will look for the capital balance of the pair
                balance = 0.0
                # So we need to look through all their books
                for tranx in household.accounts:
                    # Find the capital transactions
                    if tranx.type_ == "capital":
                        # And if they are ownership of the firm's equity
                        # We add them to the balance
                        # And mark for deletion
                        if tranx.from_ == firm:
                            balance = balance + tranx.amount
                            to_delete.append(tranx)
                        # If they are the other way around for some reason
                        # we would subtract them and mark for deletion
                        elif tranx.to == firm:
                            balance = balance - tranx.amount
                            to_delete.append(tranx)
                # We create a new transactions from the balance
                # depending on what the value of the balance is
                if balance > 0.0:
                    environment.new_transaction("capital", "", firm.identifier, household.identifier, balance, 0, 0, -1)
                elif balance < 0.0:
                    environment.new_transaction("capital", "", household.identifier, firm.identifier, balance, 0, 0, -1)
        # And at the end, we remove all the transactions that we marked before
        for tranx in to_delete:
            tranx.remove_transaction()

        logging.info("  capitalised on step: %s", time)
示例#55
0
    def consume_rationed(self, environment, time):
        # We want the consumption to be done in random pairs
        # We use rationing from market clearing class to do that
        # Price is static for this example, otherwise we can't use rationing
        # and need some other market clearing
        price = 10.0
        environment.variable_parameters["price_of_goods"] = price
        # We need a list of agents and their demand or supply
        # Supply is denoted with positive float, demand with negative float
        for_rationing = []
        # Firms give us their supply, we assume that since the goods are
        # perishable their supply is all they have in stock
        from src.helper import Helper
        helper = Helper()
        for firm in environment.firms:
            # amount = round(helper.leontief([firm.get_account("labour")], [1/firm.productivity]), 0)
            amount = helper.cobb_douglas(firm.get_account("labour"), firm.get_account("capital"),
                                         firm.total_factor_productivity, firm.labour_elasticity, firm.capital_elasticity)*price
            for_rationing.append([firm, amount])
        # Households give use their demand, we assume that they want to
        # consume the part of their wealth (cash and deposits) that they
        # do not want to save (determined through propensity to save)
        # We denote demand in units of the goods, so we divide the cash
        # households want to spend by price to get the demand
        for household in environment.households:
            demand = 0.0
            # demand = -round(((household.get_account("deposits") * (1 - household.propensity_to_save)) / price), 0)
            demand = -((household.get_account("deposits") * (1 - household.propensity_to_save)) / price)
            # demand = -household.get_account("deposits")/price
            for_rationing.append([household, demand])
        # We import the market clearing class
        from market import Market
        # Put the appropriate settings, i.e.
        # tolerance of error, resolution of search
        # and amplification for exponential search
        # This does not matter for rationing
        # But in principle we need to initialize
        # with these values
        market = Market("market")
        # And we find the rationing, ie the amounts
        # of goods sold between pairs of agents
        # TESTING THE ABSTRACT RATIONING
        # The matching function means that all pairs will have the same priority

        def matching_agents_basic(agent_one, agent_two):
            return 1.0

        # The below function means that all pairs are allowed

        def allow_match_basic(agent_one, agent_two):
            return True
        # We find the actual trades
        rationed = market.rationing_abstract(for_rationing, matching_agents_basic, allow_match_basic)
        # Then we go through the rationing
        # and move the goods and cash appropriately
        for ration in rationed:
            #
            #             A (from)    L (to)
            # bank        loan        deposit
            # household   goods       loan
            # firm        deposit     goods
            #
            environment.new_transaction("goods", "",  ration[1].identifier, ration[0].identifier,
                                        ration[2], 0,  0, -1)
            random_bank = random.choice(environment.banks)
            environment.new_transaction("deposits", "",  ration[0].identifier, random_bank.identifier,
                                        ration[2]*price, random_bank.interest_rate_deposits,  0, -1)
            environment.new_transaction("loans", "",  random_bank.identifier, ration[1].identifier,
                                        ration[2]*price, random_bank.interest_rate_loans,  0, -1)
            # We print the action of selling to the screen
            print("%s sold %d units of goods at a price %f to %s at time %d.") % (ration[0].identifier,
                                                                                  ration[2], price, ration[1].identifier, time)
        logging.info("  goods consumed on step: %s",  time)
示例#56
0
class MarketApplication(tornado.web.Application):
    def __init__(self, market_ip, market_port, market_id=1,
                 bm_user=None, bm_pass=None, bm_port=None, seed_peers=[],
                 seed_mode=0, dev_mode=False, db_path='db/ob.db'):

        db = Obdb(db_path)

        self.transport = CryptoTransportLayer(market_ip,
                                              market_port,
                                              market_id,
                                              db,
                                              bm_user,
                                              bm_pass,
                                              bm_port,
                                              seed_mode,
                                              dev_mode)

        self.market = Market(self.transport, db)

        def post_joined():
            self.transport.dht._refreshNode()
            self.market.republish_contracts()

        peers = seed_peers if seed_mode == 0 else []
        self.transport.join_network(peers)

        Thread(target=reactor.run, args=(False,)).start()

        handlers = [
            (r"/", MainHandler),
            (r"/main", MainHandler),
            (r"/html/(.*)", OpenBazaarStaticHandler, {'path': './html'}),
            (r"/ws", WebSocketHandler,
                dict(transport=self.transport, market=self.market, db=db))
        ]

        # TODO: Move debug settings to configuration location
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

    def get_transport(self):
        return self.transport

    def setup_upnp_port_mappings(self, http_port, p2p_port):
        upnp.PortMapper.DEBUG = False
        print "Setting up UPnP Port Map Entry..."
        # TODO: Add some setting whether or not to use UPnP
        # if Settings.get(Settings.USE_UPNP_PORT_MAPPINGS):
        self.upnp_mapper = upnp.PortMapper()
        # TODO: Add some setting whether or not to clean all previous port
        # mappings left behind by us
        # if Settings.get(Settings.CLEAN_UPNP_PORT_MAPPINGS_ON_START):
        #    upnp_mapper.cleanMyMappings()

        # for now let's always clean mappings every time.
        self.upnp_mapper.clean_my_mappings()
        # result_http_port_mapping = self.upnp_mapper.add_port_mapping(http_port,
        #                                                             http_port)
        # print ("UPnP HTTP Port Map configuration done (%s -> %s) => %s" %
        #        (str(http_port), str(http_port), str(result_http_port_mapping)))

        result_tcp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port)
        print ("UPnP TCP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_tcp_p2p_mapping)))

        result_udp_p2p_mapping = self.upnp_mapper.add_port_mapping(p2p_port,
                                                                   p2p_port,
                                                                   'UDP')
        print ("UPnP UDP P2P Port Map configuration done (%s -> %s) => %s" %
               (str(p2p_port), str(p2p_port), str(result_udp_p2p_mapping)))

        # return result_http_port_mapping and \
        return result_tcp_p2p_mapping and \
               result_udp_p2p_mapping

    def cleanup_upnp_port_mapping(self):
        try:
            if self.upnp_mapper is not None:
                print "Cleaning UPnP Port Mapping -> ", \
                    self.upnp_mapper.clean_my_mappings()
        except AttributeError:
            print "[openbazaar] MarketApplication.clean_upnp_port_mapping() failed!"
            pass