def funds(): form = AddFundsForm() if request.method == 'POST': # 1. if not form.validate_on_submit(): flash(u'Invalid input') return render_template('add_funds.html', form=form) # form is validated now process add funds added_funds = float(request.form['funds']) bitcoins = float(request.form['Bitcoin']) dogecoins = float(request.form['Dogecoin']) c.atomic_add('users', g.user_email, {'Bitcoin' : bitcoins, 'Dogecoin' : dogecoins, 'funds' : added_funds}) # 3. # When a user adds funds we need to reprocess his orders as there may # be some orders he has placed that were not executed due to # insufficient resources. # No transaction support for the search() function yet :( pending_orders = c.search('orders', {'user_email' : g.user_email, 'is_complete' : 0}) x = c.begin_transaction() for order in pending_orders: order_book.process_order(order['order_id'], x) x.commit() # 4. flash(u'Added funds successfully') return redirect(url_for('funds')) # 5. return render_template('add_funds.html', form=form)
def trade(): form = TransactionForm() if request.method == 'POST': # 1. if not form.validate_on_submit(): flash(u'Invalid input in form') return render_template('trade.html', form=form) # User I/P not valid # 2. order_id = str(uuid.uuid4()) action = action_dict[int(request.form['action'])][1] currency = currency_dict[int(request.form['currency'])][1] quantity = float(request.form['quantity']) order_type = order_type_dict[int(request.form['order_type'])][1] expiry = order_expiry_dict[int(request.form['expiry'])][1] rate = 0.0 if order_type == "For Price": rate = float(request.form['rate']) # Sanity check to see if input is invalid if quantity <= 0.0 or (rate <= 0.0 and order_type == 'For Price'): flash(u'Invalid input in form') return render_template('trade.html', form=form) # User I/P not valid if expiry == 'Good Until Canceled': expiry = 0 elif expiry == 'Fill or Kill': expiry = 1 elif expiry == 'Day Only': expiry = int(datetime.now().strftime("%s")) + 86400 try: c.put( 'orders', order_id, { 'action': action, 'currency': currency, 'quantity_outstanding': quantity, 'quantity_fulfilled': 0.0, 'order_type': order_type, 'rate': rate, 'expiry': expiry, 'is_complete': 0, 'user_email': g.user_email }) # 3. x = c.begin_transaction() order_book.process_order(order_id, x) x.commit() flash(u'Successfully placed order') except: c.put('orders', order_id, {'is_complete': 3}) flash(u'Order Killed') return redirect(url_for('trade')) # This is a new request. Not a POST or validation return render_template('trade.html', form=form)
def manage_dogecoin(): x = c.begin_transaction() user_data = x.get('users', g.user_email) pub_key = user_data['dogecoin_address'] form = SendDogecoinForm() if request.method == 'POST': if not form.validate_on_submit(): flash(u'Invalid Input') else: input_address = str(request.form['address']).strip() try: addr = CDogecoinAddress(input_address) amount = float(request.form['amount']) if amount == 0.0: raise user_balance = x.get('users', g.user_email)['Dogecoin'] if amount > user_balance: flash('Insufficient Funds') else: x.put('dogecoin_txns', datetime.now(), {'pub_key': input_address, 'amount': amount, 'txid': '', 'email': g.user_email}) #x.put('users', g.user_email, {'Dogecoin': (user_balance - amount)}) x.atomic_sub('users', g.user_email, {'Dogecoin': amount}) flash(u'Your transaction for %s to %s is pending' % (amount, input_address)) except Exception as inst: print inst error_string = "Couldn't process send. " if type(inst) == dogecoin.base58.Base58ChecksumError: error_string += "Invalid Address!" elif type(inst) == dogecoin.rpc.JSONRPCException: error_string += "Insufficient Funds!" flash(u'%s' % (error_string)) if user_data['bitcoin_address'] == '': return "<div class='code'>We are still assigning you an address.<br/> Contact [email protected] if you continue to see this.</div>" # Fetch UTXO for the user's address confirmed = c.get('users', g.user_email)['Dogecoin'] pending = 0.0 addrs=pub_key response = requests.get('https://chain.so/api/v2/get_tx_unspent/DOGETEST/' + addrs) if response.status_code != 200: return "We're facing issues with our Dogecoin API, please try again in a bit. :(" content = response.json() txns = content['data']['txs'] for txn in txns: pending += float(str(txn['value'])) # Fetch transactions all_transactions = c.search('dogecoin_txns', {'email': g.user_email}) txns = [dict(row) for row in all_transactions] x.commit() return render_template('dogecoin.html', pub_key=pub_key, confirmed="%0.8f" % (confirmed), pending="%0.8f" % (pending), txns=txns, form=form)
def manage_bitcoin(): x = c.begin_transaction() user_data = x.get('users', g.user_email) pub_key = user_data['bitcoin_address'] form = SendBitcoinForm() if request.method == 'POST': if not form.validate_on_submit(): flash(u'Invalid Input') else: input_address = str(request.form['address']).strip() try: addr = CBitcoinAddress(input_address) amount = float(request.form['amount']) if amount == 0.0: raise user_balance = x.get('users', g.user_email)['Bitcoin'] if amount > user_balance: flash('Insufficient Funds') else: x.put('bitcoin_txns', datetime.now(), {'pub_key': input_address, 'amount': amount, 'txid': '', 'email': g.user_email}) #x.put('users', g.user_email, {'Bitcoin': (user_balance - amount)}) x.atomic_sub('users', g.user_email, {'Bitcoin': amount}) flash(u'Your transaction for %s to %s is pending' % (amount, input_address)) except Exception as inst: print inst error_string = "Couldn't process send. " if type(inst) == bitcoin.base58.Base58ChecksumError: error_string += "Invalid Address!" elif type(inst) == bitcoin.rpc.JSONRPCException: error_string += "Insufficient Funds!" flash(u'%s' % (error_string)) if user_data['bitcoin_address'] == '': return "<div class='code'>We are still assigning you an address.<br/> Contact [email protected] if you continue to see this.</div>" # Fetch UTXO for the user's address confirmed = c.get('users', g.user_email)['Bitcoin'] pending = 0.0 addr = [] addr.append(pub_key) txns = rpc.listunspent(addrs=addr) for txn in txns: pending += float(txn['amount'])/COIN # Fetch transactions all_transactions = c.search('bitcoin_txns', {'email': g.user_email}) txns = [dict(row) for row in all_transactions] x.commit() return render_template('bitcoin.html', pub_key=pub_key, confirmed="%0.8f" % (confirmed), pending="%0.8f" % (pending), txns=txns, form=form)
def trade(): form = TransactionForm() if request.method == 'POST': # 1. if not form.validate_on_submit(): flash(u'Invalid input in form') return render_template('trade.html', form=form)# User I/P not valid # 2. order_id = str(uuid.uuid4()) action = action_dict[int(request.form['action'])][1] currency = currency_dict[int(request.form['currency'])][1] quantity = float(request.form['quantity']) order_type = order_type_dict[int(request.form['order_type'])][1] expiry = order_expiry_dict[int(request.form['expiry'])][1] rate = 0.0 if order_type == "For Price": rate = float(request.form['rate']) # Sanity check to see if input is invalid if quantity <= 0.0 or ( rate <= 0.0 and order_type == 'For Price'): flash(u'Invalid input in form') return render_template('trade.html', form=form)# User I/P not valid if expiry == 'Good Until Canceled': expiry = 0 elif expiry == 'Fill or Kill': expiry = 1 elif expiry == 'Day Only': expiry = int(datetime.now().strftime("%s")) + 86400 try: c.put('orders', order_id, {'action' : action, 'currency' : currency, 'quantity_outstanding' : quantity, 'quantity_fulfilled' : 0.0, 'order_type' : order_type, 'rate' : rate, 'expiry' : expiry, 'is_complete' : 0, 'user_email' : g.user_email}) # 3. x = c.begin_transaction() order_book.process_order(order_id, x) x.commit() flash(u'Successfully placed order') except: c.put('orders', order_id, {'is_complete' : 3}) flash(u'Order Killed') return redirect(url_for('trade')) # This is a new request. Not a POST or validation return render_template('trade.html', form=form)
def process_orders(): users = c.search('users', {}) user_emails = [] for user in users: user_emails.append(user['email']) for user_email in user_emails: x = c.begin_transaction() pending_orders = c.search('orders', {'user_email' : user_email, 'is_complete' : 0}) for order in pending_orders: order_book.process_order(order['order_id'], x) x.commit() flash(u'Finished reprocessing orders') return redirect(url_for('admin_home'))
def process_orders(): users = c.search('users', {}) user_emails = [] for user in users: user_emails.append(user['email']) for user_email in user_emails: x = c.begin_transaction() pending_orders = c.search('orders', { 'user_email': user_email, 'is_complete': 0 }) for order in pending_orders: order_book.process_order(order['order_id'], x) x.commit() flash(u'Finished reprocessing orders') return redirect(url_for('admin_home'))
def funds(): form = AddFundsForm() if request.method == 'POST': # 1. if not form.validate_on_submit(): flash(u'Invalid input') return render_template('add_funds.html', form=form) # form is validated now process add funds added_funds = float(request.form['funds']) bitcoins = float(request.form['Bitcoin']) dogecoins = float(request.form['Dogecoin']) c.atomic_add('users', g.user_email, { 'Bitcoin': bitcoins, 'Dogecoin': dogecoins, 'funds': added_funds }) # 3. # When a user adds funds we need to reprocess his orders as there may # be some orders he has placed that were not executed due to # insufficient resources. # No transaction support for the search() function yet :( pending_orders = c.search('orders', { 'user_email': g.user_email, 'is_complete': 0 }) x = c.begin_transaction() for order in pending_orders: order_book.process_order(order['order_id'], x) x.commit() # 4. flash(u'Added funds successfully') return redirect(url_for('funds')) # 5. return render_template('add_funds.html', form=form)
def delete_or_modify_order(): form = ModifyTransactionForm() if request.form.has_key('order_id_to_modify'): # This is a mew modification request from the View Orders Page # 1.1 Initialize the form values order_id_to_modify = url_safe_serializer.loads(request.form['order_id_to_modify']) order_to_modify = c.get('orders', order_id_to_modify) form = ModifyTransactionForm(order_id = request.form['order_id_to_modify'], action = get_action_id(order_to_modify['action']), currency = get_currency_id(order_to_modify['currency']), order_type = get_order_type_id(order_to_modify['order_type']), quantity = order_to_modify['quantity_outstanding'], rate = order_to_modify['rate'], expiry=get_expiry_id(order_to_modify['expiry'])) form.order_id.data = request.form['order_id_to_modify'] elif not request.form.has_key('modify_or_delete'): flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) elif request.form['modify_or_delete'] not in ('Modify', 'Delete'): flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) elif request.form['modify_or_delete'] == "Delete": order_id_to_delete = url_safe_serializer.loads(request.form['order_id']) order_to_delete = c.get('orders', order_id_to_delete) if order_to_delete == None: flash(u'Order Deletion Unsuccessful. Please Try again') else: c.put('orders', order_id_to_delete, {'is_complete' : 2}) flash(u'Order Deletion Successful') return redirect(url_for('book')) elif request.form.has_key('order_id'): order_id_to_modify = url_safe_serializer.loads(request.form['order_id']) order_to_modify = c.get('orders', order_id_to_modify) # This is a request to modify the order. # 2.1 Validate the form. if order_to_modify == None: flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) if not form.validate_on_submit(): flash(u'Invalid input in form') return render_template('modify_order.html', form=form)# User I/P not valid # 2.2 Its a valid form redirect make the modification if possible order_id = order_id_to_modify quantity = float(request.form['quantity']) order_type = order_type_dict[int(request.form['order_type'])][1] expiry = order_expiry_dict[int(request.form['expiry'])][1] rate = 0.0 if order_type == "For price": rate = float(request.form['rate']) # Sanity check to see if input is invalid if quantity <= 0.0 or ( rate <= 0.0 and order_type == 'For Price'): flash(u'Invalid input in form') return render_template('modify_order.html', form=form)# User I/P not valid if expiry == 'Good Until Canceled': expiry = 0 elif expiry == 'Fill or Kill': expiry = 1 elif expiry == 'Day Only': expiry = int(datetime.now().strftime("%s")) + 86400 try: c.put('orders', order_id_to_modify, {'quantity_outstanding' : quantity, 'rate' : rate, 'order_type' : order_type, 'expiry' : expiry}) x = c.begin_transaction() order_book.process_order(order_id, x) x.commit() flash(u'Successfully modified order') except: c.put('orders', order_id_to_modify, {'is_complete' : 3}) flash(u'Order Killed') return redirect(url_for('book')) else: # This should not happen. A request to this method must always have a valid order_id. # This request may be malicious. Redirect to Home page return redirect(url_for('index')) return render_template('modify_order.html', form=form)
def manage_dogecoin(): x = c.begin_transaction() user_data = x.get('users', g.user_email) pub_key = user_data['dogecoin_address'] form = SendDogecoinForm() if request.method == 'POST': if not form.validate_on_submit(): flash(u'Invalid Input') else: input_address = str(request.form['address']).strip() try: addr = CDogecoinAddress(input_address) amount = float(request.form['amount']) if amount == 0.0: raise user_balance = x.get('users', g.user_email)['Dogecoin'] if amount > user_balance: flash('Insufficient Funds') else: x.put( 'dogecoin_txns', datetime.now(), { 'pub_key': input_address, 'amount': amount, 'txid': '', 'email': g.user_email }) #x.put('users', g.user_email, {'Dogecoin': (user_balance - amount)}) x.atomic_sub('users', g.user_email, {'Dogecoin': amount}) flash(u'Your transaction for %s to %s is pending' % (amount, input_address)) except Exception as inst: print inst error_string = "Couldn't process send. " if type(inst) == dogecoin.base58.Base58ChecksumError: error_string += "Invalid Address!" elif type(inst) == dogecoin.rpc.JSONRPCException: error_string += "Insufficient Funds!" flash(u'%s' % (error_string)) if user_data['bitcoin_address'] == '': return "<div class='code'>We are still assigning you an address.<br/> Contact [email protected] if you continue to see this.</div>" # Fetch UTXO for the user's address confirmed = c.get('users', g.user_email)['Dogecoin'] pending = 0.0 addrs = pub_key response = requests.get( 'https://chain.so/api/v2/get_tx_unspent/DOGETEST/' + addrs) if response.status_code != 200: return "We're facing issues with our Dogecoin API, please try again in a bit. :(" content = response.json() txns = content['data']['txs'] for txn in txns: pending += float(str(txn['value'])) # Fetch transactions all_transactions = c.search('dogecoin_txns', {'email': g.user_email}) txns = [dict(row) for row in all_transactions] x.commit() return render_template('dogecoin.html', pub_key=pub_key, confirmed="%0.8f" % (confirmed), pending="%0.8f" % (pending), txns=txns, form=form)
def manage_bitcoin(): x = c.begin_transaction() user_data = x.get('users', g.user_email) pub_key = user_data['bitcoin_address'] form = SendBitcoinForm() if request.method == 'POST': if not form.validate_on_submit(): flash(u'Invalid Input') else: input_address = str(request.form['address']).strip() try: addr = CBitcoinAddress(input_address) amount = float(request.form['amount']) if amount == 0.0: raise user_balance = x.get('users', g.user_email)['Bitcoin'] if amount > user_balance: flash('Insufficient Funds') else: x.put( 'bitcoin_txns', datetime.now(), { 'pub_key': input_address, 'amount': amount, 'txid': '', 'email': g.user_email }) #x.put('users', g.user_email, {'Bitcoin': (user_balance - amount)}) x.atomic_sub('users', g.user_email, {'Bitcoin': amount}) flash(u'Your transaction for %s to %s is pending' % (amount, input_address)) except Exception as inst: print inst error_string = "Couldn't process send. " if type(inst) == bitcoin.base58.Base58ChecksumError: error_string += "Invalid Address!" elif type(inst) == bitcoin.rpc.JSONRPCException: error_string += "Insufficient Funds!" flash(u'%s' % (error_string)) if user_data['bitcoin_address'] == '': return "<div class='code'>We are still assigning you an address.<br/> Contact [email protected] if you continue to see this.</div>" # Fetch UTXO for the user's address confirmed = c.get('users', g.user_email)['Bitcoin'] pending = 0.0 addr = [] addr.append(pub_key) txns = rpc.listunspent(addrs=addr) for txn in txns: pending += float(txn['amount']) / COIN # Fetch transactions all_transactions = c.search('bitcoin_txns', {'email': g.user_email}) txns = [dict(row) for row in all_transactions] x.commit() return render_template('bitcoin.html', pub_key=pub_key, confirmed="%0.8f" % (confirmed), pending="%0.8f" % (pending), txns=txns, form=form)
def delete_or_modify_order(): form = ModifyTransactionForm() if request.form.has_key('order_id_to_modify'): # This is a mew modification request from the View Orders Page # 1.1 Initialize the form values order_id_to_modify = url_safe_serializer.loads( request.form['order_id_to_modify']) order_to_modify = c.get('orders', order_id_to_modify) form = ModifyTransactionForm( order_id=request.form['order_id_to_modify'], action=get_action_id(order_to_modify['action']), currency=get_currency_id(order_to_modify['currency']), order_type=get_order_type_id(order_to_modify['order_type']), quantity=order_to_modify['quantity_outstanding'], rate=order_to_modify['rate'], expiry=get_expiry_id(order_to_modify['expiry'])) form.order_id.data = request.form['order_id_to_modify'] elif not request.form.has_key('modify_or_delete'): flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) elif request.form['modify_or_delete'] not in ('Modify', 'Delete'): flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) elif request.form['modify_or_delete'] == "Delete": order_id_to_delete = url_safe_serializer.loads( request.form['order_id']) order_to_delete = c.get('orders', order_id_to_delete) if order_to_delete == None: flash(u'Order Deletion Unsuccessful. Please Try again') else: c.put('orders', order_id_to_delete, {'is_complete': 2}) flash(u'Order Deletion Successful') return redirect(url_for('book')) elif request.form.has_key('order_id'): order_id_to_modify = url_safe_serializer.loads( request.form['order_id']) order_to_modify = c.get('orders', order_id_to_modify) # This is a request to modify the order. # 2.1 Validate the form. if order_to_modify == None: flash(u'Order Modification Unsuccessful. Please Try again') return redirect(url_for('book')) if not form.validate_on_submit(): flash(u'Invalid input in form') return render_template('modify_order.html', form=form) # User I/P not valid # 2.2 Its a valid form redirect make the modification if possible order_id = order_id_to_modify quantity = float(request.form['quantity']) order_type = order_type_dict[int(request.form['order_type'])][1] expiry = order_expiry_dict[int(request.form['expiry'])][1] rate = 0.0 if order_type == "For price": rate = float(request.form['rate']) # Sanity check to see if input is invalid if quantity <= 0.0 or (rate <= 0.0 and order_type == 'For Price'): flash(u'Invalid input in form') return render_template('modify_order.html', form=form) # User I/P not valid if expiry == 'Good Until Canceled': expiry = 0 elif expiry == 'Fill or Kill': expiry = 1 elif expiry == 'Day Only': expiry = int(datetime.now().strftime("%s")) + 86400 try: c.put( 'orders', order_id_to_modify, { 'quantity_outstanding': quantity, 'rate': rate, 'order_type': order_type, 'expiry': expiry }) x = c.begin_transaction() order_book.process_order(order_id, x) x.commit() flash(u'Successfully modified order') except: c.put('orders', order_id_to_modify, {'is_complete': 3}) flash(u'Order Killed') return redirect(url_for('book')) else: # This should not happen. A request to this method must always have a valid order_id. # This request may be malicious. Redirect to Home page return redirect(url_for('index')) return render_template('modify_order.html', form=form)