Exemplo n.º 1
0
    def test_drinks_out_of_stock(self):
        self.x = Order(1)

        drink1 = item.initialise_drinks(dict())[0]
        drink1.stock = drink1.quantity_per_serving - 1

        self.x.set_drinks([drink1])

        # check that checkout out fails
        with pytest.raises(OutOfStockError) as e:
            GourmetBurgerSystem.checkout(self.x)

        assert len(e.value.msg) == 1

        assert drink1.name in e.value.msg

        # check that checking the item list fails
        item_list = [drink1]
        with pytest.raises(OutOfStockError) as e:
            GourmetBurgerSystem.check_item_list(item_list)

        assert len(e.value.msg) == 1

        assert drink1.name in e.value.msg

        assert self.x.drinks == (drink1, )
        assert self.x.price == drink1.price
Exemplo n.º 2
0
def initialize(poloModel):
    #ask for BTC market --TODO ONLY MARGIN TRADING
    btcMarket = fun.askForMarket(poloModel)
    #ask for how much BTC for order
    amountOrder = fun.askForAmount()
    #ask for trend
    trendOrder = fun.askForTrend()
    #ask for FB amount
    fbAmount = fun.askForFB()
    #ask for FB amount extra
    fbExtra = fun.askForFBExtra()
    #set variables
    treshold = Order.calculateTreshold(fbAmount, fbExtra, trendOrder)
    #ask for loss limit
    lossLimit = fun.askForLossLimit(treshold, trendOrder)
    #ask for win limit
    winLimit = fun.askForWinLimit(treshold, trendOrder)
    #ask for timeslot
    timeSlot = fun.askForTimeSlot()
    #CONFIRMATION, show summary
    orderModel = Order(btcMarket, amountOrder, trendOrder, fbAmount, fbExtra,
                       winLimit, lossLimit, timeSlot)
    if orderModel.confirmation():
        logger.info('created model for market: ' + str(btcMarket))
        logger.info('created model for amount: ' + str(amountOrder))
        logger.info('created model with trend: ' + str(trendOrder))
        logger.info('created model with treshold: ' + str(orderModel.treshold))
        logger.info('created model with winLimit: ' + str(winLimit))
        logger.info('created model with lossLimit: ' + str(lossLimit))
        #start program
        print("\nStarting program.... \n")
        return orderModel
    else:
        print("\nIncorrect information, starting again.... \n")
        return initialize(poloModel)
Exemplo n.º 3
0
    def push(self, event):
        if event.instrument == "USDBRL":
            self.dollar_price = event.price[3]
        elif event.instrument == "PETR3":
            self.petr3_price = event.price[3]

        if self.dollar_price and self.petr3_price:
            if self.orders:
                for order in self.orders:
                    self.cancel(self.id, order.id)

            self.orders = []

            buy_order = Order(event.instrument, 1,
                              self.petr3_to_pbr() - self.spread)
            sell_order = Order(event.instrument, -1,
                               self.petr3_to_pbr() + self.spread)
            self.orders.extend([buy_order, sell_order])

            return self.orders

        return []

        def fill(self, instrument, price, quantity, status):
            super().fill(instrument, price, quantity, status)
Exemplo n.º 4
0
    def push(self, event):
        price = event.price[3]
        self.prices.append(price)
        orders = []

        if len(self.prices) > self.window:
            if self.ema == 0:
                self.prev_ema = sum(
                    self.prices[-(self.window + 1):-1]) / self.window
            mult = self.sm_coef / (1 + self.window)
            self.ema = price * (mult) + self.prev_ema * (1 - mult)

        if self.ema > self.prev_ema and self.signal != 1:
            if self.signal == -1:
                orders.append(Order(event.instrument, 1, 0))
            orders.append(Order(event.instrument, 1, 0))
            self.signal = 1
        elif self.ema < self.prev_ema and self.signal != -1:
            if self.signal == 1:
                orders.append(Order(event.instrument, -1, 0))
            orders.append(Order(event.instrument, -1, 0))
            self.signal = -1

        self.prev_ema = self.ema
        self.counter += 1
        return orders
Exemplo n.º 5
0
    def get_order_book(self, ticker="BTC-EUR", level=2):
        url = "https://api.gdax.com/products/{}/book".format(ticker)

        params = {
            "level": level,
        }

        response = requests.get(url, params)
        json_response = json.loads(response.content)

        bids_received = json_response['bids']
        asks_received = json_response['asks']

        bids = []
        asks = []

        size = 10
        for i in range(size):
            bid = bids_received[i]
            amount = bid[2]

            for _ in range(amount):
                bids.append(
                    Order(str(uuid.uuid4()), ticker, float(bid[0]),
                          float(bid[1]), "Bid"))

            ask = asks_received[i]
            amount = ask[2]

            for _ in range(amount):
                asks.append(
                    Order(str(uuid.uuid4()), ticker, float(ask[0]),
                          float(ask[1]), "Ask"))

        return bids, asks
Exemplo n.º 6
0
def test_trade():
    quantity = 10
    price = 10
    aggressive_order = Order(1, ORDER_BUY_SIDE, 0, price, 1)
    resting_order = Order(2, ORDER_SELL_SIDE, 1, price, 2)
    trade = Trade(quantity, price, aggressive_order, resting_order)
    assert trade.price == price
    assert trade.quantity == quantity
    assert trade.aggressive_fill == FILL_TYPE_FULL
    assert trade.aggressive_quantity == 0
    assert trade.aggressive_id == 1
    assert trade.resting_fill == FILL_TYPE_PARTIAL
    assert trade.resting_quantity == 1
    assert trade.resting_id == 2
    aggressive_order = Order(1, ORDER_BUY_SIDE, 1, price, 1)
    resting_order = Order(2, ORDER_SELL_SIDE, 0, price, 2)
    trade = Trade(quantity, price, aggressive_order, resting_order)
    assert trade.price == price
    assert trade.quantity == quantity
    assert trade.aggressive_fill == FILL_TYPE_PARTIAL
    assert trade.aggressive_quantity == 1
    assert trade.aggressive_id == 1
    assert trade.resting_fill == FILL_TYPE_FULL
    assert trade.resting_quantity == 0
    assert trade.resting_id == 2
Exemplo n.º 7
0
    def test_add_order():
        order = Order(
            region='eu',
            server='Classic - Golemagg',
            faction='Alliance',
            stock=99999,
            currency='USD',
            description='test',
            min_unit_per_order=99999,
            duration=3,
            delivery_option='Face to face trade, Mail, Auction House',
            online_hrs=2,
            offline_hrs=7
        )

        order_2 = Order(
            region='eu',
            server='Classic - Golemagg',
            faction='Horde',
            stock=8888,
            currency='USD',
            description='test 2',
            min_unit_per_order=8888,
            duration=3,
            delivery_option='Face to face trade, Mail, Auction House',
            online_hrs=4,
            offline_hrs=10
        )

        bot.add_order(order_2, price=1.5)
