def make_order(self): print("Заказ с собой? y/n") option = 0 self.order_current = order.Order(True) if input() == ( "y" or "Y") else order.Order() while option != "+" and option != "-": os.system("cls") option = input( "Введите номер пиццы из меню. Для подтверждения заказа введите '+', " "для отмены -- '-': \n") if option.isdecimal(): option = int(option) if 0 < option <= len(self.menu_dict): ordered_pizza = self.menu_dict.get(option, 1) ordered_pizza = ordered_pizza() self.order_current.add(ordered_pizza) ordered_pizza.bake() ordered_pizza.pack(self.order_current.takeout) else: print("В меню нет такой позиции!") else: if option == "+" or option == "-": os.system("cls") if option == "+": print(self.order_current) print("--------------------------") print("Пройдите на выдачу.") print("Вы можете забрать свой заказ " + Handout.location_of_pickup) else: self.order_current.decline() print("Заказ отменен.") input("\nНажмите 'Enter'\n") else: print("Некорректная опция!")
def testInvalidOrder(): (symbol, testExchange, testExchangeParticipant1, testExchangeParticipant2 ) = TestExchange.testExchangeCreateTestSetup() testOrder = order.Order( symbol, trade.TradeActions.Buy, order.OrderTypes.Limit, -10, 100, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == False) testOrder = order.Order( symbol, trade.TradeActions.Buy, order.OrderTypes.Limit, 10, -10, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == False) testOrder = order.Order( "NOT SYMBOL", trade.TradeActions.Buy, order.OrderTypes.Limit, 10, -10, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == False) print "Test Completed Succesfully"
def make_order(self): print("Заказ с собой? y/n") option = 0 self.order_current = order.Order(True) if input() == ( "y" or "Y") else order.Order() # Async request for pizzas available = [] for pizza_i in asyncio.run(check_availability()): available.append(self.menu_dict[pizza_i]()) print("Доступны следующие пиццы: ") print(available) while option != "+" and option != "-": os.system("cls") option = input( "Введите номер пиццы из меню. Для подтверждения заказа введите '+', " "для отмены -- '-': \n") if option.isdecimal(): option = int(option) if 0 < option <= len(self.menu_dict): ordered_pizza = self.menu_dict.get(option, 1) ordered_pizza = ordered_pizza() try: self.order_current.add(ordered_pizza) except Exception as e: print(e) print("Нажмите 'Enter'") input() break baking = threading.Thread(target=ordered_pizza.bake()) packing = threading.Thread( target=ordered_pizza.pack(self.order_current.takeout)) baking.start() packing.start() baking.join() packing.join() else: print("В меню нет такой позиции!") else: if option == "+" or option == "-": os.system("cls") if option == "+": self.order_current.get_total_price() print(self.order_current) print("--------------------------") print("Пройдите на выдачу.") print("Вы можете забрать свой заказ " + Handout.location_of_pickup) else: self.order_current.decline() print("Заказ отменен.") input("\nНажмите 'Enter'\n") else: print("Некорректная опция!")
def _onMktData(self, barGroup): # super(SimpleStrategy, self).__onMktData() # print('SimpleStrategy on market data') print '###################.{}'.format(barGroup.dateTime) try: if len(list(self._hist['SS'].close[-10:])): if barGroup['SS'].close > np.max(list(self._hist['SS'].high[-10:])): o1 = order.Order('limit', barGroup['SS'].close + 100, order.Order.Direction.BUY, 'SS', 300) self._sendOrder(o1) elif barGroup['SS'].close < np.min(list(self._hist['SS'].low[-10:])): o1 = order.Order('limit', barGroup['SS'].close - 100, order.Order.Direction.SELL, 'SS', 300) self._sendOrder(o1) except KeyError: pass
def testExchangeSubmitLimitOrderPartialFill(): (symbol, testExchange, testExchangeParticipant1, testExchangeParticipant2 ) = TestExchange.testExchangeCreateTestSetup() # Setup test orders in the order book testOrder = order.Order( "AA", trade.TradeActions.Buy, order.OrderTypes.Limit, 10, 100, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) testOrder = order.Order( "AA", trade.TradeActions.Buy, order.OrderTypes.Limit, 9, 100, 0, testExchangeParticipant2.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) testOrder = order.Order( "AA", trade.TradeActions.Sell, order.OrderTypes.Limit, 11, 100, 0, testExchangeParticipant2.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) # Check full fill of limit order against book testOrder = order.Order( "AA", trade.TradeActions.Sell, order.OrderTypes.Limit, 9, 175, 0, testExchangeParticipant2.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) topOfBookQuote = testExchange.orderBook.getTopOfBook() testComparisonQuote = quote.Quote(symbol, 9, 11, 25, 100) assert (topOfBookQuote == testComparisonQuote) # Check partial fill of limit order against book testOrder = order.Order( "AA", trade.TradeActions.Sell, order.OrderTypes.Limit, 9, 50, 0, testExchangeParticipant2.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) topOfBookQuote = testExchange.orderBook.getTopOfBook() testComparisonQuote = quote.Quote(symbol, None, 9, 0, 25) assert (topOfBookQuote == testComparisonQuote) print "Test Completed Succesfully"
def __init__(self): self.orders = order.Order() try: with open('orders.json', 'r') as f: self.orders.load_json(f) except IOError as e: print(e)
def load_order_list(self, tday): logfile = self.file_prefix + 'order_' + tday.strftime( '%y%m%d') + '.csv' if not os.path.isfile(logfile): return {} self.id2order = {} with open(logfile, 'rb') as f: reader = csv.reader(f) for idx, row in enumerate(reader): if idx > 0: inst = row[3] pos = self.positions[inst] if ':' in row[13]: cond = dict([ tuple([int(k) for k in n.split(':')]) for n in row[13].split(' ') ]) else: cond = {} iorder = order.Order(inst, float(row[10]), int(row[4]), int(row[11]), row[7], row[8], row[9], cond, self) iorder.sys_id = row[1] iorder.local_id = row[2] iorder.filled_volume = int(row[5]) iorder.filled_price = float(row[6]) iorder.order_ref = int(row[0]) iorder.trade_ref = int(row[14]) iorder.status = int(row[12]) self.id2order[iorder.order_ref] = iorder self.add_order(iorder)
def make_order(self): option = 0 self.order_current = order.Order() while option != "+" and option != "-": os.system("cls") option = input( "Введите номер пиццы из меню. Для подтверждения заказа введите '+', " "для отмены -- '-': \n") if option.isdecimal(): option = int(option) if 0 < option <= len(self.menu_dict): ordered_pizza = self.menu_dict.get(option, 1) ordered_pizza = ordered_pizza() self.order_current.add(ordered_pizza) else: print("В меню нет такой позиции!") else: if option == "+" or option == "-": os.system("cls") if option == "+": print(self.order_current) print("--------------------------") print("Пройдите на выдачу.") else: self.order_current.decline() print("Заказ отменен.") input("\nНажмите 'Enter'\n") else: print("Некорректная опция!")
def buy(bar): print("buy decision") orders = [] date = datetime.datetime(2017, 12, 11, 14, 30, 0) orders.append(order.Order("000001.XSHE", 100, date, 11.34, True, 0)) return orders
def __init__(self, controller, phoneNumber, captcha, orderId, appchannel, privatekey, paths): self.controller = controller self.general = gen.General(controller, appchannel, privatekey, paths) self.order = order.Order(controller, paths) self.payment = pay.Payment(controller, paths) self.wallet = wal.Wallet(controller, paths) self.phoneNumber = phoneNumber self.captcha = captcha self.orderId = orderId
def get_order(self, order_id): try: o = self.api.get_order_by_client_order_id(order_id) return order.Order(o.client_order_id, o.status, o.filled_avg_price, o.qty, o.replaced_by) except tradeapi.rest.APIError as err: logging.error( f'GET /order API Code: {err.code} HTTP Code: {err.status_code} Message: {str(err)}' ) return None
def gen_order_from_file(): #reading input from input.dat and generating order input_file = os.path.join(os.path.dirname(__file__), "input.dat") with open(input_file, "r") as f: for ln in f: o = json.loads(ln) stream = o["stream"] header = o["header"] del o["stream"] del o["header"] yield order.Order(stream, header, o)
def make_order(self, screen, frame_list, label_list, order_info, answer): if answer == "yes": order.Order(order_info["unit"], order_info["counselor"], order_info["item_list"], order_info["num_people"], order_info["session"], order_info["pickup_day"], order_info["pickup_time"], order_info["drop_off_day"], order_info["drop_off_time"], order_info["needs_options"]) self.main_menu_gui(False, screen, frame_list, label_list) elif answer == "no": self.choose_unit_gui(screen, frame_list, label_list, {}) else: print("ERROR IN CONFIRMATION PAGE")
def testExchangeSubmitLimitOrderAgainstEmptyBook(): (symbol, testExchange, testExchangeParticipant1, testExchangeParticipant2 ) = TestExchange.testExchangeCreateTestSetup() testOrder = order.Order( "AA", trade.TradeActions.Buy, order.OrderTypes.Limit, 10, 100, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) print "Test Completed Succesfully"
def book_order(self, instID, volume, price_type, limit_price, trade_ref=0, order_num=1): direction = ORDER_BUY if volume > 0 else ORDER_SELL order_offsets = self.get_order_offset(instID, volume, order_num) new_orders = [order.Order(instID, limit_price, v, self.agent.tick_id, action_type, direction, price_type, trade_ref = trade_ref) \ for (action_type, v) in order_offsets] self.add_orders(new_orders) return new_orders
def get_orders(self): # TODO: Need to handle 100+ orders, this can be tested by using per_page=10 # TODO: thread this for i in range(3): try: raw_orders = self.wc_api.get('orders', params={'per_page': 100, 'page': 1}) break except ReadTimeout: print(i) pp = pprint.PrettyPrinter() pp.pprint(raw_orders.json()[0]) f1 = open('raw_data.txt', 'w') f1.write(pp.pformat(raw_orders.json())) f1.close() for order_json in raw_orders.json(): self.customer_orders[order_json['id']] = order.Order(order_json) [self.customer_orders[order_id].parse_items() for order_id in self.customer_orders] [self.customer_orders[order_id].get_shipping_info() for order_id in self.customer_orders] # TODO: thread this for i in range(3): try: raw_subs = self.wc_subs_api.get("subscriptions", params={'per_page': 100, 'page': 1}) break except ReadTimeout: print(i) subs = [] for sub_json in raw_subs.json(): a = subscription.Subscription(sub_json) subs.append(a) a.parse_items() # Add subscription stuff to order items...this is so janky... for sub in subs: for item_id in self.customer_orders[sub.parent_id].items: order_item_name = self.customer_orders[sub.parent_id].items[item_id].name for sub_item_id in sub.items: sub_item_name = sub.items[sub_item_id].name if order_item_name == sub_item_name and sub.status == 'active': self.customer_orders[sub.parent_id].items[item_id].sub = True self.customer_orders[sub.parent_id].items[item_id].date_paid = datetime.datetime.strptime(sub.date_paid, '%Y-%m-%dT%H:%M:%S').date() self.customer_orders[sub.parent_id].items[item_id].next_payment_date = datetime.datetime.strptime(sub.next_payment_date, '%Y-%m-%dT%H:%M:%S').date() # update roast dates with subscription roasts for order_id in self.customer_orders: for item_id in self.customer_orders[order_id].items: self.customer_orders[order_id].items[item_id].add_subscription_roast_dates()
def plan(self): m_orders = [] m4order = self.calMaterials() tools.print_list(m4order, ("%s 需要订购的原料" % self.name)) m_suppliers = self.get_suppliers_list() # 原料供应厂 for fname in m_suppliers: inames = self.cfg.f_stocks[fname][WType.products].keys() demand = order.get_demand(m4order, inames) if len(demand) > 0: m_order = order.Order(fname) m_order.set_demander(self.name, 0) # id - depends m_order.goods = demand m_orders.append(m_order) return m_orders
def book_order(self, instID, volume, price_type, limit_price, trade_ref=0, order_num=1): direction = ORDER_BUY if volume > 0 else ORDER_SELL order_offsets = self.get_order_offset(instID, volume, order_num) new_orders = [order.Order(instID = instID, limit_price = limit_price, volume = v, \ order_time = self.agent.tick_id, action_type = action_type, \ direction = direction, price_type = price_type, trade_ref = trade_ref) \ for (action_type, v) in order_offsets] self.add_orders(new_orders) self.positions[instID].re_calc() return new_orders
def sell(bar, positions): print("sell decision") orders = [] for pid in positions: p = positions[pid] for b in bar: if p.stockId == b["order_book_id"] and p.highestPrice < b["close"]: p.highestPrice = b.close elif p.stockId == b[ "order_book_id"] and p.highestPrice * p.lostTolerance > b[ "close"]: orders.append( order.Order(p.stockId, p.amount, b["datetime"], b["close"], False, p.id)) return orders
def get_order_history(self): db = database.connect() cursor = database.get_cursor(db) order_list = [] cursor.execute("select id from orders \ where person_id = :input_id" , \ input_id = self.get_id()) orders = cursor.fetchall() database.disconnect(db) if orders: for order_id in orders: order_list.append(order.Order(order_id[0])) return order_list
def test_simple(self): self.now = datetime.datetime(2014, 6, 24, 12, 30) a = order.Order(clock=self.clock) a.next[0] = True url = mail_url(a) parts = urllib.parse.urlparse(url) self.assertEqual(parts.scheme, 'mailto') self.assertEqual(parts.netloc, TO_ADDRESS) self.assertEqual(parts.path, '') self.assertEqual(parts.params, '') query = urllib.parse.parse_qs(parts.query, keep_blank_values=True, strict_parsing=True) self.assertEqual(parts.fragment, '') self.assertEqual(query['subject'][0], 'Essen KW27') ordered = [w in query['body'][0] for w in WOCHENTAGE] self.assertSequenceEqual(ordered, [True, False, False, False, False])
def processAction(self, action): statusString = "" if action == 1: self.graph = graph.Graph() statusString = "The graph has been created successfully" elif action == 2: if self.graph != None: self.clearScreen() self.graph.printGraph() input("\nPress enter to return to the main menu...") statusString = "The graph was displayed successfully" else: statusString = "Error : The graph hasn't been created yet" elif action == 3: self.clearScreen() self.order = order.Order() self.order.takeOrder() statusString = "The order was taken successfully" elif action == 4: if self.order != None: self.clearScreen() self.order.printOrder() input("\nPress enter to return to the main menu...") statusString = "The order was displayed successfully" else: statusString = "An order hasn't been created yet" elif action == 5: if (self.graph != None) and (self.order != None): self.clearScreen() self.algoSolver.findShortestPath(self.graph, START_NODE_ID, self.order) input("\nPress enter to return to the main menu...") statusString = "The shortest path was displayed successfully" elif (self.graph == None) and (self.order == None): statusString = "The graph and the order haven't been created yet" elif self.graph == None: statusString = "The graph hasn't been created yet" elif self.order == None: statusString = "An order hasn't been created yet" elif action == 6: exit() return statusString
def handle(self, quote): print(self.lastQuote.volume) if ( self.lastQuote.volume > 1000 ): #and (self.lastQuote.low<self.lastQuote.close) and (self.lastQuote.open>self.lastQuote.close) and (self.lastQuote.close-self.lastQuote.low)>2: self.columna.append(self.lastQuote.close) self.orders.append( m.Order(self.data.index, self.data.time, self.lastQuote.time, self.lastQuote.close, 3, self.lastQuote.close + 3, 'sell', 34)) #rt.Singleton.getInstance().result['tmr'][self.indice] = True #rt.Singleton.getInstance().result['gaa'] = True else: #print ('gaaa') self.columna.append(np.nan) #rt.Singleton.getInstance().result['tmr'][self.indice] = False #print (len(self.columna) , (rt.Singleton.getInstance().result['close'])) #rt.Singleton.getInstance().result['tmr'][self.indice] = pd.Series(self.columna, index =rt.Singleton.getInstance().result.index ) self.indice += 1
def testExchangeCancelOrder(): (symbol, testExchange, testExchangeParticipant1, testExchangeParticipant2 ) = TestExchange.testExchangeCreateTestSetup() testOrder = order.Order( symbol, trade.TradeActions.Buy, order.OrderTypes.Limit, 10, 100, 0, testExchangeParticipant1.getAccount().getAccountId()) result = testExchange.submitOrder(testOrder) assert (result[0] == True) topOfBookQuote = testExchange.orderBook.getTopOfBook() testComparisonQuote = quote.Quote(symbol, 10, None, 100, 0) assert (topOfBookQuote == testComparisonQuote) testExchange.cancelOrder(1) topOfBookQuote = testExchange.orderBook.getTopOfBook() testComparisonQuote = quote.Quote(symbol, None, None, 0, 0) assert (topOfBookQuote == testComparisonQuote) print "Test Completed Succesfully"
def setUp(self): self.storage = Mock() self.cursor = Mock() self.cursor.description = [['ID'], ['amount'], ['limitRate']] self.cursor.fetchone = Mock(return_value=[42, 6000000, 200000]) #60 eur @ 2 eur/btc self.storage.execute = Mock(return_value=self.cursor) order.StoredObject.createStoredObject = Mock(return_value=43) self.order = order.Order( self.storage, 'foo', 42, False, address='bar', bid=offer.Asset(max_amount=0, max_amount_divisor=100000000000, currency='btc', exchange='ln'), ask=offer.Asset(max_amount=0, max_amount_divisor=100000, currency='eur', exchange='bl3p.eu'), )
def check_trade(self, exec_trade): pending_orders = [] trade_ref = exec_trade.id if exec_trade.id not in self.ref2trade: self.ref2trade[exec_trade.id] = exec_trade if exec_trade.status == order.ETradeStatus.Pending: if exec_trade.valid_time < self.tick_id: exec_trade.status = order.ETradeStatus.Cancelled strat = self.strategies[exec_trade.strategy] strat.on_trade(exec_trade) else: pending_orders = self.process_trade(exec_trade) elif (exec_trade.status == order.ETradeStatus.Processed) or ( exec_trade.status == order.ETradeStatus.PFilled): #exec_trade.update() if exec_trade.valid_time < self.tick_id: if exec_trade.status != order.ETradeStatus.Done: exec_trade.valid_time = self.tick_id + self.cancel_protect_period new_orders = {} for inst in exec_trade.instIDs: orders = [] for iorder in exec_trade.order_dict[inst]: if (iorder.volume > iorder.filled_volume): if ( iorder.status == order.OrderStatus.Waiting) \ or (iorder.status == order.OrderStatus.Ready): iorder.on_cancel() event = Event(type=EVENT_ETRADEUPDATE) event.dict['trade_ref'] = iorder.trade_ref self.trade_update(event) else: self.cancel_order(iorder) if exec_trade.status == order.ETradeStatus.PFilled: cond = { iorder: order.OrderStatus.Cancelled } norder = order.Order( iorder.position, 0, 0, # fill in the volume when the dependent order is cancelled self.tick_id, iorder.action_type, iorder.direction, OPT_MARKET_ORDER, cond, trade_ref, gateway=iorder.gateway) orders.append(norder) if len(orders) > 0: new_orders[inst] = orders for inst in new_orders: gateway = self.inst2gateway[inst] pos = gateway.positions[inst] for iorder in new_orders[inst]: exec_trade.order_dict[inst].append(iorder) pos.add_order(iorder) self.ref2order[iorder.order_ref] = iorder if iorder.status == order.OrderStatus.Ready: pending_orders.append(iorder.order_ref) if (len(pending_orders) > 0): for order_ref in pending_orders: self.send_order(self.ref2order[order_ref]) self.save_state()
def process_trade(self, exec_trade): all_orders = {} pending_orders = [] order_prices = [] trade_ref = exec_trade.id for inst, v, tick in zip(exec_trade.instIDs, exec_trade.volumes, exec_trade.slip_ticks): if v > 0: order_prices.append(self.instruments[inst].bid_price1 + self.instruments[inst].tick_base * tick) else: order_prices.append(self.instruments[inst].ask_price1 - self.instruments[inst].tick_base * tick) curr_price = sum([ p * v * cf for p, v, cf in zip(order_prices, exec_trade.volumes, exec_trade.conv_f) ]) / exec_trade.price_unit if curr_price <= exec_trade.limit_price: required_margin = 0 for idx, (inst, v, otype) in enumerate( zip(exec_trade.instIDs, exec_trade.volumes, exec_trade.order_types)): orders = [] gateway = self.inst2gateway[inst] pos = gateway.positions[inst] pos.re_calc() gateway.calc_margin() if ((v>0) and (v > pos.can_close.long + pos.can_yclose.long + pos.can_open.long)) or \ ((v<0) and (-v > pos.can_close.short + pos.can_yclose.short + pos.can_open.short)): self.logger.warning( "ETrade %s is cancelled due to position limit on leg %s: %s" % (exec_trade.id, idx, inst)) exec_trade.status = order.ETradeStatus.Cancelled strat = self.strategies[exec_trade.strategy] strat.on_trade(exec_trade) return False if v > 0: direction = ORDER_BUY vol = max(min(v, pos.can_close.long), 0) remained = v - vol else: direction = ORDER_SELL vol = max(min(-v, pos.can_close.short), 0) remained = v + vol if vol > 0: cond = {} if (idx > 0) and (exec_trade.order_types[idx - 1] == OPT_LIMIT_ORDER): cond = { o: order.OrderStatus.Done for o in all_orders[exec_trade.instIDs[idx - 1]] } order_type = OF_CLOSE if (self.instruments[inst].exchange == "SHFE"): order_type = OF_CLOSE_TDAY iorder = order.Order(pos, order_prices[idx], vol, self.tick_id, order_type, direction, otype, cond, trade_ref, gateway=gateway.gatewayName) orders.append(iorder) if (self.instruments[inst].exchange == "SHFE") and (abs(remained) > 0) and ( pos.can_yclose.short + pos.can_yclose.long > 0): if remained > 0: direction = ORDER_BUY vol = max(min(remained, pos.can_yclose.long), 0) remained -= vol else: direction = ORDER_SELL vol = max(min(-remained, pos.can_yclose.short), 0) remained += vol if vol > 0: cond = {} if (idx > 0) and (exec_trade.order_types[idx - 1] == OPT_LIMIT_ORDER): cond = { o: order.OrderStatus.Done for o in all_orders[exec_trade.instIDs[idx - 1]] } iorder = order.Order(pos, order_prices[idx], vol, self.tick_id, OF_CLOSE_YDAY, direction, otype, cond, trade_ref, gateway=gateway.gatewayName) orders.append(iorder) vol = abs(remained) if vol > 0: if remained > 0: direction = ORDER_BUY else: direction = ORDER_SELL under_price = 0.0 if (self.instruments[inst].ptype == instrument.ProductType.Option): under_price = self.instruments[ self.instruments[inst].underlying].price required_margin += vol * self.instruments[ inst].calc_margin_amount(direction, under_price) cond = {} if (idx > 0) and (exec_trade.order_types[idx - 1] == OPT_LIMIT_ORDER): cond = { o: order.OrderStatus.Done for o in all_orders[exec_trade.instIDs[idx - 1]] } iorder = order.Order(pos, order_prices[idx], vol, self.tick_id, OF_OPEN, direction, otype, cond, trade_ref, gateway=gateway.gatewayName) orders.append(iorder) all_orders[inst] = orders exec_trade.order_dict = all_orders for inst in exec_trade.instIDs: for iorder in all_orders[inst]: pos = self.gateways[iorder.gateway].positions[inst] pos.add_order(iorder) self.ref2order[iorder.order_ref] = iorder if iorder.status == order.OrderStatus.Ready: pending_orders.append(iorder.order_ref) exec_trade.status = order.ETradeStatus.Processed return pending_orders else: return pending_orders
""" returns iformation about needed order """ needed_order = 0 for this_order in self.orders: if this_order.orderId == orderId: needed_order = this_order break if needed_order != 0: return f"Your order #{orderId} is sent to \ {needed_order.city}. Total price: {needed_order.calculateAmount()} UAH." return "No such order." if __name__ == "__main__": vehicles = [vehicle.Vehicle(1), vehicle.Vehicle(2)] logSystem = LogisticSystem(vehicles) my_items = [item.Item('book',110), item.Item('chupachups',44)] my_order = order.Order(user_name = 'Oleg', city = 'Lviv', postoffice = 53, items = my_items) print(my_order) logSystem.placeOrder(my_order) print(logSystem.trackOrder(1)) my_items2 = [item.Item('flowers',11), item.Item('shoes',153), item.Item('helicopter',0.33)] my_order2 = order.Order('Andrii', 'Odessa', 3, my_items2) print(my_order2) # Your order number is 234976475. logSystem.placeOrder(my_order2) print(logSystem.trackOrder(2)) my_items3 = [item.Item('coat',61.8), item.Item('shower',5070), item.Item('rollers',700)] my_order3 = order.Order("Olesya", 'Kharkiv', 17, my_items3) logSystem.placeOrder(my_order3)
def pay(self, order): '''计算订单总价,根据各种折扣规则''' '''计算折扣前订单总价''' pay = self.calc_pay(order) qy = self.calc_quantity(order) isvip = self.query_is_vip(order.customer.mobile) discount = min( discount_func(isvip, pay, qy) for discount_func in self.dm.discounts) final_pay = discount * pay print( f'price is {pay:.2f}, discount is {discount:.2f}, so final price is {final_pay:.2f}元' ) return final_pay if __name__ == '__main__': sm = SuperMarket() """准备订单""" """1st type: vip用户数量和价格均达到,此时应该是8折""" Onomah = order.Customer('Onomah', '13500000001') cart = [ order.Product('apple', '2'), order.Product('orange', '30'), order.Product('pineapple', '10') ] order1 = order.Order(Onomah, cart) sm.pay(order1)
# test for the order structure import order import order_detail from src.main.python.core import * from src.main.python.entities import * ioc_instance = ioc.Ioc() order_controller = ioc_instance.get_instance('order_controller') order_1 = order.Order() order_detail_1 = order_detail.OrderDetails() order_2 = order.Order() order_detail_2 = order_detail.OrderDetails() product_1 = product.Product() product_1.id = 1 product_1.name = 'pizza' product_1.description = 'ham and cheese with bacon' product_1.price = 250 product_2 = product.Product() product_2.name = 'hamburger' product_2.description = 'bacon triple hamburger' product_2.price = 200 product_3 = product.Product() product_3.name = 'Pina Colada' product_3.description = 'Frozen Pina Colada' product_3.price = 100