Best Python code snippet using playwright-python
security.py
Source:security.py
...81 print e;82 print '----------------End-----------------'83 return render(request, 'security_add.html', data)84@csrf_exempt85def save_security_details(request):86 print '==============security save===================',request.POST87 #pdb.set_trace()88 try:89 print request.POST90 if request.method == "POST":91 ticker=check_security_bloomer_ticker_insave(request.POST['txtbloombergticker'])92 if ticker=='not_available':93 security_obj = Security_Details(94 asset_sub_class_id=Asset_Sub_Class_Details.objects.get(asset_sub_class_id=request.POST['selectAssetSubClass']),95 security_name=request.POST['txtSecurity'],96 security_isin=request.POST['txtIsin'],97 security_type=SecurityType.objects.get(securitytype_id=request.POST['selectType']),98 security_benchmark_index=BenchmarkIndex.objects.get(99 benchmarkindex_id=request.POST['selectBenchmarkIndex']),100 security_bloomer_ticker=request.POST['txtbloombergticker'],101 security_security_state=SecurityState.objects.get(state_id=request.POST['selectSecurityState']),102 security_local_currency=Currency.objects.get(currency_id=request.POST['selectCurrency']),103 country_id=SecurityCountry.objects.get(country_id=request.POST['selectCountry']),104 sector_id=SecuritySector.objects.get(sector_id=request.POST['selectSector']),105 security_beta=check_float_val(request.POST['txtBeta']),106 security_lot_size=check_int_val(request.POST['txtLotSize']),107 record_status='Active',108 security_created_by=request.session['login_user'],109 security_updated_by=request.session['login_user'],110 security_updated_date=datetime.datetime.now(),111 security_created_date=datetime.datetime.now()112 )113 security_obj.save()114 result={'success':'true'}115 elif ticker=='available':116 result={'success':'ticker_available'}117 else:118 raise "ticker error!"119 except Exception, e:120 print 'Exception: ' + e121 result={'success':'false'}122 #return redirect('/open-security-page/')123 return HttpResponse(json.dumps(result), content_type='application/json')124@csrf_exempt125def update_security_details(request):126 try:127 #pdb.set_trace()128 print request.POST129 if request.method == "POST":130 ticker=check_security_bloomer_ticker_inupdate(request.POST['txtbloombergticker'],request.POST['txtSecurity_id'])131 if ticker=='not_available':132 security_obj=Security_Details.objects.get(security_id=request.POST['txtSecurity_id'])133 security_obj.record_status='Inactive'134 security_obj.security_updated_by=request.session['login_user']135 security_obj.security_updated_date=datetime.datetime.now().date()136 security_obj.save()137 security_new_obj=Security_Details()138 security_new_obj.asset_sub_class_id=Asset_Sub_Class_Details.objects.get(asset_sub_class_id=request.POST['selectAssetSubClass'])139 security_new_obj.security_name=request.POST['txtSecurity']140 security_new_obj.security_isin=request.POST['txtIsin']141 security_new_obj.security_type=SecurityType.objects.get(securitytype_id=request.POST['selectType'])142 security_new_obj.security_bloomer_ticker=request.POST['txtbloombergticker']143 security_new_obj.security_benchmark_index=BenchmarkIndex.objects.get(benchmarkindex_id=request.POST['selectBenchmarkIndex'])144 security_new_obj.security_security_state=SecurityState.objects.get(state_id=request.POST['selectSecurityState'])145 security_new_obj.security_local_currency=Currency.objects.get(currency_id=request.POST['selectCurrency'])146 security_new_obj.country_id=SecurityCountry.objects.get(country_id=request.POST['selectCountry'])147 security_new_obj.sector_id=SecuritySector.objects.get(sector_id=request.POST['selectSector'])148 security_new_obj.security_beta=check_float_val(request.POST['txtBeta'])149 #print '==========>value check',check_float_val(request.POST['txtLotSize'])150 security_new_obj.security_lot_size=check_int_val(request.POST.get('txtLotSize'))151 security_new_obj.record_status='Active'152 security_new_obj.security_created_by=security_obj.security_created_by153 security_new_obj.security_created_date=security_obj.security_created_date154 security_new_obj.security_updated_by=request.session['login_user']155 security_new_obj.security_updated_date=datetime.datetime.now().date()156 security_new_obj.save()157 security_price_list=Security_Price_Details.objects.filter(security_id=security_obj,record_status='Active')158 if security_price_list:159 for price in security_price_list:160 price.security_id=security_new_obj161 price.save()162 trade_list=Trade_Details.objects.filter(security_id=security_obj,record_status='Active')163 if trade_list:164 for trade in trade_list:165 trade.security_id=security_new_obj166 trade.save()167 result={'success':'true'}168 elif ticker=='available':169 result={'success':'ticker_available'}170 else:171 raise "ticker error!"172 except Exception, e:173 print 'Security.py|update_security_details|Exception: ', e174 result={'success':'false'}175 return HttpResponse(json.dumps(result), content_type='application/json')176def view_security_details(request):177 #pdb.set_trace()178 print '===================view security==============='179 try:180 if request.method=='GET':181 print "security_id ",request.GET.get('security_id')182 flag = request.GET.get('flag', '')183 print "FLAG",flag184 security_obj=Security_Details.objects.get(security_id=request.GET['security_id'])185 print '====security Object==='186 print security_obj187 asset_class_list = add_to_dropdown(Asset_Class_Details)188 sub_asset_class_list = Asset_Sub_Class_Details.objects.filter(asset_class_id=security_obj.asset_sub_class_id.asset_class_id)189 benchmarkindex_list = add_to_dropdown(BenchmarkIndex)190 country_list = add_to_dropdown(SecurityCountry)...
trades.py
Source:trades.py
1import pdb2import re3from django.shortcuts import render4from zamapp.models import *5from django.http import HttpResponse6import json7from django.shortcuts import render_to_response8# from django.core.context_processors import csrf9from django.views.decorators.csrf import csrf_exempt10from datetime import date, timedelta11from zamapp.captcha_form import CaptchaForm12from django.template import RequestContext13# Create your views here.14def open_trade(request):15 if request.user.is_authenticated():16 return render(request, 'trade_index.html')17 else:18 form = CaptchaForm()19 return render_to_response('login.html', dict(20 form=form21 ), context_instance=RequestContext(request))22def open_add_trade(request):23 security = []24 if request.user.is_authenticated():25 assets_class = Asset_Class_Details.objects.all()26 assets_sub_class = Asset_Sub_Class_Details.objects.all()27 security_obj = Security_Details.objects.filter(record_status = "Active").values_list('security_name').distinct()28 for sec in security_obj:29 security.append({'value' : sec[0] , 'data' : sec[0]})30 security = json.dumps(security)31 #print security32 data = {'securities': security}33 return render(request, 'trade_add.html', data)34 else:35 form = CaptchaForm()36 return render_to_response('login.html', dict(37 form=form38 ), context_instance=RequestContext(request))39@csrf_exempt40def view_security_list(request):41 try:42 # pdb.set_trace()43 data_list = []44 search_txt = request.POST['search_txt']45 # print search_txt46 security_obj = Security_Details.objects.filter(security_name=search_txt ,record_status = "Active")47 # print security_obj48 if security_obj:49 for security in security_obj:50 data_obj = {51 'security': security.security_name,52 'b_ticker': security.security_bloomer_ticker,53 'asset_cls': security.asset_sub_class_id.asset_class_id.asset_class_name,54 'asset_sub_cls': security.asset_sub_class_id.asset_sub_class_name,55 'country': security.security_local_currency.country_id.country_name,56 'add_btn': '<button id="' + security.security_name + '" name="' + str(57 security.security_id) + '" value="'+ str(security.security_lot_size) +'" onclick="add_trade_form(this.id,this.name,this.value)" class="btn btn-default btn-primary2 btn-xs btn-outline">Add</button>'58 }59 data_list.append(data_obj)60 data = {'success': 'true', 'data_list': data_list}61 #print data62 else:63 print "None"64 data = {'success': 'false'}65 # print data66 except Security_Details.DoesNotExist as e:67 print 'Exception', e68 data = {'success': 'false'}69 except Exception as e:70 print 'Exception', e71 data = {'success': 'false'}72 return HttpResponse(json.dumps(data), content_type='application/json')73@csrf_exempt74def check_price(request):75 try:76 trade_quantity = 077 security_id = request.POST['sec_id']78 trade_obj = Trade_Details.objects.filter(security_id = security_id, record_status="Active")79 for trade in trade_obj:80 if trade.buy_sell_indicator == "Buy":81 trade_quantity = trade_quantity + int(trade.trade_security_quantity)82 elif trade.buy_sell_indicator == "Sell":83 trade_quantity = trade_quantity - int(trade.trade_security_quantity)84 print "Trade Quantity: ",trade_quantity85 security_price = Security_Price_Details.objects.filter(security_id = security_id)86 if security_price:87 security_price = "Yes"88 else:89 security_price = "No"90 data = {"security_price" : security_price, "trade_quantity" : trade_quantity}91 except Exception as e:92 print 'Exception', e93 return HttpResponse(json.dumps(data), content_type='application/json')94@csrf_exempt95def view_security_lists(request):96 try:97 # pdb.set_trace()98 data_list = []99 search_txt = request.POST['search_txt']100 # print search_txt101 security_obj = Security_Details.objects.filter(security_name__istartswith=search_txt ,record_status = "Active")102 # print security_obj103 if security_obj:104 for security in security_obj:105 data_obj = {106 'security': security.security_name,107 'b_ticker': security.security_bloomer_ticker,108 'asset_cls': security.asset_sub_class_id.asset_class_id.asset_class_name,109 'asset_sub_cls': security.asset_sub_class_id.asset_sub_class_name,110 'country': security.security_local_currency.country_id.country_name,111 'add_btn': '<button id="' + security.security_name + '" name="' + str(112 security.security_id) + '" value="'+ str(security.security_lot_size) +'" onclick="add_trade_form(this.id,this.name,this.value)" class="btn btn-default btn-primary2 btn-xs btn-outline">Add</button>'113 }114 data_list.append(data_obj)115 data = {'success': 'true', 'data_list': data_list}116 print data117 else:118 print "None"119 data = {'success': 'false'}120 # print data121 except Security_Details.DoesNotExist as e:122 print 'Exception', e123 data = {'success': 'false'}124 except Exception as e:125 print 'Exception', e126 data = {'success': 'false'}127 return HttpResponse(json.dumps(data), content_type='application/json')128def open_view_trade(request):129 try:130 # pdb.set_trace()131 trade = request.GET.get('trade_id')132 type = request.GET.get('type')133 trade_quantity = 0134 trade_obj = Trade_Details.objects.get(trade_id=trade)135 security_id = trade_obj.security_id.security_id136 trades = Trade_Details.objects.filter(security_id = security_id, record_status="Active")137 for trade in trades:138 if trade.buy_sell_indicator == "Buy":139 trade_quantity = trade_quantity + int(trade.trade_security_quantity)140 elif trade.buy_sell_indicator == "Sell":141 trade_quantity = trade_quantity - int(trade.trade_security_quantity)142 #print "Trade id: ", trade143 #print "Type: ", type144 trade_data = {145 'trade_id': trade_obj.trade_id,146 'trade_date': str(trade_obj.trade_date.strftime('%d/%m/%Y')),147 'buy_sell_indicator': trade_obj.buy_sell_indicator,148 'trade_security_quantity': trade_obj.trade_security_quantity,149 'trade_amount': trade_obj.trade_amount,150 'trade_price': trade_obj.trade_price,151 'fx_price': trade_obj.fx_price,152 'broker': trade_obj.broker,153 'lot_size': trade_obj.lot_size,154 'security_id': trade_obj.security_id.security_id,155 'security_name': trade_obj.security_id.security_name,156 'present_quantity' : trade_quantity157 }158 data = {'trade_obj': trade_data, 'type' : type}159 #print data160 except Exception, e:161 print 'Exception', e162 data = {'success': 'false'}163 return render(request, 'trade_view.html', data)164def open_add_bulk_trade(request):165 if request.user.is_authenticated():166 return render(request, 'trade_bulk_add.html')167 else:168 form = CaptchaForm()169 return render_to_response('login.html', dict(170 form=form171 ), context_instance=RequestContext(request))172@csrf_exempt173def asset_subclass(request):174 try:175 asset_id = request.GET.get('asset_id')176 asset_sub_obj = Asset_Sub_Class_Details.objects.filter(asset_class_id=asset_id)177 options = []178 for asset_sub in asset_sub_obj:179 options_data = '<option value=' + str(180 asset_sub.asset_sub_class_id) + '>' + asset_sub.asset_sub_class_name + '</option>'181 options.append(options_data)182 print options183 data = {'options': options}184 except Exception, e:185 print e186 data = {'success': 'false'}187 return HttpResponse(json.dumps(data), content_type='application/json')188@csrf_exempt189def append_security(request):190 try:191 asset_sub_id = request.GET.get('asset_sub_id')192 print asset_sub_id193 security_obj = Security_Details.objects.filter(asset_sub_class_id=asset_sub_id)194 print security_obj195 options = []196 for security in security_obj:197 options_data = '<option value=' + str(security.security_id) + '>' + security.security_name + '</option>'198 options.append(options_data)199 print options200 data = {'options': options}201 except Exception, e:202 print e203 data = {'success': 'false'}204 return HttpResponse(json.dumps(data), content_type='application/json')205@csrf_exempt206def get_price(request):207 try:208 security = request.POST['security_id']209 # print security210 security_price_obj = Security_Price_Details.objects.filter(security_id=security).order_by(211 '-security_price_created_date')212 s_id = security_price_obj.first()213 # sp_obj = Security_Price_Details.objects.get(security_id=s_id)214 security_price = s_id.security_last_price215 # print security_price216 data = {'success': 'true', 'security_price': security_price}217 except Exception, e:218 print e219 data = {'success': 'false'}220 return HttpResponse(json.dumps(data), content_type='application/json')221@csrf_exempt222def add_trade(request):223 try:224 print "adding trade"225 print request.POST226 a = 0227 date = request.POST.getlist('date')228 sec_id = request.POST.getlist('security_id')229 tr_type = request.POST.getlist('trade_type')230 quantity = request.POST.getlist('quantity')231 trade_price = request.POST.getlist('trade_price')232 fx_price = request.POST.getlist('fx_price')233 amount = request.POST.getlist('amount')234 broker = request.POST.getlist('broker')235 lot_size = request.POST.getlist('lot_size')236 for i in range(len(sec_id)):237 print type(amount[i])238 if date[i] == '':239 continue240 else:241 a = 1242 print date[i]243 security_obj = Security_Details.objects.get(security_id=sec_id[i])244 trade_obj = Trade_Details(245 security_id=security_obj,246 trade_date=datetime.strptime(date[i], '%d/%m/%Y').date(),247 buy_sell_indicator=tr_type[i],248 trade_security_quantity=quantity[i],249 trade_amount=amount[i],250 trade_price=trade_price[i],251 fx_price=fx_price[i],252 broker=broker[i],253 lot_size = lot_size[i],254 record_status="Active",255 trade_created_by=request.session['login_user'],256 trade_updated_by=request.session['login_user'],257 trade_created_date=datetime.now(),258 trade_updated_date=datetime.now(),259 )260 trade_obj.save()261 data = {'success': 'true', 'sts':a}262 except Exception, e:263 print e264 data = {'success': 'false'}265 return HttpResponse(json.dumps(data), content_type='application/json')266@csrf_exempt267def view_trades(request):268 trade_obj = Trade_Details.objects.filter(record_status="Active")269 trade_list = []270 for trade in trade_obj:271 view_btn = '<a href="/open-view-trade/?trade_id=' + str(272 trade.trade_id) + '&type=view" class="infont"> ' + '<i class="fa fa-eye"></i></i> </a>'273 edit_btn = '<a href="/open-view-trade/?trade_id=' + str(274 trade.trade_id) + '&type=edit" class="infont"> ' + '<i class="fa fa-edit"></i></i> </a>'275 delete_btn = '<a id="'+str(trade.trade_id)+'" onclick=delete_trade(this.id) class="infont"> ' + '<i class="fa fa-trash-o"></i></i> </a>'276 trade_data = {277 'date': str(trade.trade_date.strftime('%d/%m/%Y')),278 'security': trade.security_id.security_name,279 'trade_type': trade.buy_sell_indicator,280 'quantity': trade.trade_security_quantity,281 'trade_price': trade.trade_price,282 'fx_price': trade.fx_price,283 'trade_amount': trade.trade_amount,284 'broker': trade.broker,285 'view_btn': view_btn,286 'edit_btn': edit_btn,287 'delete_btn': delete_btn,288 }289 trade_list.append(trade_data)290 data = {'data': trade_list}291 #print data292 return HttpResponse(json.dumps(data), content_type='application/json')293@csrf_exempt294def edit_trade(request):295 try:296 print "editng trade"297 security_price_obj = Security_Details.objects.get(security_id=request.POST['security_id'])298 trade_obj = Trade_Details.objects.get(trade_id=request.POST['trade_id'])299 trade_obj.record_status = "Inactive"300 trade_obj.trade_updated_by = request.session['login_user']301 trade_obj.trade_updated_date = datetime.now()302 trade_obj.save()303 trade_new_obj = Trade_Details()304 trade_new_obj.security_id = security_price_obj305 trade_new_obj.trade_date = datetime.strptime(request.POST['date'], '%d/%m/%Y').date()306 trade_new_obj.buy_sell_indicator = request.POST['trade_type']307 trade_new_obj.trade_security_quantity = request.POST['quantity']308 trade_new_obj.trade_amount = request.POST['total_amount']309 trade_new_obj.record_status = "Active"310 trade_new_obj.trade_price = request.POST['trd_price']311 trade_new_obj.fx_price = request.POST['fx_price']312 trade_new_obj.broker = request.POST['broker']313 trade_new_obj.lot_size = request.POST['lot_size']314 trade_new_obj.trade_created_by = request.session['login_user']315 trade_new_obj.trade_created_date = datetime.now()316 trade_new_obj.trade_updated_by = request.session['login_user']317 trade_new_obj.trade_updated_date = datetime.now()318 trade_new_obj.save()319 # print trade_obj320 data = {'success': 'true'}321 except Exception, e:322 print e323 data = {'success': 'false'}324 return HttpResponse(json.dumps(data), content_type='application/json')325@csrf_exempt326def delete_trade(request):327 try:328 print "deleting trade"329 trade_obj = Trade_Details.objects.get(trade_id=request.POST['trade_id'])330 trade_obj.record_status = "Inactive"331 trade_obj.save()332 # print trade_obj333 data = {'success': 'true'}334 except Exception, e:335 print e336 data = {'success': 'false'}337 return HttpResponse(json.dumps(data), content_type='application/json')338@csrf_exempt339def add_bulk_trade(request):340 # pdb.set_trace()341 try:342 bulk_data = request.POST.get('totalData')343 bulk_data_info = json.loads(bulk_data)344 data_list = []345 trade_data = []346 check_list = []347 for data in bulk_data_info:348 security = data.get('Security*')349 b_ticker = data.get('Bloomberg Ticker*')350 as_cls = data.get('Asset Class*')351 as_sub_cls = data.get('Asset Sub Class*')352 quantity = data.get('Quantity*')353 trade_price = data.get('Trade Price*')354 fx_price = data.get('FX Price*')355 Trade_Type = data.get('Trade Type*')356 lot_size = data.get('Lot Size')357 total_amount = data.get('Total Amount')358 broker = data.get('Broker')359 status = '<td class="text-center "><span class="label label-danger " style="cursor: pointer;">Mismatch</span></td>'360 asset_obj = check_asset_obj(as_cls);361 if asset_obj == "error":362 asset_obj = '<td class="text-center "><span class="label label-danger ">' + as_cls + '</span></td>'363 as_sub_obj = "error"364 else:365 as_sub_obj = check_as_sub_obj(as_sub_cls,asset_obj);366 asset_obj = as_cls367 if as_sub_obj == "error":368 security_obj = "error"369 as_sub_obj = '<td class="text-center "><span class="label label-danger ">' + as_sub_cls + '</span></td>'370 else:371 security_obj = check_sec_obj(security,as_sub_obj,b_ticker);372 as_sub_obj = as_sub_cls373 if security_obj == "error" or security_obj == "Add Price":374 if security_obj == "error":375 security_obj = '<td class="text-center "><span class="label label-danger ">' + security + '</span></td>'376 blm_ticker = '<td class="text-center "><span class="label label-danger ">' + b_ticker + '</span></td>'377 status = '<td class="text-center "><span class="label label-danger" style="cursor: pointer;" title="Security not Found">' \378 'Mismatch</span></td>'379 elif security_obj == "Add Price":380 security_obj = '<td class="text-center "><span class="label label-danger ">' + security + '</span></td>'381 blm_ticker = '<td class="text-center "><span class="label label-danger ">' + b_ticker + '</span></td>'382 status = '<td class="text-center "><span class="label label-warning " style="cursor: pointer;" title="Please add price \nfor this security \nto add trade">' \383 'Add Price</span></td>'384 else:385 security_obj = security386 if data.get('Trade Type*') != "Buy" and data.get('Trade Type*') != "Sell" and data.get('Trade Type*') != "Sell Short" and data.get('Trade Type*') != "Cover Short":387 if data.get('Trade Type*') == "":388 Trade_Type = '<td class="text-center "><span class="label label-danger ">null</span></td>'389 else:390 Trade_Type = '<td class="text-center "><span class="label label-danger ">' + data.get(391 'Trade Type*') + '</span></td>'392 if quantity == "":393 quantity = '<td class="text-center "><span class="label label-danger ">null</span></td>'394 if trade_price == "":395 trade_price = '<td class="text-center "><span class="label label-danger ">null</span></td>'396 if fx_price == "":397 fx_price = '<td class="text-center "><span class="label label-danger ">null</span></td>'398 data_obj = {'date': data.get('Date*'),399 'security': security_obj,400 'b_ticker': blm_ticker,401 'as_cls': asset_obj,402 'as_sub_cls': as_sub_obj,403 'trade_type': Trade_Type,404 'quantity': quantity,405 'trade_price': trade_price,406 'fx_price': fx_price,407 'lot_size': lot_size,408 'total_amount': total_amount,409 'broker': broker,410 'status': status411 }412 data_list.append(data_obj)413 else:414 415 if security_obj and data.get('Date*') != "" and data.get('Trade Type*') == "Buy" or data.get(416 'Trade Type*') == "Sell" or data.get('Trade Type*') == "Sell Short" or data.get('Trade Type*') == "Cover Short" and data.get('Quantity*') != "" and data.get('Trade Price*') != "":417 #print "security_obj: ",security_obj418 trade_obj = {419 'security_obj':int(security_obj.security_id),420 'trade_type':data.get('Trade Type*'),421 'quantity':quantity422 }423 trade_data.append(trade_obj)424 425 data_obj = {'date': data.get('Date*'),426 'security': int(security_obj.security_id),427 'security_id': int(security_obj.security_id),428 'b_ticker': data.get('Bloomberg Ticker*'),429 'as_cls': asset_obj,430 'as_sub_cls': as_sub_obj,431 'trade_type': data.get('Trade Type*'),432 'quantity': quantity,433 'trade_price': trade_price,434 'fx_price': fx_price,435 'lot_size': lot_size,436 'total_amount': total_amount,437 'broker': broker,438 'status': status439 }440 check_list.append(data_obj) 441 442 #print "trade_data: ",trade_data443 444 chck_quantity = check_quantity(trade_data)445 flag = 0446 for check_trd in check_list:447 val = chck_quantity[check_trd['security']]448 if val < 0 :449 flag = 1450 check_trd['status'] = '<td class="text-center "><span class="label label-warning " style="cursor: pointer;" title="Sell trade quantity is\ngreater then buy trade\nquantity">' \451 'Invalid Data</span></td>'452 check_trd['trade_type'] = '<td class="text-center "><span class="label label-danger ">'+ check_trd['trade_type'] +'</span></td>'453 check_trd['quantity'] = '<td class="text-center "><span class="label label-danger ">'+ check_trd['quantity'] +'</span></td>'454 #print "Security.........false",check_trd['security']455 security = Security_Details.objects.get(security_id=check_trd['security'])456 check_trd['security'] = security.security_name457 else: 458 check_trd['status'] = '<td class="text-center "><span class="label label-success " style="cursor: pointer;">' \459 'Valid Data</span></td>'460 #print "Security.........ture",check_trd['security']461 security = Security_Details.objects.get(security_id=check_trd['security'])462 check_trd['security'] = security.security_name463 464 if flag == 1 or data_list != []:465 data_list.extend(check_list)466 else:467 sv_trade = save_trades(check_list,request)468 if sv_trade == "saved":469 data_list = []470 if data_list == []:471 data = {'success': 'true', 'data_list': data_list}472 else:473 data = {'success': 'false', 'data_list': data_list}474 except Exception as e:475 print "Exception: ",e476 data = {'success': 'false', 'data_list':''}477 return HttpResponse(json.dumps(data), content_type='application/json')478def check_sec_obj(security,as_sub_obj,b_ticker):479 try:480 sec_obj = Security_Details.objects.get(security_name=security,asset_sub_class_id=as_sub_obj,481 security_bloomer_ticker=b_ticker,record_status="Active")482 if sec_obj:483 sec_price = Security_Price_Details.objects.filter(security_id = sec_obj, record_status="Active")484 if sec_price:485 sec_obj = sec_obj486 else:487 sec_obj = "Add Price"488 except Security_Details.DoesNotExist, e:489 sec_obj = "error"490 #print sec_obj491 return sec_obj492def check_asset_obj(as_cls):493 try:494 ast_obj = Asset_Class_Details.objects.get(asset_class_name=as_cls,row_status="Active")495 except Asset_Class_Details.DoesNotExist, e:496 ast_obj = "error"497 return ast_obj498def check_as_sub_obj(as_sub_cls,asset_obj):499 try:500 ast_sub_obj = Asset_Sub_Class_Details.objects.get(asset_sub_class_name=as_sub_cls,501 asset_class_id = asset_obj,row_status="Active")502 except Asset_Sub_Class_Details.DoesNotExist, e:503 ast_sub_obj = "error"504 return ast_sub_obj505def check_quantity(trade_data):506 total_quantity = 0507 sec_list = []508 list2 = [] 509 dis = [] 510 511 for trade in trade_data:512 if trade["trade_type"]=="Sell" or trade["trade_type"]=="Sell":513 sec_list.append(trade["security_obj"])514 515 unique_list=list(set(sec_list))516 #print "unique_list: ",unique_list517 trd_data = []518 for i in unique_list:519 trd_obj = Trade_Details.objects.filter(security_id=i,record_status="Active")520 for trd in trd_obj:521 trds_obj = {522 'security_obj':int(i),523 'trade_type':trd.buy_sell_indicator,524 'quantity':trd.trade_security_quantity525 }526 trd_data.append(trds_obj)527 #print "trd_data:", trd_data528 trade_data.extend(trd_data)529 test_desc={} 530 for security in trade_data:531 if test_desc.has_key(security['security_obj']):532 if security['trade_type']=='Buy':533 test_desc[security['security_obj']]=test_desc[security['security_obj']]+int(security['quantity'])534 else:535 test_desc[security['security_obj']]=test_desc[security['security_obj']]-int(security['quantity'])536 else:537 if security['trade_type']=='Buy':538 test_desc[security['security_obj']]=0+int(security['quantity'])539 else:540 test_desc[security['security_obj']]=0-int(security['quantity'])541 #print test_desc542 return test_desc543def save_trades(check_list,request):544 try:545 for check_trd in check_list:546 print "saving........"547 security_obj = Security_Details.objects.get(security_id=check_trd['security_id'])548 trade_obj = Trade_Details(549 security_id=security_obj,550 trade_date=datetime.strptime(check_trd['date'], '%d/%m/%Y').date(),551 buy_sell_indicator=check_trd['trade_type'],552 trade_security_quantity=check_trd['quantity'],553 trade_price=check_trd['trade_price'],554 fx_price=check_trd['fx_price'],555 trade_amount=check_trd['total_amount'],556 broker=check_trd['broker'],557 lot_size=check_trd['lot_size'],558 record_status="Active",559 trade_created_by=request.session['login_user'],560 trade_updated_by=request.session['login_user'],561 trade_created_date=datetime.now(),562 trade_updated_date=datetime.now(),563 )564 trade_obj.save()565 trade_status = "saved"566 except Exception as e:567 print "Exception: ",e568 trade_status = "error"...
routes.py
Source:routes.py
1from flask import (render_template, url_for, flash, jsonify,2 redirect, request, abort, Blueprint, Response)3from flask_login import current_user, login_required4from capital_gains_loss import db5from capital_gains_loss.models import Transaction6from capital_gains_loss.transactions.forms import TransactionForm, TransactionFormUpdate7import datetime8import requests9import io10import csv11from capital_gains_loss.config import Config12from decimal import Decimal13transactions = Blueprint('transactions', __name__)14@transactions.route("/transaction/new", methods=['GET', 'POST'])15@login_required16def new_transaction():17 form = TransactionForm()18 if form.validate_on_submit():19 dt = datetime.datetime.strptime(form.transaction_date.data, '%m/%d/%Y %I:%M %p')20 transaction = Transaction(security_name=form.security_name.data.upper(),21 security_details=form.security_details.data,22 transaction_date=dt,23 transaction_type=form.transaction_type.data,24 quantity=form.quantity.data,25 price_per_share=form.price_per_share.data,26 fees=form.fees.data,27 forex_rate=form.forex_rate.data,28 amount_recieved=form.amount_recieved.data,29 amount_recieved_details=form.amount_recieved_details.data,30 author=current_user)31 db.session.add(transaction)32 db.session.commit()33 flash('New transaction has been created!', 'success')34 return redirect(url_for('main.home'))35 return render_template('create_transaction.html', title='New Transaction',36 form=form, legend='New Transaction')37@transactions.route("/transaction/<int:transaction_id>/update", methods=['GET', 'POST'])38@login_required39def update_transaction(transaction_id):40 transaction = Transaction.query.get_or_404(transaction_id)41 if transaction.author != current_user:42 abort(403)43 form = TransactionFormUpdate()44 if form.validate_on_submit():45 transaction.security_name = form.security_name.data.upper()46 transaction.transaction_type = form.transaction_type.data47 transaction.security_details = form.security_details.data48 transaction.quantity = form.quantity.data49 transaction.price_per_share = form.price_per_share.data50 transaction.fees = form.fees.data51 transaction.forex_rate = form.forex_rate.data52 transaction.transaction_date = datetime.datetime.strptime(form.transaction_date.data, '%m/%d/%Y %I:%M %p')53 transaction.amount_recieved = form.amount_recieved.data54 transaction.amount_recieved_details = form.amount_recieved_details.data55 db.session.commit()56 flash('Transaction has been updated!', 'success')57 return redirect(url_for('main.home'))58 elif request.method == 'GET':59 form.security_name.data = transaction.security_name60 form.transaction_type.data = transaction.transaction_type61 form.security_details.data = transaction.security_details62 form.quantity.data = transaction.quantity63 form.price_per_share.data = transaction.price_per_share64 form.fees.data = transaction.fees65 form.forex_rate.data = transaction.forex_rate66 form.transaction_date.data = datetime.datetime.strftime(transaction.transaction_date, '%m/%d/%Y %I:%M %p')67 form.amount_recieved_details.data = transaction.amount_recieved_details68 form.amount_recieved.data = transaction.amount_recieved69 return render_template('create_transaction.html', title='Update Transaction',70 form=form, legend='Update Transaction')71@transactions.route("/transaction/schedule3report", methods=['GET'])72@login_required73def schedule3_report():74 transactions = Transaction.query.filter(Transaction.gain_loss!=Decimal(0),Transaction.author==current_user).order_by(Transaction.transaction_date.desc()).all()75 return render_template('report.html', transactions=transactions)76@transactions.route("/transaction/<int:transaction_id>/delete", methods=['POST'])77@login_required78def delete_transaction(transaction_id):79 transaction = Transaction.query.get_or_404(transaction_id)80 if transaction.author != current_user:81 abort(403)82 db.session.delete(transaction)83 db.session.commit()84 flash('Your transaction has been deleted!', 'success')85 return redirect(url_for('main.home'))86@transactions.route("/transaction/<symbol_id>/delete", methods=['GET'])87@login_required88def delete_all_transaction(symbol_id):89 transaction = Transaction.query.filter_by(security_name=symbol_id,author=current_user).delete()90 db.session.commit()91 flash('All transactions has been deleted for symbol %s!' %(symbol_id), 'success')92 return redirect(url_for('main.home'))93@transactions.route('/forex', methods=['GET'])94@login_required95def find_forex_rate():96 try:97 trans_date = request.args.get('trans_date',0,type=str)98 trans_date = datetime.datetime.strptime(trans_date, '%m/%d/%Y %I:%M %p').date()99 qdate = datetime.datetime.strftime(trans_date, "%Y-%m-%d")100 r = requests.get("https://www.bankofcanada.ca/valet/observations/FXUSDCAD/json?start_date=%s&end_date=%s" %(qdate,qdate))101 res = r.json()102 forex = res['observations'][0]['FXUSDCAD']['v']103 return jsonify(result=forex)104 except Exception as e:105 print(e)106 return str(e)107@transactions.route('/commission', methods=['GET'])108@login_required109def find_commission():110 try:111 quantity = Decimal(request.args.get('quantity',0))112 forex_rate = Decimal(request.args.get('forex_rate',0))113 fees = Decimal(request.args.get('fees',0,type=str))114 amount_recieved = Decimal(request.args.get('amount_recieved',0))115 price_per_share = Decimal(request.args.get('price_per_share',0))116 if forex_rate != Decimal(0):117 amount = (quantity * price_per_share * forex_rate) - (fees * forex_rate)118 else:119 amount = (quantity * price_per_share) - fees120 difference = amount - amount_recieved121 if forex_rate != Decimal(0):122 fees = fees + difference/forex_rate123 else:124 fees = fees + difference125 print("DEBUG IN COMMISSION : Amount : %f , difference : %f, FEES: %f" %(amount,difference, fees))126 fees = round(fees,2)127 return jsonify(result=str(fees))128 except Exception as e:129 print(e)130 return str(e)131@transactions.route('/downloadcsv/')132@login_required133def download_csv():134 transactions = Transaction.query.filter_by(author=current_user).order_by(Transaction.transaction_date.desc())135 output = io.StringIO()136 writer = csv.writer(output)137 list_items = ['id', 'security_name', 'security_details', 'transaction_date', 'transaction_type',\138 'quantity', 'price_per_share', 'fees', 'forex_rate', 'acb', 'gain_loss', 'amount_recieved',\139 'amount_recieved_details', 'amount_in_cad', 'acb_change']140 line = ''141 for x in list_items:142 line = line + x + ','143 line = line.rstrip(',')144 writer.writerow([line])145 for transaction in transactions:146 line = ''147 for x in list_items:148 line = line + '"' + str(getattr(transaction,x)) + '"' + ','149 line = line.rstrip(',')150 writer.writerow([line])151 filedt = datetime.datetime.utcnow().strftime('%m_%d_%Y')152 output.seek(0)153 return Response(output, mimetype="text/csv", headers={"Content-Disposition":"attachment;filename=export_%s.csv" %(filedt)})154def allowed_file(filename):155 if not "." in filename:156 return False157 ext = filename.rsplit(".", 1)[1]158 if ext.upper() in ['CSV']:159 return True160 else:161 return False162@transactions.route('/uploadcsv', methods = ['GET', 'POST'])163@login_required164def upload_csv():165 if request.method == "POST":166 if request.files:167 csvfile1 = request.files["csvfile"]168 if csvfile1.filename == "":169 flash('No file provided!', 'danger')170 return redirect(request.url)171 if not allowed_file(csvfile1.filename):172 flash('Only csv files are allowed', 'danger')173 return redirect(request.url)174 stream = io.StringIO(csvfile1.stream.read().decode("UTF8"), newline=None)175 csv_input = csv.reader(stream)176 result = []177 headers = [header.strip() for header in next(csv_input)]178 headers = headers[0].split(",")179 for line in csv_input:180 values = [value.strip() for value in line]181 values = values[0].split(",")182 r = {}183 for idx, val in enumerate(headers):184 #print("IDX: %d, VAL: %s" %(idx,val))185 r[val] = values[idx].strip('"')186 result.append(r)187 for r in result:188 dt = datetime.datetime.strptime(r['transaction_date'], '%Y-%m-%d %H:%M:%S')189 transaction = Transaction(security_name=r['security_name'].upper(),190 security_details=r['security_details'],191 transaction_date=dt,192 transaction_type=r['transaction_type'],193 quantity=r['quantity'],194 price_per_share=r['price_per_share'],195 fees=r['fees'],196 forex_rate=r['forex_rate'],197 amount_recieved=r.get('amount_recieved'),198 amount_recieved_details=r.get('amount_recieved_details'),199 author=current_user)200 db.session.add(transaction)201 db.session.commit()202 flash('CSV file uploaded successfully!', 'success')203 return redirect(url_for('main.home'))...
browser_bot_response.py
Source:browser_bot_response.py
1# -*- coding: utf-8 -*-23"""4 neutrino_api56 This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ).7"""8910class BrowserBotResponse(object):1112 """Implementation of the 'Browser Bot Response' model.1314 TODO: type model description here.1516 Attributes:17 url (string): The page URL18 content (string): The complete raw, decompressed and decoded page19 content. Usually will be either HTML, JSON or XML20 mime_type (string): The document MIME type21 title (string): The document title22 is_error (bool): True if an error has occurred loading the page. Check23 the 'error-message' field for details24 is_timeout (bool): True if a timeout occurred while loading the page.25 You can set the timeout with the request parameter 'timeout'26 error_message (string): Contains the error message if an error has27 occurred ('is-error' will be true)28 http_status_code (int): The HTTP status code the URL returned29 http_status_message (string): The HTTP status message the URL30 returned31 is_http_ok (bool): True if the HTTP status is OK (200)32 is_http_redirect (bool): True if the URL responded with an HTTP33 redirect34 http_redirect_url (string): The redirected URL if the URL responded35 with an HTTP redirect36 server_ip (string): The HTTP servers IP address37 load_time (int): The number of seconds taken to load the page (from38 initial request until DOM ready)39 response_headers (dict<object, string>): Map containing all the HTTP40 response headers the URL responded with41 is_secure (bool): True if the page is secured using TLS/SSL42 security_details (dict<object, string>): Map containing details of the43 TLS/SSL setup44 elements (list of string): Array containing all the elements matching45 the supplied selector. Each element object will contain the text46 content, HTML content and all current element attributes47 exec_results (list of string): If you executed any JavaScript this48 array holds the results as objects4950 """5152 # Create a mapping from Model property names to API property names53 _names = {54 "url":'url',55 "content":'content',56 "mime_type":'mimeType',57 "title":'title',58 "is_error":'isError',59 "is_timeout":'isTimeout',60 "error_message":'errorMessage',61 "http_status_code":'httpStatusCode',62 "http_status_message":'httpStatusMessage',63 "is_http_ok":'isHttpOk',64 "is_http_redirect":'isHttpRedirect',65 "http_redirect_url":'httpRedirectUrl',66 "server_ip":'serverIp',67 "load_time":'loadTime',68 "response_headers":'responseHeaders',69 "is_secure":'isSecure',70 "security_details":'securityDetails',71 "elements":'elements',72 "exec_results":'execResults'73 }7475 def __init__(self,76 url=None,77 content=None,78 mime_type=None,79 title=None,80 is_error=None,81 is_timeout=None,82 error_message=None,83 http_status_code=None,84 http_status_message=None,85 is_http_ok=None,86 is_http_redirect=None,87 http_redirect_url=None,88 server_ip=None,89 load_time=None,90 response_headers=None,91 is_secure=None,92 security_details=None,93 elements=None,94 exec_results=None):95 """Constructor for the BrowserBotResponse class"""9697 # Initialize members of the class98 self.url = url99 self.content = content100 self.mime_type = mime_type101 self.title = title102 self.is_error = is_error103 self.is_timeout = is_timeout104 self.error_message = error_message105 self.http_status_code = http_status_code106 self.http_status_message = http_status_message107 self.is_http_ok = is_http_ok108 self.is_http_redirect = is_http_redirect109 self.http_redirect_url = http_redirect_url110 self.server_ip = server_ip111 self.load_time = load_time112 self.response_headers = response_headers113 self.is_secure = is_secure114 self.security_details = security_details115 self.elements = elements116 self.exec_results = exec_results117118119 @classmethod120 def from_dictionary(cls,121 dictionary):122 """Creates an instance of this model from a dictionary123124 Args:125 dictionary (dictionary): A dictionary representation of the object as126 obtained from the deserialization of the server's response. The keys127 MUST match property names in the API description.128129 Returns:130 object: An instance of this structure class.131132 """133 if dictionary is None:134 return None135136 # Extract variables from the dictionary137 url = dictionary.get('url')138 content = dictionary.get('content')139 mime_type = dictionary.get('mimeType')140 title = dictionary.get('title')141 is_error = dictionary.get('isError')142 is_timeout = dictionary.get('isTimeout')143 error_message = dictionary.get('errorMessage')144 http_status_code = dictionary.get('httpStatusCode')145 http_status_message = dictionary.get('httpStatusMessage')146 is_http_ok = dictionary.get('isHttpOk')147 is_http_redirect = dictionary.get('isHttpRedirect')148 http_redirect_url = dictionary.get('httpRedirectUrl')149 server_ip = dictionary.get('serverIp')150 load_time = dictionary.get('loadTime')151 response_headers = dictionary.get('responseHeaders')152 is_secure = dictionary.get('isSecure')153 security_details = dictionary.get('securityDetails')154 elements = dictionary.get('elements')155 exec_results = dictionary.get('execResults')156157 # Return an object of this model158 return cls(url,159 content,160 mime_type,161 title,162 is_error,163 is_timeout,164 error_message,165 http_status_code,166 http_status_message,167 is_http_ok,168 is_http_redirect,169 http_redirect_url,170 server_ip,171 load_time,172 response_headers,173 is_secure,174 security_details,175 elements,176 exec_results)177
...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!