Exemplo n.º 8
0
    def push(self, event):
        orders = []
        print('Event: {0} {1}@{2}'.format(event.instrument, event.quantity,
                                          event.price))

        if event.instrument == "PETR3":
            self.petr3 = event.price[3]

        if event.instrument == "USDBRL":
            self.usdbrl = event.price[3]

        if self.petr3 and self.usdbrl:
            self.pbr = self.calculate_pbr(self.petr3, self.usdbrl)

            #em que valor comprar e vender

            entrar = self.pbr - self.margem
            sair = self.pbr + self.margem

            #cancela
            if self.orders:
                for orderid in self.orders:
                    self.cancel(self.id, orderid)

            #manda duas novas ordens
            self.orders = []
            orders.append(Order("PBR", 1, entrar))
            orders.append(Order("PBR", -1, sair))
            for order in orders:
                self.orders.append(order.id)

            return orders
        return []
Exemplo n.º 9
0
def insertOrder(line):
    mylist = line.split(",")
    print(mylist)
    #product_id,product_name,category,price,quantity
    order = Order(mylist[0].strip(),mylist[1].strip(),mylist[2].strip())
    #print(cust)
    order.insert()
Exemplo n.º 10
0
    def calculate_total(self, order: Order) -> float:
        if order is None:
            return 0

        size_price = 0
        sizes = self.data.get_pizza_manager().get_pizza_sizes()
        for size in sizes:
            if size["Size"].lower() == order.get_pizza_size().lower():
                size_price = size["Price"]
                break

        type_price = 0
        types = self.data.get_pizza_manager().get_pizza_types()
        for type in types:
            if type["Type"].lower() == order.get_pizza_type().lower():
                type_price = type["Price"]
                break

        topping_price = 0
        toppings = self.data.get_pizza_manager().get_pizza_toppings()
        for order_topping in order.get_toppings():
            for topping in toppings:
                if topping["Topping"].lower() == order_topping.lower():
                    topping_price += topping["Price"]
                    break

        drink_price = 0
        drinks = self.data.get_pizza_manager().get_drinks()
        for drink in drinks:
            if drink["Drink"].lower() == order.get_drink().lower():
                drink_price = drink["Price"]
                break

        return size_price + type_price + topping_price + drink_price
Exemplo n.º 11
0
    def negative_tests(self):
        # invalid temperature
        order2 = {
            "id": "0ff534a7-a7c4-48ad-b6ec-7632e36af950",
            "name": "Cheese Pizza",
            "temp": "very hot",
            "shelfLife": 300,
            "decayRate": 0.45
        }
        try:
            new_order = Order(order2['id'], order2['name'], order2['temp'],
                              order2['shelfLife'], order2['decayRate'])
            self.assertIsNone(new_order)
        except Exception as ex:
            self.assertIsInstance(ex, ValueError)

        # invalid order id
        order2 = {
            "id": "0ff534a7-a7c4",
            "name": "Cheese Pizza",
            "temp": "very hot",
            "shelfLife": 300,
            "decayRate": 0.45
        }
        try:
            new_order = Order(order2['id'], order2['name'], order2['temp'],
                              order2['shelfLife'], order2['decayRate'])
            self.assertIsNone(new_order)
        except Exception as ex:
            self.assertIsInstance(ex, ValueError)

        # invalid shelfLife
        order2 = {
            "id": "0ff534a7-a7c4-48ad-b6ec-7632e36af950",
            "name": "Cheese Pizza",
            "temp": "hot",
            "shelfLife": 0,
            "decayRate": 0.45
        }
        try:
            new_order = Order(order2['id'], order2['name'], order2['temp'],
                              order2['shelfLife'], order2['decayRate'])
            self.assertIsNone(new_order)
        except Exception as ex:
            self.assertIsInstance(ex, ValueError)

        # invalid decayRate
        order2 = {
            "id": "0ff534a7-a7c4-48ad-b6ec-7632e36af950",
            "name": "Cheese Pizza",
            "temp": "hot",
            "shelfLife": 300,
            "decayRate": 1.15
        }
        try:
            new_order = Order(order2['id'], order2['name'], order2['temp'],
                              order2['shelfLife'], order2['decayRate'])
            self.assertIsNone(new_order)
        except Exception as ex:
            self.assertIsInstance(ex, ValueError)
Exemplo n.º 12
0
 def __init__(self):
     self.inventory = None
     self.order = Order()
     self.start_point = (0, 0)
     print("Importing inventory...")
     self.importInventory('qvBox-warehouse-data-s19-v01.txt')
     print("Inventory imported successfully!")
Exemplo n.º 13
0
def take_order(menu):
    divider = '=' * 60
    order = Order()
    last_item = None
    while True:
        clear_screen()
        print divider
        if last_item:
            print 'Added %s to your order!' % last_item
        print 'Order total: $%3.2f' % order.get_total()
        print divider
        print 'Below is our menu.  Enter an item number to order it,'
        print 'or just hit enter to complete your order.'
        print divider
        menu.print_menu()
        product_number = raw_input('Product number: ')
        if product_number == '':
            break
        product = menu.find_product(int(product_number))
        if not product:
            continue
        quantity = int(raw_input('Quantity: '))
        order.add_item(product, quantity)
        last_item = product.name
    return order
Exemplo n.º 14
0
 def get_depth(self, base, alt):
     book = {"bids": [], "asks": []}
     pair0 = (base, alt)
     pair, swapped = self.get_validated_pair(pair0)
     newbase, newalt = pair
     slug = newbase + "_" + newalt
     marketdata = self.unauthenticated_request('markets/data/')
     depth = marketdata['markets'][slug]['marketdepth']
     if swapped:
         for bid in depth['bids']:
             o = Order(float(bid['r']), float(bid['q']))
             ask = get_swapped_order(o)
             book['asks'].append(ask)
         for ask in depth['asks']:
             o = Order(float(ask['r']), float(ask['q']))
             bid = get_swapped_order(o)
             book['bids'].append(o)
     else:
         for bid in depth['bids']:
             o = Order(float(bid['r']), float(bid['q']))
             book['bids'].append(o)
         for ask in depth['asks']:
             o = Order(float(ask['r']), float(ask['q']))
             book['asks'].append(o)
     return book
Exemplo n.º 15
0
def test_delete_item(inventory_fixture, ingredient_cost_fixture):
    order1 = Order(inventory_fixture, ingredient_cost_fixture)
    assert(isinstance(order1, Order))

    orig_white_bun = inventory_fixture["white"]
    orig_beef = inventory_fixture["beef"]
    orig_cheese = inventory_fixture["cheese"]

    burg1 = order1.Create_Item("Burger")
    burg1.Bun_Type = "white"
    burg1.Add_Bun()
    burg1.Add_Bun()
    burg1.Patty_Type = "beef"
    burg1.Add_Patty()
    burg1.Add_Other("cheese")

    assert(inventory_fixture["white"] == (orig_white_bun - 2))
    assert(inventory_fixture["beef"] == (orig_beef - 1))
    assert(inventory_fixture["cheese"] == (orig_cheese - 1))

    order1.Delete_Item(burg1)

    assert(inventory_fixture["white"] == (orig_white_bun))
    assert(inventory_fixture["beef"] == (orig_beef))
    assert(inventory_fixture["cheese"] == (orig_cheese))
