def create_user_from_mt4demouser(mt4du): if (not email_re.match(mt4du.email) or not get_account_type(mt4du.group) or not mt4du.name): return None names = mt4du.name.split() try: new_user = register_user( email=mt4du.email.lower(), first_name=names[0], last_name=names[1] if len(names) > 1 else u'', phone_mobile=mt4du.phone, country=guess_country(mt4du.country), state=guess_state(mt4du.state, mt4du.city), city=mt4du.city, address=mt4du.address) #skip accounts with wrong email except SMTPRecipientsRefused: return None assert new_user #update date_joined to match mt4 account creation date new_user.date_joined = mt4du.regdate new_user.save() profile = new_user.profile profile.user_from = {'system': 'MT4'} profile.save() return new_user
def welcome_account(request, account_id, user_id=None, slug=None): """Welcome screen, displayed when new account is created.""" if user_id is not None: account = get_object_or_404(TradingAccount, mt4_id=account_id, user=user_id, is_deleted=False) elif request.user.is_authenticated(): account = get_object_or_404(TradingAccount, mt4_id=account_id, user=request.user, is_deleted=False) else: raise Http404 # Checking if we have a custom welcome template for acount's # group, if not — falling back to base.html. try: template = "mt4/welcome/%s.html" % (slug or account.group.slug) get_template(template) except TemplateDoesNotExist: template = "mt4/welcome/base.html" finally: return { "TEMPLATE": template, "account_type": get_account_type(slug) or account.group, "account": account, "group_slug": slug or account.group.slug, "next": request.GET.get('next') }
def execute(self, *args, **options): #select accounts, created in last day #with email set for mt4du in (Mt4DemoUser.objects.filter( regdate__gt=datetime.now() - timedelta(1), enable=1).exclude(Q(email=None) | Q(email=''))): #if we have no Mt4Account for this Mt4DemoUser if TradingAccount.objects.filter(mt4_id=mt4du.login).exists(): continue #damn, we could have multiple accounts with same email, so # we should take latest one users = User.objects.filter( email__iexact=mt4du.email).order_by('-date_joined') if users: user = users[0] else: #possible, we should create new one user = self.create_user_from_mt4demouser(mt4du) #if we cannot create user - skip this one if not user: continue #damn, safe if better than unsafe, lol TradingAccount.objects.get_or_create( user=user, mt4_id=mt4du.login, creation_ts=mt4du.regdate, group_name=mt4du.group, #simplied code from create_account task _group_as_char=unicode(get_account_type(mt4du.group)))
def filter(self, qs, value): if value: rxs = [] for v in value: t = get_account_type(v) if t: rxs.append(t.regex.pattern) qs = qs.filter(group_name__regex='|'.join(rxs)) return qs
def agent_list(request, account_id=None): if "account_id" in request.POST: return redirect("mt4_agent_list", request.POST["account_id"]) if account_id: try: account_id = int(account_id) except: raise Http404 if not request.user.is_superuser: account = get_object_or_404(TradingAccount, user=request.user, mt4_id=account_id, is_deleted=False) else: # HACK: "group_name" is set, cause if it is not, the model # will be saved, which will cause an IntegrityError account = TradingAccount(mt4_id=account_id, group_name='real_ib') else: accounts = request.user.accounts.active().real_ib() if not accounts: raise Http404 elif len(accounts) > 1: return { "form": AccountChooseForm(accounts), "TEMPLATE": "agent_list_choose.html" } else: account = accounts[0] try: res = {} for agent_type in ["agents", "demo_agents"]: res[agent_type] = [] for mt4_user in getattr(account, agent_type): acc_type = get_account_type(mt4_user.group) mt4_acc = TradingAccount.objects.filter(mt4_id=mt4_user.login) res[agent_type].append({ "group": acc_type, "mt4": mt4_user, "site": None if not mt4_acc else mt4_acc[0] }) except (OperationalError, DatabaseError): return HttpResponse("This operation is currently unavailable") return { "agents": res["agents"], "demoagents": res["demo_agents"], "account": account }
def symbols_for_instrument(request, acc_type_raw="realstandard", spec_type_raw=""): cache_key = "contract_specs_all_instruments_%s" % get_language() res = cache.get(cache_key) if res: res = json.loads(res) else: res = {} for acc_type in [StandardAccountType]: # qs = InstrumentsByGroup.objects.filter(account_group__iregex=acc_type.regex.pattern) # FIXME: When going to production qs = InstrumentsByGroup.objects.filter(account_group__iregex=r'^realstd_.*$') res[acc_type.slug] = defaultdict(dict) for group_raw in ( qs.filter(symbol_group__in=INSTRUMENTS_MAP.keys()) .values_list("symbol_group", flat=True) .order_by("symbol_group").distinct()): group = mutate_name(group_raw) try: tab_name = INSTRUMENTS_MAP[group_raw] except KeyError: continue values_list = COLUMNS[group] res[acc_type.slug][tab_name][group_raw] = { "data": list(Instruments.objects.filter(group=group_raw) .order_by("group") .values_list(*values_list)), "columns": [unicode(Instruments._meta.get_field_by_name(f_name)[0].verbose_name) for f_name in values_list] } res[acc_type.slug].default_factory = None # cache until 5 AM if datetime.now().hour < 5: # cache gonna to expire today! timeout = int(((datetime.now() + relativedelta(hour=5, minute=0, second=0))-datetime.now()).total_seconds()) else: # cache is gonna to expire tomorrow timeout = int(((datetime.now() + relativedelta(days=1, hour=5, minute=0, second=0))-datetime.now()).total_seconds()) cache.set(cache_key, json.dumps(res), timeout) return { "acc_data": res['realstandard'], "acc_type": get_account_type(acc_type_raw) or StandardAccountType, "spec_type": (spec_type_raw or '').upper() }
def register_mt4account(details, user, account_type_details, form_class, partner_api_id, additional_fields=None): additional_fields = additional_fields or dict() engine = "demo" if account_type_details["is_demo"] else "default" mt4_id = mt4api.RemoteMT4Manager(engine).create_account(**details) # mt4_id = api.SocketAPI(engine=account_type_details['engine']).create_account(**details) account = TradingAccount( user=user, mt4_id=mt4_id, _login=str(mt4_id), group_name=account_type_details['slug'], agreement_type=additional_fields.get('agreement_type')) if partner_api_id: try: account.registered_from_partner_domain = PartnerDomain.objects.get( api_key=partner_api_id) except PartnerDomain.DoesNotExist: pass account.save() Logger(user=user, content_object=account, ip=account_type_details["ip"], event=Events.ACCOUNT_CREATED).save() form_class.send_notification(account, account_type_details['slug'], **details) account_created.send( sender=account, type_details=account_type_details, mt4data=details, ) account_group = get_account_type(account_type_details['slug']) if account_group.creation_callback is not None: account_group.creation_callback(account, **additional_fields) return { 'mt4_id': mt4_id, 'mt4_password': details['password'], 'slug': account_type_details['slug'], 'account_pk': account.pk }
def get_account_welcome_page(request): account_type = get_account_type(request.GET["slug"]) account = TradingAccount.objects.filter(mt4_id=request.GET["mt4_id"])[0] return { "welcome_page": render_to_string([ "mt4/welcome/%s.html" % account_type.slug, "mt4/welcome/base.html" ], RequestContext( request, { "account_type": account_type, "account": account, "alternate_base": "ajax_base.html", })) }
def get(self, request, slug): # get form template = "includes/create_account_form_with_errors.html" account_type = get_account_type(slug) if str( account_type ) == 'ECN.Invest' and not request.user.profile.allow_open_invest: return redirect('verify_docs') if not account_type.is_demo and request.user.profile.status == request.user.profile.UNVERIFIED: # return self.json_response({ # "redirect": redirect("mt4_create_account", slug=21) # }) return redirect("verify_docs") if not account_type.is_demo and request.user.profile.status < request.user.profile.UNVERIFIED: return redirect("account_app") if not (account_type.is_demo or request.user.profile.has_otp_devices): return security(request) if not request.is_ajax(): return redirect("mt4_create_account", slug) num_of_accounts = self.max_accounts_reached(request.user, account_type) if num_of_accounts: return render_to_response( template, RequestContext( request, { "too_many_accounts": True, "num_of_accounts": num_of_accounts, "acc_type": account_type })) form = account_type.account_form(request=request, account_type=account_type) return render_to_response( template, RequestContext(request, { "form": form, "acc_type": account_type }))
def send_notification(cls, account, account_type_slug, **kwargs): """Send account creation email to account user""" account_type = get_account_type(account_type_slug) notification_data = { "account": account, "login": account.mt4_id, "group": account_type } kwargs.pop("group", None) notification_data.update(kwargs) recipients = [account.user] notification_name = None if getattr(cls, "notification_name", None): notification_name = cls.notification_name cls.get_notification().send(recipients, notification_name, notification_data, no_django_message=True)
def post(self, request, slug): # post form account_type = get_account_type(slug or request.POST.get("account_type")) if not account_type.is_demo and request.user.profile.status == request.user.profile.UNVERIFIED: return self.json_response({"redirect": redirect("verify_docs")}) if not account_type.is_demo and request.user.profile.status < request.user.profile.UNVERIFIED: return self.json_response({"redirect": redirect("account_app")}) if self.max_accounts_reached(request.user, account_type): return self.json_response( {"redirect": redirect("mt4_create_account", args=[slug])}) assert 'OK' if not (account_type.is_demo or request.user.profile.has_otp_devices): return security(request) form = account_type.account_form(request.POST, request=request, account_type=account_type) if form.is_valid(): form_result = form.save(profile=request.user.profile) if getattr(form.save, 'async', None): return self.json_response({ "ok": True, "wait": reverse("mt4_ajax_account_creation_done", args=[form_result]), }) account = form_result['account'] Logger(user=request.user, content_object=account, ip=request.META["REMOTE_ADDR"], event=Events.ACCOUNT_CREATED).save() return self.json_response({ "ok": True, "no_wait": True, "slug": account_type.slug, "mt4_id": account.mt4_id, "mt4_password": form_result["password"], "platform": account.platform_type, "login": account._login, "redirect": reverse("mt4_account_welcome", args=[account_type.slug, account.mt4_id]), }) return self.json_response({ "nok": True, "errors": {k: map(unicode, v) for k, v in form.errors.items()}, })
def create_account(request, slug, extra_context=None): account_type = get_account_type(slug) if not account_type: raise Http404() if account_type.login_required and request.user.is_anonymous(): return redirect(settings.LOGIN_URL + "?next=%s" % request.path) if not (account_type.is_demo or request.user.profile.has_otp_devices): messages.info( request, _("You need to set up a secure authentication method before opening a Real account." )) return redirect(reverse("otp_security") + "?next=" + request.path) num_of_accounts = CreateAccountView.max_accounts_reached( request.user, account_type) if num_of_accounts: return { 'documents_unverified': False, "too_many_accounts": True, "num_of_accounts": num_of_accounts, "acc_type": account_type } if request.POST: form = account_type.account_form(request.POST, request.FILES, request=request) if form.is_valid(): form_result = form.save(profile=request.user.profile) if form.save. async: return redirect("mt4_wait_for_account_creation", form_result) else: if isinstance(form_result, HttpResponse): return form_result Logger(user=request.user, content_object=form_result, ip=request.META["REMOTE_ADDR"], event=Events.ACCOUNT_CREATED).save() kwargs = { "slug": account_type.slug, "account_id": form_result.mt4_id } done_url = reverse('mt4_account_welcome', kwargs=kwargs) if request.GET.get('next'): return redirect(done_url + '?next=%s' % request.GET.get('next')) else: return redirect(done_url) else: form = account_type.account_form(request=request) result = {"forms": {"account": form}} if extra_context is not None: result.update(extra_context) return result
def account_type(self): """ Type of account: demo/real/etc """ return get_account_type(self.group)