def trade(self, today: datetime, context: Context) -> List[Order]: assert isinstance(today, datetime) window = 10.0 previous = today - timedelta(days=window) iso = previous.strftime("%Y-%m-%d") test = self.data["AAPL"].get_single_price(previous, flexible=True) rolling_test = self.data["AAPL"].get_rolling_average(previous, today) test2 = self.data["AAPL"].check_date_range(previous, today, flexible=True) curr = self.AlpacaData.get_bars_data("AAPL", timeframe='15Min', start=today, end=today, limit=5) curr_data = curr["AAPL"].at[ curr["AAPL"].index[-1], 'close'] # getting most recent closing price if test < curr_data: # buy self.orders.append(Order("buy", "AAPL", 1)) else: # sell self.orders.append(Order("sell", "AAPL", 1)) return self.orders
def test_return_good_orders(self): orders = [ Order('buy', 'AAPL', 2), Order('sell', 'GMC', notional=2000.00), Order('buy', 'GOOG', 3.5), ] new_orders = self.o_r.backtest_orders(orders) self.assertTrue(orders == new_orders)
def test_reduce_multiples3(self): orders = [ Order('buy', 'AAPL', 2), Order('buy', 'AAPL', 1), Order('sell', 'AAPL', 5) ] resultant = Order('sell', "AAPL", 2) filtered = self.o_r.backtest_orders(orders) self.assertTrue(resultant == filtered[0])
def test_instantiation(self): try: Order('buy', "GMC", 2) Order('sell', 'RKT', notional=1500.00) Order("buy", "AMC", notional=1000.00) except AssertionError: self.fail() else: self.assertTrue(True)
def add(): title = 'Cadastrar Pedido' form = OrderForm() form.cliente.data = session.get('user_id', '') if request.form: form = OrderForm(request.form) if form.validate_on_submit(): if form.order_id.data: order = Order() ret = order.get(form.order_id.data) order.observacao = form.observacao.data order.clientes_id = form.cliente.data ret = order.update() flash(ret, 'info') return redirect(url_for('order.index')) else: flash('É necessário ao menos um produto para cadastrar um pedido.', 'danger') return render_template('order_form.html', form=form, title=title, mode='add', pageOrigin='add-page'), 200
def post(self): try: data = json.loads(request.data) chef_id = data.get("chefId") user_id = data.get("userId") arrival_ts = data.get("arrivalDateTimeStamp") # items with meal_id and quantity ordered_items = data.get("orderedItems") order = Order(chef_id, user_id, arrival_ts) order.save() for item in ordered_items: ojmt_obj = OrderJoinMealItem(order.id, item.get("id"), item.get("quantity")) ojmt_obj.save() total_amount_dollars = compute_total(ordered_items) intent = stripe.PaymentIntent.create(amount=int( total_amount_dollars * 100), currency='usd') return jsonify({ 'clientSecret': intent['client_secret'], 'totalAmount': total_amount_dollars, 'orderId': order.id }) except Exception: return custom_json_response( {'error': 'problem getting clientSecret'}, 403)
def post_order(): """ header Authorization: Token Authentication_user_token { "event_key": "y37jsnks", "drinks": [{ "mixer_type": "coke", "alcohol_type": "rhum", "double": True }], } """ if request.content_type != JSON_MIME_TYPE: return json_error('Invalid Content Type', 'Invalid Content Type', 400) if g.get('current_user', None) is None: return json_error('No user found might have been a machine token', status=401) data = request.json event = Event.find(data.get('event_key')) if event is None: return json_error('Event not found', 'Event not found', 404) drinks = [ Drink(drink.get('mixer_type'), drink.get('alcohol_type'), drink.get('double')) for drink in data.get('drinks') ] # total_price = Order.get_price_from_drinks(drinks) # TODO process transation, for now assume the trasaction always passes new_order = Order(g.current_user._id, drinks, payed=True) new_order.create() event.add_new_order(new_order) g.current_user.add_order(new_order) return json_response(json.dumps(new_order.to_dict()), status=200)
def make_order_info(self, prompt, customer_known): """Býr til tóma pöntun og sendir pöntunina í gegnum ferlið að búa til allar upplýsingar um hana""" price_repo = PriceRepository() new_order = Order() for step in range(1, 5): if customer_known and (step == 1): new_order.set_customer(customer_known) else: choice = new_order.change_info(str(step), self.__car_service, self.__customer_service, prompt, price_repo) if choice == "t": return "t" elif choice == "h": return "h" price_repo = PriceRepository() price = calc_price(new_order, price_repo) new_order.set_price(price) print_header(prompt) print(new_order) print("="*70) continue_q = input("\nEr allt rétt? (j/n) ").lower() if continue_q != "j": self.change_order_info(new_order, prompt) print_header(prompt) payment_complete = take_payment(new_order.get_order_price()) if type(payment_complete) == str: return "h" print_header(prompt) print("Pöntun skráð.") sleep(2.5) self.__order_repo.add_order(new_order) return new_order
def get(self): user_info = self.session['index_user'].to_json() data = json.loads(self.get_argument('data')) trade_no = sec_pass(str(int(time.time()))) # 交易号 # 加入订单 save_data = { "TRADE_NO": trade_no, "UserID": user_info.get('UserID'), "OrderTotalPrice": data.get('totalprice'), "OrderPayType": 1, "OrderStatus": False, "OrderSendAddress": data.get('address') } try: product_list = [] for i, x in enumerate(data.get('all_data')): # 删除购物车信息 session.query(ShopCart).filter( ShopCart.ShopCartID == x['shopcartid']).delete() # 修改商品信息 session.query(Product).filter( Product.ProductID == x['productid']).update({ "ProductBuyNum": Product.ProductBuyNum + int(x['num']) }) product_list.append(str(x['productid'])) save_data['ProductID'] = ','.join(product_list) session.add(Order(**save_data)) session.commit() except Exception, e: session.rollback()
def seed_db(): from models.Item import Item from models.User import User from models.Order import Order from models.OrderShipping import OrderShipping from main import bcrypt from faker import Faker import random faker = Faker() for i in range(3): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) admin = User() admin.email = "*****@*****.**" admin.password = bcrypt.generate_password_hash("123456").decode("utf-8") admin.admin = True db.session.add(admin) db.session.commit() for i in range(10): item = Item() item.name = faker.currency_name() item.description = faker.paragraph(nb_sentences=3) item.price = 53.25 db.session.add(item) db.session.commit() ordershipping = [] for i in range(5): shipping = OrderShipping() shipping.first_name = faker.first_name() shipping.last_name = faker.last_name() shipping.address = faker.street_address() shipping.state = faker.city() shipping.zip_code = faker.postcode() db.session.add(shipping) ordershipping.append(shipping) db.session.commit() orders = [] for i in range(5): order = Order() order.shipping_id = random.choice(ordershipping).id db.session.add(order) orders.append(order) db.session.commit() print("Tables seeded.")
def test_condense2(self): orders = [ ("buy", "GMC", 2.5), ("sell", 'GMC', 3.0), ] objs = [Order(*o) for o in orders] self.assertTrue(objs[0].condensable(objs[1]))
def test_condense3(self): orders = [ ("buy", "GMC", 2.5), ("buy", 'GMC', 3.0, 'limit', 0.0, 'day', 150.0), ] objs = [Order(*o) for o in orders] self.assertFalse(objs[0].condensable(objs[1]))
def add_order(): if (request.form['client']): now = datetime.now() order = Order(now.strftime("%y-%m-%d %H:%M:%S"), request.form['obs'], request.form['client']) ret = order.insert() if ret == 'Pedido cadastrado com sucesso!': return jsonify({'order_id': order.id}) else: return jsonify({'message': ret}) return jsonify({'message': 'O parâmetro ID do cliente é obrigatório'})
def seed_db(): from main import bcrypt from models.Menu import Menu from models.User import User from models.Order import Order from faker import Faker import random faker = Faker() users = [] menus = [] for i in range(10): user = User() user.email = faker.email() user.password = bcrypt.generate_password_hash("123456").decode("utf-8") user.first_name = faker.first_name() user.last_name = faker.last_name() user.admin = faker.boolean(chance_of_getting_true=50) users.append(user) db.session.add(user) print(f"{i} users created") db.session.commit() for i in range(10): menu = Menu() menu.title = faker.color_name() menu.price = faker.random_number(digits=2) menu.vegetarian = faker.boolean(chance_of_getting_true=50) menus.append(menu) db.session.add(menu) print(f"{i} book record(s) created") db.session.commit() for i in range(10): order = Order() order.menu_id = random.choice(menus).id order.user_id = random.choice(users).id order.test = "test" db.session.add(order) print(f"{i} order created") db.session.commit() print("Tables seeded")
def test_bad_orders(self): orders = [ ("hold", "BTC"), ("SELL", 'GMC', 2.0), ("buy", "AAPL", 2.0, 'stop_limit'), ] for o in orders: try: Order(*o) except AssertionError: continue else: self.fail() self.assertTrue(True)
def order_create(): # create new order order_fields = order_schema.load(request.json) shipping_id = request.args["shipping_id"] shipping_id = OrderShipping.query.filter_by(id=shipping_id).first() new_order = Order() new_order.date_ordered = order_fields["date_ordered"] new_order.shipped = order_fields["shipped"] shipping_id.orders.append(new_order) db.session.commit() return jsonify(order_schema.dump(new_order))
def hello_world(product, email): db.drop_all() db.create_all() user1 = User(email=email) db.session.add(user1) db.session.commit() product1 = Product(title=product) db.session.add(product1) db.session.commit() order1 = Order(user=user1, product=product1) db.session.add(order1) db.session.commit() return 'Ok'
def delete_product_order(): if (request.form['order_id'] and request.form['product_id']): order_p = OrderProduct() order_p.pedidos_id = request.form['order_id'] order_p.produtos_id = request.form['product_id'] ret = order_p.delete() if (request.form['from'] and request.form['from'] == 'add-page'): order = Order() order.id = request.form['order_id'] order.delete() return jsonify({'message': ret}) return jsonify({ 'message': 'O parâmetro ID do pedido e ID do produto são obrigatórios' })
def edit(id): title = 'Editar Pedido' order = Order() ret = order.get(id) if not order.id: flash(ret, 'info') return redirect(url_for('order.index')) if session.get('user_grupo', '') == 'user': if order.clientes_id != session.get('user_id', ''): flash('Você não tem permissão para acessar este recurso.', 'info') return redirect(url_for('order.index')) order_p = OrderProduct() products = order_p.getByOrderId(order.id) images = [] for product in products: images.append(b64encode(product[7]).decode("utf-8")) if not request.form: form = OrderForm() form.cliente.data = str(order.clientes_id) form.observacao.data = order.observacao form.order_id.data = order.id orderproduct = OrderProduct() pedidos_produtos = orderproduct.getByOrderId(order.id) else: form = OrderForm(request.form) if form.validate_on_submit(): order.observacao = form.observacao.data order.clientes_id = form.cliente.data ret = order.update() flash(ret, 'info') return redirect(url_for('order.edit', id=order.id)) return render_template('order_form.html', form=form, title=title, mode='edit', orderId=order.id, clientName=order.cliente_name, pageOrigin='edit-page', products=products, images=images), 200
def index(): order = Order() user_id = request.args.get('user', None) client = Client() clients = client.getAll() if session.get('user_grupo', '') != 'user': if user_id: orders = order.getByUser(user_id) else: orders = order.getAll() else: orders = order.getByUser(session.get('user_id', '')) return render_template('order.html', orders=orders, clients=clients, user_id=user_id), 200
def populate_order_list(self): """ Opens the database (csv) file and reads its contents. If the file doesn't exist it is created with the columns of the file. """ try: with open("./data/orders.csv", "r") as orders_db: csv_dict = csv.DictReader(orders_db) for line in csv_dict: new_order = Order( line["Order_id"], line["Order_date"], line["Rent_date_from"], line["Rent_date_to"], line["Insurance_with_credit_card"], line["Bought_km"], line["Additional_Insurance"], line["Customer_id"], line["Car_id"], line["Additional_Cost"]) self.__orders.append(new_order) except FileNotFoundError: with open("./data/orders.csv", "w") as orders_db: orders_db.write( "Order_id,Order_date,Rent_date_from,Rent_date_to,Insurance_with_credit_card,Bought_km,Additional_Insurance,Customer_id,Car_id,Additional_Cost\n" )
def create(): # This will deserialize the JSON from insomnia schema = OrderSchema() try: # attempt to convert the JSON into a dict data = schema.load(request.get_json()) # Use that to create a order object order = Order(**data) # store it in the database db.commit() except ValidationError as err: # if the validation fails, send back a 422 response return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 # otherwise, send back the order data as JSON return schema.dumps(order), 201
def order_create(storeId, customerID): order_fields = order_schema.load(request.json) new_order = Order() new_order.order_placed = order_fields["order_placed"] cart = order_fields["cart"] for item in cart: item_query = Product.query.filter_by(id=item).first() new_order.orders_products.append(item_query) db.session.commit() new_order.customer_id = customerID customer = Customer.query.filter_by(id=customerID).first() if not customer: return abort(400, description="Incorrect customer") customer.order.append(new_order) db.session.commit() return jsonify(order_schema.dump(new_order))
def delete(id): order = Order() ret = order.get(id) if not order.id: flash(ret, 'info') return redirect(url_for('order.index')) if session.get('user_grupo', '') == 'user': if order.clientes_id != session.get('user_id', ''): flash('Você não tem permissão para acessar este recurso.', 'info') return redirect(url_for('order.index')) if request.method == 'POST': order_p = OrderProduct() order_p.deleteByPedido(id) ret = order.delete() flash(ret, 'info') return redirect(url_for('order.index')) title = 'Deseja realmente deletar o pedido ' + str(order.id) + '?' return render_template('order_delete.html', orderId=id, title=title), 200
async def _getOrders(self, orderFilter: 'OrderRepository.Filter', currency: str) -> List[Order]: multiplier = await productRepository.getCurrencyMultiplier(currency) if multiplier is None: raise Exception(f'Invalid currency {currency}') # implementing select with M2M using aggregation instead of subquery # so use raw SQL sql = f""" SELECT orders.id, min(orders.user_id), min(orders.name), min(orders.surname), min(orders.status)::text, min(orders.shipping_price) * {multiplier}, min(orders.address), json_agg(json_build_object( 'id', products.id, 'name', products.name, 'picture', products.picture, 'price', products.price_dollar * {multiplier}, 'amount', order_product_link.amount )) FROM orders JOIN order_product_link ON orders.id = order_product_link.order_id JOIN products ON order_product_link.product_id = products.id {orderFilter.getRawCond()} GROUP BY orders.id ORDER BY orders.id ASC LIMIT {orderFilter.limit} OFFSET {orderFilter.offset} """ result = await databaseClient.query(sql) return [ Order( id=row[0], userId=row[1], name=row[2], surname=row[3], status=Order.Status[row[4]], shippingPrice=row[5].normalize(), address=row[6], products=[self._productInfoFromDict(prod) for prod in row[7]]) for row in result ]
def rent_car(self, new_order): number, customer_id, lp_number, category, pickup_date, return_date, price, insurance, actual_return_date = str( new_order).split(",") #number = '', customer_id = '', lp_number = '', category = '', pickup_date = '', return_date = '', price = '', insurance = '' # self.__order_repo.__category = category # self.__order_repo.__pickup_date = pickup_date # self.__order_repo.__return_date = return_date # self.__order_repo.__customer_id = customer_id # self.__order_repo.__insurance = insurance # self.__order_repo.number = self.find_next_order_number() days = self.number_of_days(pickup_date, return_date) number = self.find_next_order_number() available_car_lp = self.find_available_car(category, pickup_date, return_date) lp_number = available_car_lp price = self.__price_service.calculate_price_for_order( category, days, insurance) order = Order(number, customer_id, lp_number, category, pickup_date, return_date, price, insurance, actual_return_date) self.__order_repo.price = price self.__order_repo.add_order(order)
def delete(id): client = Client() ret = client.get(id) if not client.id: flash(ret, 'info') return redirect(url_for('client.index')) order = Order() has = order.hasByUser(session.get('user_id')) if has: flash( 'O usuário não pode ser deletado pois existe algum pedido relacionado à ele.', 'info') return redirect(url_for('client.index')) if request.method == 'POST': ret = client.delete() flash(ret, 'info') return redirect(url_for('client.index')) title = 'Deseja realmente deletar o usuário ' + client.nome + '?' return render_template('client_delete.html', clientId=id, title=title), 200
def report(id): order = Order() ret = order.get(id) if not order.id: flash(ret, 'info') return redirect(url_for('order.index')) order_p = OrderProduct() products = order_p.getByOrderId(order.id) images = [] for product in products: images.append(b64encode(product[7]).decode("utf-8")) ren = render_template('order_report.html', products=products, images=images, order=order) pdf = pdfkit.from_string(ren, False) response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers[ 'Content-Disposition'] = 'attachement; filename=relatorio-pedido.pdf' return response
description="""Experimental and music that was a slow and producer for the first time decayed in the other techno miniatur of ‘The House Sex The Arts (The Earth)’, and the modular sense of sky artists and the short of his 1980 styles in the studio and story of the most most distance that was a proper interesting In Kasm and deep and strongly of the most pace of the sense of recordings and the start of the results that was some of the end""", mediums=[tape, vinyl, download] ) Record( artist="First", title="Title", cover="/images/eleven.png", description="""Electronic music for those Italy self-time recorded and just a fully still for our media and the sound all and complete the parts of the more artist and the separate strings of ‘The Moon’. The sense of the flute of the arti in a sense of the master off the still recordings of the still recordings Unsitting artists of the strong strong screwed contrastion with the strrike mind of ‘Pattern’ and the slow and graniste based sublime styled sounds of soundtrack and synthesis and the sounds of style to Japanese decades""", mediums=[tape, vinyl, cd, download] ) Record( artist="First", title="Title", cover="/images/twelve.png", description="""The introspective sound, while “the big timbre not preservations of modern parts, and time and compositions and contemporary soundscape with the string and the most successful music to the recording of the same album is a small descent of party another stepper found the extended debut artist and t Compositional abstract space and the story descent that explores the steel of the sustain of the songs he captures now many of Present Kultzzelle of the studio and stry footwork a series to the sound of sounds and technoid charge and sense of all deeper sound that was a careful of the contemporary""", mediums=[cd, download] ) Order( records=[first, second] ) db.commit()
def seed_db(): from models.User import User from models.Store import Store from models.Product import Product from models.Customer import Customer from models.Order import Order from main import bcrypt from faker import Faker faker = Faker() users = [] stores = [] products = [] customers = [] for i in range(5): user = User() user.email = f"test{i+1}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") user.isAdmin = False db.session.add(user) users.append(user) db.session.commit() store = Store() store.storename = faker.bs() store.firstname = faker.first_name() store.lastname = faker.last_name() store.user_id = users[i].id db.session.add(store) stores.append(store) db.session.commit() for j in range(5): product = Product() product.title = faker.numerify(text="Duck ###") product.price = faker.random_int(min=5, max=200, step=5) product.store_id = stores[i].id db.session.add(product) products.append(product) db.session.commit() for j in range(5): customer = Customer() customer.firstname = faker.first_name() customer.lastname = faker.last_name() customer.email = faker.ascii_email() customer.phone = faker.phone_number() customer.store_id = stores[i].id db.session.add(customer) customers.append(customer) db.session.commit() for k in range(5): order = Order() order.order_placed = choice([True, False]) order.customer_id = choice(customers).id db.session.add(order) db.session.commit() for m in range(3): order.orders_products.append(choice(products)) db.session.commit() customers = [] db.session.commit() print("Tables seeded")