Exemplo n.º 16
0
    def init_order(self):
        self.insertPlain("正在点击初始化按钮...")
        if self.username is None:
            cookies = self.web.get_cookie()
            pos = cookies.find("lid=")
            if pos==-1:
                self.web.page().runJavaScript("window.alert('请先登录')")
                return;
            else:
                cookies =cookies[pos+4:]
                username =cookies.split(";")[0]
                self.username = unquote(username.strip(),"utf-8")
                LoggerUtil.write_file_log("淘宝拍单用户[%s]登录成功"%self.username)
                self.order = Order(self.username)

        self.order.pop()
        if self.order.current_order is None:
            self.insertPlain("暂无数据")
            self.web.page().runJavaScript("window.alert('暂无数据')")
            return;
        LoggerUtil.write_file_log("当前订单商品信息为:")
        info = json.dumps(self.order.current_order, ensure_ascii=False, indent=2)
        LoggerUtil.write_file_log(info)
        self.insertPlain("当前订单商品贝贝订单号为:%s" % self.order.current_order_id)
        self.insertPlain("当前订单商品链接为:%s" % self.order.current_url)
        self.insertPlain("当前订单商品skuId:%s"%self.order.sku_id)
        self.btn_add_adress.setEnabled(True)
        # self.web.load(QUrl(address_url))
        self.btn_add_adress.click()
Exemplo n.º 17
0
 def get_depth(self, base, alt):
     pair0 = (base, alt)
     pair, swapped = self.get_validated_pair(pair0)
     newbase, newalt = pair
     marketid = self.get_market_id(newbase, newalt)
     data = self.api.depth(marketid)['return']
     book = {"bids": [], "asks": []}
     if swapped:
         for bid in data['buy']:
             # find out
             o = Order(float(bid[0]), float(bid[1]))
             ask = get_swapped_order(o)
             book['asks'].append(ask)
         for ask in data['sell']:
             o = Order(float(ask[0]), float(ask[1]))
             bid = get_swapped_order(o)
             book['bids'].append(bid)
     else:
         for bid in data['buy']:
             o = Order(float(bid[0]), float(bid[1]))
             book['bids'].append(o)
         for ask in data['sell']:
             o = Order(float(ask[0]), float(ask[1]))
             book['asks'].append(o)
     return book
Exemplo n.º 18
0
    def __init__(self, config_file):
        with open(config_file, 'r') as f:
            self.rows, self.cols, self.num_drones, self.num_turns, self.max_payload = get_line(f.readline())
            self.num_product_types = get_line_first(f.readline())
            weights = get_line(f.readline())
            self.products = []
            for idx in range(self.num_product_types):
                self.products.append(Product(idx, weights[idx]))

            self.num_warehouses = get_line_first(f.readline())
            self.warehouses = []
            for warehouse_idx in range(self.num_warehouses):
                loc = tuple(get_line(f.readline()))
                warehouse = Warehouse(warehouse_idx, loc)
                for prod_idx, prod_quant in enumerate(get_line(f.readline())):
                    prod = self.products[prod_idx]
                    warehouse.add_product(prod, prod_quant)
                self.warehouses.append(warehouse)

            self.num_orders = get_line_first(f.readline())
            self.orders = []
            for order_idx in range(self.num_orders):
                loc = tuple(get_line(f.readline()))
                order = Order(order_idx, loc)
                f.readline() #just skip cause we know it from the next line
                for prod_id in get_line(f.readline()):
                    prod = self.products[prod_id]
                    order.add_product(prod)
                self.orders.append(order)

            self.drones = [Drone(drone_idx, self.warehouses[0].location, self.max_payload) \
                           for drone_idx in range(self.num_drones)]
Exemplo n.º 19
0
    def push(self, event):
        orders = []
        if random.randint(1, 5000) == 1:
            side = random.choice([-1, 1])
            if side != self.side:
                orders.append(Order(event.instrument, -self.side, 0))
                orders.append(Order(event.instrument, side, 0))

                self.price = event.price

                gain = Order(event.instrument, -side,
                             event.price + side * 0.10)

                self.gain = gain.id
                orders.append(gain)

        if self.side == 1 and event.price <= self.price - 0.05:
            orders.append(Order(event.instrument, -self.side, 0))
            self.cancel(self.id, self.gain)
        elif self.side == -1 and event.price >= self.price + 0.05:
            orders.append(Order(event.instrument, -self.side, 0))
            self.cancel(self.id, self.gain)

        if len(orders) > 0:
            for order in orders:
                print(order.print())

        return orders
Exemplo n.º 20
0
    def test_creation_ordering_success(self):

        ingredients = item.initialise_ingredients(dict())
        bun = item.initialise_buns(dict())[0]

        self.x = Order(1)

        for ingredient in ingredients:
            ingredient.increment(ingredient.quantity_per_serving * 2)

        bun.increment(bun.quantity_per_serving * 2)

        burger = Burger(ingredients, [bun] * 2)

        wrap = Wrap(ingredients)

        self.x.set_wraps([wrap])
        self.x.set_burgers([burger])

        GourmetBurgerSystem.checkout(self.x)

        assert self.x.status == "being prepared"

        for ingredient in ingredients:
            assert ingredient.stock == 0

        assert bun.stock == 0

        assert self.x.price == wrap.price + burger.price
Exemplo n.º 21
0
 def __init__(self):
     params_list = {
         'token': 'ZhZIC5HluW3vVdlO',
         'begin_date': '2014-01-01',
         'end_date': '2015-10-01'
     }
     url = "union.55haitao.com"
     suffix = "/union.php?mod=api_cashback"
     data = GetResponse(params_list, url, suffix)
     print data
     decodejson = json.loads(data)
     if decodejson["status"]["code"] == 0:
         orders_data = decodejson["data"]
         for order_data in orders_data:
             print order_data
             order = Order()
             print md5('55haitao' + order_data["order_id"])
             order.InsertDb(
                 md5('55haitao' + order_data["order_id"]),
                 order_data["tagcode"], 1, order_data["store_id"],
                 order_data["store_name"], order_data["sale_amount"],
                 order_data["cashback"], order_data["order_time"],
                 order_data["report_time"], order_data["valid_time"],
                 order_data["currency_type"], order_data["status"])
             order.ShowDb()
     else:
         print decodejson["status"]
Exemplo n.º 22
0
    def push(self, event):
        if event.type == Event.TRADE:
            price = event.price
            self.prices.append(price)
            orders = []
            if len(self.prices) == self.size:
                std = np.array(self.prices).std()
                mavg = sum(self.prices) / self.size

                if price >= mavg + std:
                    if self.signal == 1:
                        orders.append(Order(event.instrument, -100, 0))
                        orders.append(Order(event.instrument, -100, 0))
                    if self.signal == 0:
                        orders.append(Order(event.instrument, -100, 0))
                    self.signal = -1
                elif price <= mavg - std:
                    if self.signal == -1:
                        orders.append(Order(event.instrument, 200, 0))
                    if self.signal == 0:
                        orders.append(Order(event.instrument, 100, 0))
                    self.signal = 1

                del self.prices[0]

            return orders
        return []
Exemplo n.º 23
0
def test_default_wrap(inventory_fixture, ingredient_cost_fixture):
    order1 = Order(inventory_fixture, ingredient_cost_fixture)
    assert(isinstance(order1, Order))

    orig_pita = inventory_fixture["pita"]
    orig_pork = inventory_fixture["pork"]
    orig_cheese = inventory_fixture["cheese"]
    orig_tortilla = inventory_fixture["tortilla"]
    orig_tuna = inventory_fixture["tuna"]
    orig_lettuce = inventory_fixture["lettuce"]
    orig_onion = inventory_fixture["onion"]
    orig_tomato = inventory_fixture["tomato"]
    orig_avocado = inventory_fixture["avocado"]

    def_wrap1 = order1.Create_Item("Default Wrap")
    order1.Add_To_Order(def_wrap1)
    assert(def_wrap1 in order1.Items)
    #assert(order1.Calculate_Cost() == 8)

    

    assert(inventory_fixture["pita"] == (orig_pita - 1))
    assert(inventory_fixture["pork"] == (orig_pork - 1))
    assert(inventory_fixture["cheese"] == (orig_cheese))
    assert(inventory_fixture["tortilla"] == (orig_tortilla))
    assert(inventory_fixture["tuna"] == (orig_tuna))
    assert(inventory_fixture["lettuce"] == (orig_lettuce - 1))
    assert(inventory_fixture["onion"] == (orig_onion))
    assert(inventory_fixture["tomato"] == (orig_tomato))
    assert(inventory_fixture["avocado"] == (orig_avocado))

    assert(order1.ID == None)
    assert(order1.Status == None)
Exemplo n.º 24
0
def basket_list(request):
    context = get_default_context(request)
    basket = Basket(request.session)
    basket_items = basket.get_list()
    
    if request.method == 'GET':
        # Showing basket to user
        context['basket'] = basket_items
        context['form'] = OrderForm()
    else:
        # Checking and posting the order
        form = OrderForm(request.POST)
        if form.is_valid():
            # Valid order
            # Saving to the model
            
            order = Order()
            form_cd  = form.cleaned_data
            summary_info = basket.get_summary_info()
            context['fields'] = order.send_mail(form_cd, basket_items, summary_info, request.session)
            basket.clear()
            return render_to_response('basket/good.html', context)
        else:
            # Invalid order: repeating form
            context['basket'] = basket_items
            context['form'] = form

    return render_to_response('basket/index.html', context)
Exemplo n.º 25
0
    def push(self, event):
        self.prices.append(event.price)
        self.shorttermprices.append(event.price)
        orders = []
        if event.type == Event.TRADE:
            precos = np.array(list(self.shorttermprices))
            tinyrollingmean = np.mean(precos)
            precos = np.array(list(self.prices))
            rollingmean = np.mean(precos)
            std = np.std(precos)
            upperband = rollingmean + std*2
            lowerband = rollingmean - std*2

            if tinyrollingmean > upperband:
                prob = 100
            elif tinyrollingmean < lowerband:
                prob = 0
            else:
                prob = ((tinyrollingmean - lowerband)/(upperband - lowerband))*100
            
            if ((10 > prob)):
                if (prob == 0):
                    orders.append(Order(event.instrument, 1, 0))
                orders.append(Order(event.instrument, 1, 0))

            if ((70 < prob)):
                if (prob == 1):
                    orders.append(Order(event.instrument, -1, 0))
                orders.append(Order(event.instrument, -1, 0))

        if len(orders) > 0:
            for order in orders:
                print(order.print())

        return orders
Exemplo n.º 26
0
def test_default_burger(inventory_fixture, ingredient_cost_fixture):
    order1 = Order(inventory_fixture, ingredient_cost_fixture)
    assert(isinstance(order1, Order))

    orig_white_bun = inventory_fixture["white"]
    orig_beef = inventory_fixture["beef"]
    orig_cheese = inventory_fixture["cheese"]
    orig_tortilla = inventory_fixture["tortilla"]
    orig_tuna = inventory_fixture["tuna"]
    orig_lettuce = inventory_fixture["lettuce"]
    orig_onion = inventory_fixture["onion"]
    orig_tomato = inventory_fixture["tomato"]
    orig_avocado = inventory_fixture["avocado"]

    def_burg1 = order1.Create_Item("Default Burger")
    order1.Add_To_Order(def_burg1)
    assert(def_burg1 in order1.Items)
    assert(order1.Calculate_Cost() == 8)

    

    assert(inventory_fixture["white"] == (orig_white_bun - 2))
    assert(inventory_fixture["beef"] == (orig_beef - 1))
    assert(inventory_fixture["cheese"] == (orig_cheese))
    assert(inventory_fixture["tortilla"] == (orig_tortilla))
    assert(inventory_fixture["tuna"] == (orig_tuna))
    assert(inventory_fixture["lettuce"] == (orig_lettuce - 1))
    assert(inventory_fixture["onion"] == (orig_onion))
    assert(inventory_fixture["tomato"] == (orig_tomato))
    assert(inventory_fixture["avocado"] == (orig_avocado))

    assert(order1.ID == None)
    assert(order1.Status == None)
Exemplo n.º 27
0
    def new_order(self, id):
        new_order = Order()

        new_order.set_ID(id)
        self._orders.append(new_order)

        return new_order
Exemplo n.º 28
0
async def status(ctx, order_id):
    start_time = monotonic()
    print("Check order id {}".format(order_id))
    if not order_id.isdigit():
        await Misc.send_error(
            ctx, ':warning: Order ID must only consist of numbers',
            'Example: !status 12345')
        return
    await ctx.trigger_typing()
    response = ytc.get_order(order_id)
    if 'code' in response:
        if response['code'] == 'woocommerce_rest_shop_order_invalid_id':
            await Misc.send_error(
                ctx, ':warning: No order exists with the given ID')
        else:
            await Misc.send_error(
                ctx,
                ':warning: Unknown error occurred, please ping a staff member for assistance',
                response['code'])
        return
    notes = ytc.get_order_notes(order_id)
    order = Order(response, notes)
    embed = order.create_embed()
    await ctx.send(embed=embed)
    if order.status in ['processing', 'completed']:
        await add_patron_role(ctx, order)
    end_time = monotonic()
    print('ok, took {:.2f} s'.format(end_time - start_time))
    print('-----')
    def get_depth(self, alt, base):
        book = {'bids': [], 'asks': []}

        pair, swapped = self.get_validated_pair((alt, base))
        a, b = pair

        slug = a + "/" + b

        #print ("slug to fetch order book: %s swaped %s" % (slug, swapped))

        data = self.exchange.fetch_order_book(slug)

        if swapped:
            for ask in data['asks']:
                o = Order(float(ask[0]), float(ask[1]))
                bid = get_swapped_order(o)
                book['bids'].append(bid)
            for bid in data['bids']:
                o = Order(float(bid[0]), float(bid[1]))
                ask = get_swapped_order(o)
                book['asks'].append(ask)
        else:
            for bid in data['bids']:
                o = Order(float(bid[0]), float(bid[1]))
                book['bids'].append(o)
            for ask in data['asks']:
                o = Order(float(ask[0]), float(ask[1]))
                book['asks'].append(o)

        return book
Exemplo n.º 30
0
 def register(self, order: Order) -> str:
     """Registers a valid order in the live orders board, returning the id assigned to the new order"""
     if not order.is_valid():
         raise ValueError('Cannot register an invalid order!')
     order.id = uuid.uuid1()
     self.orders.append(order)
     return order.id
Exemplo n.º 31
0
 def __init__(self):
     self.read_order = Order()
     self.read_product = Product()
     self.text = ''
     self.account_name = ''
     self.mail = None
     self.df = None
Exemplo n.º 32
0
 def test_start_next_food(self):
     price = 3000
     making_time = 60
     var_truck = FoodTruck(price, making_time)
     next_order = Order(10)
     var_truck.start_next_food(next_order)
     self.assertEqual(next_order, var_truck.current_order)
     self.assertEqual(making_time*next_order.get_qty(), var_truck.time_remaining)
Exemplo n.º 33
0
 def run1(self):
     for i in range(30,len(self.__dt)): 
         index = self.__dt.index.values[i]
         prv_idx = self.__dt.index.values[i-1]
         if self.__dt.IN_T[index]==1 and self.__dt.IN_T[prv_idx]==0:
             od = Order()
             od.setOrder(i,self.__dt.loc[index])
             self.__oo.append(od)
         pass     
Exemplo n.º 34
0
    def test_order_filled_if_enough_in_warehouse(self, mock_wh):
        order = Order(TALISKER, 50)

        mock_wh.add(TALISKER, 50)

        order.fill(mock_wh)

        self.assertTrue(order.is_filled())
        mock_wh.get_inventory.assert_called_once_with(TALISKER)
        mock_wh.remove.assert_called_once_with(TALISKER, 50)
def get_order_by_order_id(sql_connection, order_id):
    sql_cursor = sql_connection.cursor()
    sql_cursor.execute(GET_ORDERS_BY_ORDER_ID, (order_id,))
    result = sql_cursor.fetchone()
    sql_cursor.close()
    if result:
        order = Order(result[0], result[1], result[2], result[3],
                      result[5], result[4], result[6], [])
        order.order_details = get_order_details_by_order_id(sql_connection, order.id)
        return order
    raise OrderIdNotFoundException("order_id: %s, not found" % order_id)
def get_orders_by_customer_name(sql_connection, customer):
    sql_cursor = sql_connection.cursor()
    query = GET_ORDERS_BY_CUSTOMER_NAME.format(customer=customer)
    sql_cursor.execute(query)
    results = sql_cursor.fetchall()
    sql_cursor.close()
    orders = []
    for result in results:
        order = Order(result[0], result[1], result[2], result[3],
                      result[5], result[4], result[6], [])
        order.order_details = get_order_details_by_order_id(sql_connection, order.id)
        orders.append(order)

    return orders
Exemplo n.º 37
0
 def __init__(self, scope, q, alpha, reward, discount, quotes, bankroll, 
                                                                   log=None):
     self.logger = log
     self.actions = ACTIONS # BUY, SELL, DO_NOTHING
     Indicators.__init__(self, log)
     Learning.__init__(self, q, alpha, reward, discount, self.state, \
                                                                self.actions)
     Order.__init__(self, scope, bankroll, log)
     self.num_trades = 0
     self.performance = 1
     self.volume = max(self.performance, 1)
     self.logger = log
     self.status = {'status':'','action':''}
     self.quotes = quotes
     self.states = None
Exemplo n.º 38
0
    def test_proper_order(self):

        class FakeLeg(object):
            def __init__(self):
                self.index = None

            def toDict(self):
                return {'phony': 'leg'}

        legs = [FakeLeg(), FakeLeg(), FakeLeg()]

        order = Order(
            price_type='limit',
            time_in_force='good_till_cancel',
            price='72.50',
            underlying_stock_symbol='COP',
            legs=legs,
            allOrNone=False,
            order_subtype='single',
        )

        expected_data = {
            'm_order_id': 1,
            'price_type': 'limit',
            'time_in_force': 'good_till_cancel',
            'price': '72.50',
            'underlying_stock_symbol': 'COP',
            'source': 'API',
            'client_id': order.data['client_id'],
            'preferred_destination': 'BEST',
            'legs': legs,
            'allOrNone': False,
            'order_subtype': 'spread',
            'order_type': 'regular'
        }
        self.assertEqual(order.data, expected_data)

        expected_data['legs'] = [
            { 'index': 0, 'phony': 'leg' },
            { 'index': 1, 'phony': 'leg' },
            { 'index': 2, 'phony': 'leg' },
        ]
        self.assertEqual(order.toDict(), expected_data)

        order.modify(1337)
        expected_data['modify_order'] = True
        expected_data['order_id'] = 1337
        self.assertEqual(order.toDict(), expected_data)
Exemplo n.º 39
0
    def run(self):
        for i in range(30,len(self.__dt)):        
            #check for buy postion
            if self.__dt.loc[i].close >= self.__dt.loc[i-1].m20 and len(self.__oo)==0:
                od = Order()
                od.setOrder(i,self.__dt.loc[i])
                self.__oo.append(od)

            #check for short position
            if len(self.__oo)>0:            
                if self.checkSell(self.__oo[0],self.__dt.loc[i]) == True:
                    od = self.__oo.pop(0)
                    od.closeOrder(i,self.__dt.loc[i])
                    self.__co.append(od)
        
            #calculate daily margin
            margin = 0.0
            for o in self.__oo:
                margin += self.__dt.loc[i].close-o.getPrice()
        
            for o in self.__co:
                margin += o.getMargin()
        
            self.__dt.loc[i,['margin']]=1000.0+margin

        #end for
     
        #handle last order if any
        if len(self.__oo)>0:
            od = self.__oo.pop(0)
            od.closeOrder(i,self.__dt.loc[len(self.__dt)-1])
            self.__co.append(od)
Exemplo n.º 40
0
def main():
    ships = Ship.parse_input_file('menetrend.txt')
    orders = Order.parse_input_file('rakomany.txt')
    docks_by_name = utility.create_docks_by_name(ships, orders)
    money, commands = game_loop(docks_by_name, ships)
    print money
    utility.order_commands(commands)
    with open('output.txt', 'w') as output_file:
        for command in commands:
            output_file.write(command.get_string_line() + '\n')
Exemplo n.º 41
0
    def test_order_is_filled_if_enough_in_warehouse(self):
        # Create the Order as usual
        order = Order(TALISKER, 50)

        # Create the mock warehouse object in record mode
        mocker = mox.Mox()
        warehouse = mocker.CreateMockAnything()

        # Record the sequence of actions expected from the Order object
        warehouse.get_inventory(TALISKER).AndReturn(50)
        warehouse.remove(TALISKER, 50)

        # Put all mock objects in replay mode
        mocker.ReplayAll()

        # Exercise the Order object
        order.fill(warehouse)

        # Verify that the order is filled and that the warehouse saw
        # the correct behavior
        self.assertTrue(order.is_filled())
        mocker.VerifyAll()
Exemplo n.º 42
0
 def handle_beacon(self, nodes):
     """
     This function will go through the nodes, instantiating the appropriate module object and attempt
     to beacon out in succession to the supplied Nodes. It will fail our it no nodes are available.
     """
     # 
     # nodes example:
     # list of tuples, where each tuples first value is a string of the beacon type and second value is a dictionary of arguments
     # [('http_get',{'node':'192.168.2.2','port':'80','path':'/index.html','timeout':'10'})]
     #
     
     print config.BEAC_PROMPT + " beaconing..."
     
     try:
         
         success = False
         # Should I randomize the order of nodes? this is a potential behavior that could be defined.
         for node in nodes:
             beacon_type = node[config.BEACON_TYPE_IND]
             params = node[config.PARAMS_IND]
             
             ip = params.get(config.NODE_IP_KEY)
             port = params.get(config.NODE_PORT_KEY)
     
             beaconer_class = self.beacon_map.get(beacon_type) # get this from the beacon map based on beacon type
             beaconer = beaconer_class() # instantiate the object
             try:
                 success, response = beaconer.beacon(params)
             except Exception, e:
                 print "%s Error connecting to %s:%s" % (config.BEAC_PROMPT, ip, port)
                 success = False
             
             # generate a 'bean' called Orders to act as a sort of 'cookie' between handlers
             if success:
                 print "%s Successfully retrieved data from %s:%s" % (config.BEAC_PROMPT, ip, port)
                 order = Order()
                 order.node = node
                 order.node_ip = ip
                 order.node_port = port
                 order.node_type = beacon_type
                 order.node_params = params
                 order.raw_response = response
                 
                 return (success, order)
             else:
                 # Will not all failures raise an exception? Perahsp this should be forced implementation by all Beaconers?
                 # print "%s Failed to retrieve data from %s:%s" % (BEAC_PROMPT, ip, port)
                 # Should I pause here or just continue?
                 pass
             
         # What do I do if none of the nodes worked?
         return (False, None)
Exemplo n.º 43
0
class OrderTest(unittest.TestCase):
    def setUp(self):
        self.timestamp = 48
        self.var_order = Order(self.timestamp)

    def tearDown(self):
        del self.timestamp
        del self.var_order

    def test___init__(self):
        self.assertEqual(self.timestamp, self.var_order.order_time)
        self.assertGreaterEqual(self.var_order.qty, 1)
        self.assertLessEqual(self.var_order.qty, 5)

    def test_get_order_time(self):
        self.assertEqual(self.timestamp, self.var_order.get_order_time())

    def test_get_qty(self):
        self.assertGreaterEqual(self.var_order.get_qty(), 1)
        self.assertLessEqual(self.var_order.get_qty(), 5)

    def test_wait_time(self):
        current_time = 60
        self.assertEqual(12, self.var_order.wait_time(current_time))
Exemplo n.º 44
0
def unlink(user_id, password, model, odoo_id):
    _check_user(user_id, password)
    if model not in MODELS_CLASS.keys():
        raise Fault("unknown_model", "Reference model does not exist!")
    mod_class = MODELS_CLASS[model]
    try:
        rec = mod_class.get(mod_class.odoo_id == odoo_id)
    except mod_class.DoesNotExist:
        pass
    else:
        if model == "customer":
            for invoice in Invoice.select().where(Invoice.partner_id == rec.id):
                invoice.delete_instance()
            for rma in Rma.select().where(Rma.partner_id == rec.id):
                for rma_product in RmaProduct.select().where(
                        RmaProduct.id_rma == rma.id):
                    rma_product.delete_instance()
                rma.delete_instance()
        elif model == 'product':
            for rma_product in RmaProduct.select().where(
                    RmaProduct.product_id == rec.id):
                rma_product.delete_instance()
        elif model == 'rma':
            for rma_product in RmaProduct.select().where(
                    RmaProduct.id_rma == rec.id):
                rma_product.delete_instance()
        elif model == 'rmastatus':
            for rma_product in RmaProduct.select().where(
                    RmaProduct.status_id == rec.id):
                rma_product.delete_instance()
        elif model == 'rmastage':
            for rma in Rma.select().where(
                    Rma.stage_id == rec.id):
                rma.delete_instance()
        elif model == 'customertagcustomerrel':
            for customertagcustomerrel in CustomerTagCustomerRel.select().where(
                    CustomerTagCustomerRel.odoo_id == rec.odoo_id):
                customertagcustomerrel.delete_instance()
        elif model == 'producttagproductrel':
            for producttagproductrel in ProductTagProductRel.select().where(
                    ProductTagProductRel.odoo_id == rec.odoo_id):
                producttagproductrel.delete_instance()
        elif model == 'order':
            for order in Order.select().where(
                Order.partner_id == rec.id):
                order.delete_instance()
        rec.delete_instance()
    return True
Exemplo n.º 45
0
def assemble_order(rein, document):
    """
    Take one document and build the entire order based on it. The idea here is that one Job ID should
    allow us to query each available server for each document type that is associated with it, then
    filter out bogus shit by focusing on who's signed correct stuff. This kind of command can also
    look for attempted changes in foundational info like participants public keys and redeem scripts.
    If this works well, we can reduce how much data is required at each stage. Finally, we should
    be able to serialize a job from end to end so it can be easily reviewed by a mediator.
    """
    parsed = parse_document(document.contents)
    if 'Job ID' not in parsed:
        return 0
    job_id = parsed['Job ID']
    urls = get_urls(rein)
    documents = []
    if job_id:
        for url in urls:
            res = get_documents_by_job_id(rein, url, job_id)
            if res:
                documents += res
        order_id = Order.get_order_id(rein, job_id)
        if not order_id:
            o = Order(job_id, testnet=rein.testnet)
            rein.session.add(o)        
            rein.session.commit()

    for document in documents:
        doc_type = get_document_type(document)
        if not doc_type:
            rein.log.info('doc_type not detected')
            continue
        doc_hash = calc_hash(document)
        d = rein.session.query(Document).filter(Document.doc_hash == doc_hash).first()
        if d:
            d.set_order_id(order_id)
        else:
            new_document = Document(rein, doc_type, document, order_id, 'external', source_key=None, sig_verified=True, testnet=rein.testnet)
            rein.session.add(new_document)

        rein.session.commit()

    return len(documents)
Exemplo n.º 46
0
 def test_checkProductQuantityIsSet(self):
     o = Order(" 100 P156923    SPORTING856     1012399")
     self.assertEqual(o.create()._quantity, 856)
Exemplo n.º 47
0
 def setUp(self):
     self.timestamp = 48
     self.var_order = Order(self.timestamp)
Exemplo n.º 48
0
def read_ops(filename):
    """Read data from given file to create Orders."""
    try:
        with open(filename, newline="") as file:
            # stores all the read lines
            reader = csv.DictReader(file, fieldnames=FIELDS)
            # stores all the skipped lines
            skipped_lines = []
            # connect to database
            db.connect()

            # init successful quote and order counter
            quotes_made = 0
            orders_made = 0
            # total lines
            total_lines = 0
            for row in reader:
                # update total lines
                total_lines += 1
                # skip if empty row
                if row["cliente"] == "" or row["cliente"] == "CLIENTE":
                    skipped_lines.append(row)
                else:
                    # materials list
                    materials_list = []
                    # finishings list
                    finishings_list = []
                    # printing sides and colors
                    sides = 0
                    colors_front = 0
                    colors_back = 0
                    # loop through items
                    for key, val in row.items():
                        # check materials
                        if key in MATERIALS.keys():
                            # print("### material ### ", end='')
                            if val == "X":
                                materials_list.append(MATERIALS[key])
                                if key == "impresion_t":
                                    sides = 1
                                    colors_front = 4
                                elif key == "impresion_tr":
                                    sides = 2
                                    colors_front = 4
                                    colors_back = 4
                        # check finishings
                        elif key in FINISHINGS.keys():
                            # print("%%% finishing %%% ", end='')
                            if val == "X":
                                finishings_list.append(FINISHINGS[key])

                        elif key == "cliente":
                            logging.debug("=== cliente === {}: {}".format(key, val))
                        elif key == "orden":
                            orden = val
                            logging.debug("=== OP === {}: {}".format(key, orden))
                        elif key == "cantidad":
                            num_copies = val.replace(",", "")
                            num_copies = int(num_copies)
                            logging.debug("=== Num copies === {}: {}".format(key, num_copies))
                        elif key == "material":
                            product = val
                            logging.debug("=== Pdct Type === {}: {}".format(key, product))
                        elif key == "fecha_entrega":
                            # date comes in format: dd/mm/yyyy
                            day, month, year = val.split("/")
                            # convert to integers
                            day = int(day)
                            month = int(month)
                            year = int(year)
                            # create date instance
                            due_date = datetime.date(year, month, day)
                            logging.debug("=== Due Date === {}: {}".format(key, due_date))
                        else:
                            logging.debug("/// {}: {}".format(key, val))

                    # check that only T/R is added if T is in materials list
                    if 1 in materials_list and 2 in materials_list:
                        materials_list.remove(1)
                    if 3 in materials_list and 4 in materials_list:
                        materials_list.remove(3)
                    if 7 in materials_list and 8 in materials_list:
                        materials_list.remove(7)
                    if 9 in materials_list and 10 in materials_list:
                        materials_list.remove(9)
                    if 13 in materials_list and 14 in materials_list:
                        materials_list.remove(13)

                    # print lists
                    logging.debug("### Materials = {}".format(materials_list))
                    logging.debug("### Finishings = {}".format(finishings_list))

                    logging.debug("Sides = {}".format(sides))
                    logging.debug("Colors (f, b): {}, {}".format(colors_front, colors_back))

                    # used to determine if rollback or commit
                    errors = False
                    with db.atomic() as txn:
                        # create Quote instance
                        try:
                            quote = Quote.create(
                                quote_name="Orden {}".format(orden),
                                quote_due_date=due_date,
                                quote_copies=num_copies,
                                quote_product_name=product,
                                quote_dimention_length=DEFAULT_LENGTH,
                                quote_dimention_width=DEFAULT_WIDTH,
                                quote_printing_bleed=DEFAULT_BLEED,
                                quote_printing_sides=sides,
                                quote_printing_colors_front=colors_front,
                                quote_printing_colors_back=colors_back,
                            )
                        except IntegrityError as err:
                            errors = True  # rollback transaction
                            logging.debug("> Quote error: {}".format(err))
                        else:
                            quotes_made += 1
                            logging.debug("> Quote created successfully.")
                            # create Quote_Client instance
                            try:
                                Quote_Client.create(quote_id=quote.quote_id, client_id=DEFAULT_CLIENT)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Client error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Client created " "successfully."))
                            # create Quote_Executive instance
                            try:
                                Quote_Executive.create(quote_id=quote.quote_id, executive_id=DEFAULT_EXECUTIVE)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Executive error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Executive created " "successfully."))
                            # create Quote_Finishing instance(s)
                            for finishing in finishings_list:
                                try:
                                    Quote_Finishing.create(quote_id=quote.quote_id, finishing_id=finishing)
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> Quote_Finishing error: {}".format(err))
                                else:
                                    logging.debug(("> Quote_Finishing created " "successfully."))
                            # create Quote_Material instance(s)
                            for material in materials_list:
                                try:
                                    Quote_Material.create(quote_id=quote.quote_id, material_id=material)
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> Quote_Material error: {}".format(err))
                                else:
                                    logging.debug(("> Quote_Material created " "successfully."))
                            # create Quote_Paper instance
                            try:
                                Quote_Paper.create(quote_id=quote.quote_id, paper_id=DEFAULT_PAPER)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Paper error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Paper created " "successfully."))
                            # create AuthorizedQuote instance
                            try:
                                auth_quote = AuthorizedQuote.create(quote_id=quote.quote_id)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> AuthorizedQuote error: {}".format(err))
                            else:
                                # authorize quote
                                quote.quote_is_authorized = True
                                # set total price
                                quote.quote_total_price = DEFAULT_PRICE
                                # set imposing
                                quote.quote_imposing_per_sheet = DEFAULT_IMPOSING
                                # save quote
                                quote.save()
                                logging.debug(("> Quote authorized " "successfully."))
                                # create ApprovedQuote instance
                                try:
                                    appr_quote = ApprovedQuote.create(
                                        authorized_quote_id=auth_quote.authorized_quote_id
                                    )
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> ApprovedQuote error: {}".format(err))
                                else:
                                    # approve quote
                                    quote.quote_is_approved = True
                                    quote.save()
                                    # packaging
                                    # address to deliver
                                    # notes
                                    logging.debug(("> Quote approved " "successfully."))
                                    # create Order instance
                                    try:
                                        Order.create(approved_quote_id=appr_quote.approved_quote_id)
                                    except IntegrityError as err:
                                        errors = True  # rollback transaction
                                        logging.debug("> Order error: {}".format(err))
                                    else:
                                        # only if Quote made correctly
                                        if errors is False:
                                            orders_made += 1
                                        logging.debug(("> Order created " "successfully."))
                        # rollback if errors ocurred
                        if errors is True:
                            txn.rollback()

            # report quotes and orders made
            print("> Total lines: {}".format(total_lines))
            print("> Quotes made: {}".format(quotes_made))
            print("> Orders made: {}".format(orders_made))
            print("> Skipped {} lines.".format(len(skipped_lines)))
    except FileNotFoundError as err:
        print("> Error: {}".format(err))
Exemplo n.º 49
0
max_payload = int(words[4])
manager = Manager()
manager.changeDrones(int(words[2]))
manager.changeTurns(int(words[3]))
manager.changePayload(int(words[4]))

manager.changeNumberOfTypes(int(input()))

manager.changeWeigh(input().split())

for e in range(int(input())):
  #creates all warehouses
  w = Warehouse(input().split())
  w.addproducts(input().split())
  manager.addWarehouse(w)

nr_orders = int(input())

orders = []
for e in range(nr_orders):
  order = Order(len(orders), input().split())
  order.addproducts(int(input()), input().split())
  manager.addOrder(order)

manager.organizeWarehouses()

#for e in orders:
#  print(e.products())

deliveryCalculateStorageVisit(manager.orders(), manager.warehouses())
Exemplo n.º 50
0
 def test_order_does_not_remove_if_not_enough(self):
     order = Order(TALISKER, 51)
     order.fill(self.warehouse)
     self.assertFalse(order.is_filled())
     self.assertEqual(self.warehouse.get_inventory(TALISKER), 50)
Exemplo n.º 51
0
 def test_order_is_filled_if_enough_in_warehouse(self):
     order = Order(TALISKER, 50)
     order.fill(self.warehouse)
     self.assertTrue(order.is_filled())
     self.assertEqual(self.warehouse.get_inventory(TALISKER), 0)
Exemplo n.º 52
0
sys.setdefaultencoding('utf-8')


def deal_str(string):
    return str(string).replace(' ', '').replace('\n', '')

# def spider(x):
# return x.replace(re.match(r'<a href="/events/python-events/\d{3}/">',
# x).group(), '').replace('</a>', '')

with open('test.html', 'r') as content:
    html = content.read()

soup = BeautifulSoup(html)

xndian_order = Order()

# 订单号
order_num_list = soup.find_all('span', class_='g_stress')
xndian_order.num = deal_str(order_num_list[0].string)

# 总价
xndian_order.total_price = deal_str(order_num_list[1].string)

# 电话号 寝室号
order_tel_list = soup.find_all('td', class_='propItemValue')

xndian_order.tel = deal_str(order_tel_list[0].string)
xndian_order.dorm_num = deal_str(order_tel_list[1].string)

xndian_good_list = []
Exemplo n.º 53
0
			thres = order.rate + order.rate * order.offset/100
		if order.price < order.rate:
			order.rate = order.price
			print("{}: New peak rate: {}".format(order.pair, order.price))
		elif (order.price > thres):
			order.done = True
			order.api.buy(order.pair, order.amount, order.price)
			print("buy {} on {} at {}.".format(order.amount, order.pair, order.price))
		print("{} is at {g} will order at {g}".format(order.pair, order.price, thres))


if "__main__" == __name__:
	print("Copyright (c) 2018 Ali Raheem")
	print("Poloniex Trailing Bot")
	config = loads(open('config.json', 'r').read())
	api = polo(config["api-key"], config["api-secret"])
	api.getPrices()
	orders = []
	order = Order(api, "BTC_DOGE", 100, 2.5, sell = True, fixed = False) # Sell 100 DOGE if price falls 5%
	order.updatePrice()
	orders.append(order)
	while True:
		api.getPrices()
		for order in orders:
			order.updatePrice()
			if order.done:
				orders.remove(order)
				break
			checkOrder(order)

Exemplo n.º 54
0
 def test_checkCategoryIsSet(self):
     o = Order(" 100 P156923    SPORTING856     1012399")
     self.assertEqual(o.create()._category, "SPORTING")
Exemplo n.º 55
0
 def test_checkProductCodeIsSet(self):
     o = Order(" 100 P156923    SPORTING856     1012399")
     self.assertEqual(str(o.create()._code), "P156923")
Exemplo n.º 56
0
 def test_checkLineNoIsSet(self):
     o = Order(" 100 P15678923  SPORTING856     1012399")
     self.assertEqual(o.create()._lineNo, 100)
Exemplo n.º 57
0
def autotrader(strategy_file="", market_file="",backbars=300, interval=0.5, 
               quote=False,maxbars=False, start="",end="",pov=0,tax=0):
    """ autotrader(strategy_file,market_data,backbars)
        A set of script for you to trade any financial product in market
        this is the main script

        autotrader [options] your_strategy_file.py

        OPTIONS:
        
        -m, -market=your_market_file
            the incoming market data stream, now we only work on text file,
            you have to implement this by yourself

        -b, -backbars
            how many back bars you take to caculate, the small the better depend on your strategy
            , impact on performance
        
        -h --help       read the help
        
        -i interval the timer for check the strategy, default 0.5 second

        --start=YYYY-MM-DD tell where to start


        --end=YYYY-MM-DD tell where to end
        
        the following is market file format
        read thhe csv file last few lines to process look back data
        
        marrket file format 
        
        YYYY/MM/DD,HH:MM,OPEN,HIGH,LOW,CLOSE,VOLUMN 
        YYYY/MM/DD,OPEN,HIGH,LOW,CLOSE,VOLUMN 
        
        or 
        
        YYYY-MM-DD,OPEN,HIGH,LOW,CLOSE,VOLUMN
    """
    global AUTOTRADER_RUN,NOW,CURRENT_BAR,RUNDATA,DATASET,OO,HH,LL,CC,VV,dl,tl,ol,hl,ll,cl,vl

    if strategy_file:
        
        print "Exec Strategy File-> ", strategy_file
        
        strategy_source = open(strategy_file).read()
        
        # bind order function
        ORDER = Order()
        BUY = Buy = buy = ORDER.BUY
        SELL = Sell = sell = ORDER.SELL
        EXITLONG = ExitLong = exitlong = ORDER.EXITLONG
        EXITSHORT = ExitShort = exitshort = ORDER.EXITSHORT
        if pov:
            ORDER.pov=pov
        if tax:
            ORDER.tax=tax
        
        if re_paras.search(strategy_source):
            dd = re_paras.search(strategy_source).group()
            exec(dd)
            for k,v in PARAS.items():
                # FIXME it's not secure, but we exec strategy file anyway
                vars()[k]=v

         
        if re_vars.search(strategy_source):
            dd = re_vars.search(strategy_source).group()
            exec(dd)
            for k,v in VARS.items():
                vars()[k]=v
        
        # set time frame
        
        dl,tl,ol,hl,ll,cl,vl = [],[],[],[],[],[],[]
        
        num = len(RUNDATA)
        for i in range(num):
            # bind order variable
            ORDER.dt = RUNDATA[i][0]
            DATASET = RUNDATA[:i+1]
            MARKETPOSITION=MarketPosition=marketposition=MKS = ORDER.market_position
            ENTRYPRICE=EntryPrice=entryprice = ORDER.entry_price
            # load record
            dl,tl,ol,hl,ll,cl,vl = General_Row(dl,tl,ol,hl,ll,cl,vl,RUNDATA[i],length=backbars)
            DATE = Date=dl
            TIME = Time=tl
            OPEN = Open = O =ol
            HIGH = High = H =hl
            LOW  = Low  = L =ll
            CLOSE= Close= C =cl
            VOLUME=Volume=V = vl
            OO = ol[0] 
            HH = hl[0] 
            LL = ll[0] 
            CC = cl[0] 
            VV = vl[0] 
            exec(strategy_source)
       
        # after looping all history we taken, 
        if start or end:  
            ORDER.REPORT()
        # clear instance data 
        OO = HH = LL = CC = 0
        while AUTOTRADER_RUN and quote:
            #print datetime.datetime.now(),ORDER,ORDER.market_position, ORDER.dt
            ORDER.dt = RUNDATA[-1][0]
            MARKETPOSITION=MarketPosition=marketposition=MKS = ORDER.market_position
            ENTRYPRICE=EntryPrice=entryprice = ORDER.entry_price
            DATE = Date=dl
            TIME = Time=tl
            OPEN = Open = O =ol
            HIGH = High = H =hl
            LOW  = Low  = L =ll
            CLOSE= Close= C =cl
            VOLUME=Volume=V = vl
            if CURRENT_BAR:
                ORDER.current_dt = CURRENT_BAR

            exec(strategy_source)

            time.sleep(interval)
Exemplo n.º 58
0
 def test_checkProductPriceIsSet(self):
     o = Order(" 100 015678923 SPORTING99856    101239 ")
     self.assertEqual(o.create()._price, 1012.39)