diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..100fe35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,548 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python,pycharm,virtualenv,venv +# Edit at https://www.toptal.com/developers/gitignore?templates=python,pycharm,virtualenv,venv + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +### venv ### +# Virtualenv +# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +[Bb]in +[Ii]nclude +[Ll]ib +[Ll]ib64 +[Ll]ocal +[Ss]cripts +pyvenv.cfg +pip-selfcheck.json + +### VirtualEnv ### +# Virtualenv +# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ + +# End of https://www.toptal.com/developers/gitignore/api/python,pycharm,virtualenv,venv +Hello! How can I assist you today? + +Text from your selection +Created by https://www.toptal.com/developers/gitignore/api/python,pycharm,virtualenv,venv +Edit at https://www.toptal.com/developers/gitignore?templates=python,pycharm,virtualenv,venv +PyCharm +Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 +User-specific stuff +.idea//workspace.xml .idea//tasks.xml .idea//usage.statistics.xml .idea//dictionaries .idea/**/shelf + +AWS User-specific +.idea/**/aws.xml + +Generated files +.idea/**/contentModel.xml + +Sensitive or high-churn files +.idea//dataSources/ .idea//dataSources.ids .idea//dataSources.local.xml .idea//sqlDataSources.xml .idea//dynamic.xml .idea//uiDesigner.xml .idea/**/dbnavigator.xml + +Gradle +.idea//gradle.xml .idea//libraries + +Gradle and Maven with auto-import +When using Gradle or Maven with auto-import, you should exclude module files, +since they will be recreated, and may cause churn. Uncomment if using +auto-import. +.idea/artifacts +.idea/compiler.xml +.idea/jarRepositories.xml +.idea/modules.xml +.idea/*.iml +.idea/modules +*.iml +*.ipr +CMake +cmake-build-*/ + +Mongo Explorer plugin +.idea/**/mongoSettings.xml + +File-based project format +*.iws + +IntelliJ +out/ + +mpeltonen/sbt-idea plugin +.idea_modules/ + +JIRA plugin +atlassian-ide-plugin.xml + +Cursive Clojure plugin +.idea/replstate.xml + +SonarLint plugin +.idea/sonarlint/ + +Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties + +Editor-based Rest Client +.idea/httpRequests + +Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +PyCharm Patch +Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 +*.iml +modules.xml +.idea/misc.xml +*.ipr +Sonarlint plugin +https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +SonarQube Plugin +https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +Markdown Navigator plugin +https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea//markdown-navigator.xml .idea//markdown-navigator-enh.xml .idea/**/markdown-navigator/ + +Cache file creation bug +See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/ +� +� +� +� +� +� +� +� +� +CACHE +F + + ILE + +CodeStream plugin +https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +Azure Toolkit for IntelliJ plugin +https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +Python +Byte-compiled / optimized / DLL files +pycache/ *.py[cod] *$py.class + +C extensions +*.so + +Distribution / packaging +.Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST + +PyInstaller +Usually these files are written by a python script from a template +before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest *.spec + +Installer logs +pip-log.txt pip-delete-this-directory.txt + +Unit test / coverage reports +htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ + +Translations +*.mo *.pot + +Django stuff: +*.log local_settings.py db.sqlite3 db.sqlite3-journal + +Flask stuff: +instance/ .webassets-cache + +Scrapy stuff: +.scrapy + +Sphinx documentation +docs/_build/ + +PyBuilder +.pybuilder/ target/ + +Jupyter Notebook +.ipynb_checkpoints + +IPython +profile_default/ ipython_config.py + +pyenv +For a library or package, you might want to ignore these files since the code is +intended to run in multiple environments; otherwise, check them in: +.python-version +pipenv +According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +However, in case of collaboration, if having platform-specific dependencies or dependencies +having no cross-platform support, pipenv may install dependencies that don't work, or not +install all needed dependencies. +#Pipfile.lock + +poetry +Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +This is especially recommended for binary packages to ensure reproducibility, and is more +commonly ignored for libraries. +https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +pdm +Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock + +pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +in version control. +https://pdm.fming.dev/#use-with-ide +.pdm.toml + +PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +pypackages/ + +Celery stuff +celerybeat-schedule celerybeat.pid + +SageMath parsed files +*.sage.py + +Environments +.env .venv env/ venv/ ENV/ env.bak/ venv.bak/ + +Spyder project settings +.spyderproject .spyproject + +Rope project settings +.ropeproject + +mkdocs documentation +/site + +mypy +.mypy_cache/ .dmypy.json dmypy.json + +Pyre type checker +.pyre/ + +pytype static type analyzer +.pytype/ + +Cython debug symbols +cython_debug/ + +PyCharm +JetBrains specific template is maintained in a separate JetBrains.gitignore that can +be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +and can be added to the global gitignore or merged into this file. For a more nuclear +option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +Python Patch +Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +ruff +.ruff_cache/ + +LSP config files +pyrightconfig.json + +venv +Virtualenv +http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +[Bb]in [Ii]nclude [Ll]ib [Ll]ib64 [Ll]ocal [Ss]cripts pyvenv.cfg pip-selfcheck.json + +VirtualEnv +Virtualenv +http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +End of https://www.toptal.com/developers/gitignore/api/python,pycharm,virtualenv,venv +What would you like to do with the text? \ No newline at end of file diff --git a/README.md b/README.md index c16311f..2b54ce1 100644 --- a/README.md +++ b/README.md @@ -29,3 +29,39 @@ We want a clean, readable and maintainable code with meaningful comments and doc 3. Push your code to your repository 4. Send us a pull request, we will review and get back to you 5. Enjoy + +#---------------------------------------------------------------- +# All functions which have been performed in the system +- User is able to sign up , sign in, request to track position(per symbol) +- Authentication has been implemented (JWT token) +- User is able to see list of positions (cache system is applied) +- KuCoin api key & secrets are stored in encrypted format +- The system can handle multiuser requests for tracking +- Swagger has been provided in `/docs` endpoint +- pagination is provided in `/positions` endpoint +- All endpoints must be set **access token** in head as **Authorization** with prefix JWT except for `auth/user` +## All dependencies +- Redis has been applied as message broker and cache system +- Celery has been applied as task queue +- MySQL or Sqlite has been applied as database (default database is `MySQL`) +## Installation +- activate virtualenv +- install all python requirments by `pip install -r requirements.txt` +- migrate database through `python manage.py migrate` +- **check the following fields** in settings.py +1) `CELERY_BROKER_URL` +2) `CELERY_RESULT_BACKEND` +3) `CELERY_TASK_SERIALIZER` +4) `CELERY_RESULT_SERIALIZER` +5) `CELERY_ACCEPT_CONTENT` +6) `CELERY_BEAT_SCHEDULER ,CACHES ,EXPIRE_TIME` +7) `TARGET_SCHEDULE_APP_NAME, INTERVAL` + +- Change the database backend in setting.py +- Ensure that the database and redis are installed and available. +- Run these commands in separate shells in the same python virtualenv. +1) `celery -A position beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler` +2) `celery -A position worker -l info -P gevent` +3) in development mode (`python manage.py runserver`), but you are able to use gunicorne or uwsgi +## Admin Panel +- If you register as superuser can access the `PERIODIC TASK`, it allows you to enable or disable every task whatever you want. diff --git a/project/__init__.py b/project/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/core/__init__.py b/project/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/core/admin.py b/project/core/admin.py new file mode 100644 index 0000000..b9b3319 --- /dev/null +++ b/project/core/admin.py @@ -0,0 +1,23 @@ +from django.contrib import admin +from .models import User +from django.contrib.auth.admin import UserAdmin as BaseUserAdmin +from .forms import UserCreationForm, UserChangeForm + + +# Register your models here. + +@admin.register(User) +class UserAdmin(BaseUserAdmin): + form = UserChangeForm + add_form = UserCreationForm + + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('username', 'password1', 'password2', 'email', 'first_name', 'last_name'), + }), + ) + + list_display = ("username", "email", "first_name", "last_name", "is_staff", "is_active",) + list_filter = ("is_staff", "is_superuser", "is_active", "groups") + diff --git a/project/core/apps.py b/project/core/apps.py new file mode 100644 index 0000000..8115ae6 --- /dev/null +++ b/project/core/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'core' diff --git a/project/core/forms.py b/project/core/forms.py new file mode 100644 index 0000000..806cbc7 --- /dev/null +++ b/project/core/forms.py @@ -0,0 +1,15 @@ +from django.contrib.auth.forms import UserCreationForm, UserChangeForm + +from .models import User + + +class UserCreationForm(UserCreationForm): + class Meta: + model = User + fields = ('email',) + + +class UserChangeForm(UserChangeForm): + class Meta: + model = User + fields = ('email',) diff --git a/project/core/migrations/0001_initial.py b/project/core/migrations/0001_initial.py new file mode 100644 index 0000000..80c6383 --- /dev/null +++ b/project/core/migrations/0001_initial.py @@ -0,0 +1,44 @@ +# Generated by Django 4.2 on 2023-04-15 10:30 + +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'user', + 'verbose_name_plural': 'users', + 'abstract': False, + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/project/core/migrations/0002_user_kucoin_api_key_user_kucoin_api_secret.py b/project/core/migrations/0002_user_kucoin_api_key_user_kucoin_api_secret.py new file mode 100644 index 0000000..72ee065 --- /dev/null +++ b/project/core/migrations/0002_user_kucoin_api_key_user_kucoin_api_secret.py @@ -0,0 +1,23 @@ +# Generated by Django 4.2 on 2023-04-15 10:33 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='user', + name='kucoin_api_key', + field=models.CharField(blank=True, max_length=255, null=True), + ), + migrations.AddField( + model_name='user', + name='kucoin_api_secret', + field=models.CharField(blank=True, max_length=255, null=True), + ), + ] diff --git a/project/core/migrations/0003_user_kucoin_passphrase.py b/project/core/migrations/0003_user_kucoin_passphrase.py new file mode 100644 index 0000000..c2e8cc3 --- /dev/null +++ b/project/core/migrations/0003_user_kucoin_passphrase.py @@ -0,0 +1,18 @@ +# Generated by Django 4.2 on 2023-04-15 21:07 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0002_user_kucoin_api_key_user_kucoin_api_secret'), + ] + + operations = [ + migrations.AddField( + model_name='user', + name='kucoin_passphrase', + field=models.CharField(blank=True, max_length=255, null=True), + ), + ] diff --git a/project/core/migrations/0004_alter_user_kucoin_api_key_and_more.py b/project/core/migrations/0004_alter_user_kucoin_api_key_and_more.py new file mode 100644 index 0000000..7f6833b --- /dev/null +++ b/project/core/migrations/0004_alter_user_kucoin_api_key_and_more.py @@ -0,0 +1,29 @@ +# Generated by Django 4.2 on 2023-04-18 21:30 + +from django.db import migrations, models +import django_cryptography.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('core', '0003_user_kucoin_passphrase'), + ] + + operations = [ + migrations.AlterField( + model_name='user', + name='kucoin_api_key', + field=django_cryptography.fields.encrypt(models.CharField(blank=True, max_length=255, null=True)), + ), + migrations.AlterField( + model_name='user', + name='kucoin_api_secret', + field=django_cryptography.fields.encrypt(models.CharField(blank=True, max_length=255, null=True)), + ), + migrations.AlterField( + model_name='user', + name='kucoin_passphrase', + field=django_cryptography.fields.encrypt(models.CharField(blank=True, max_length=255, null=True)), + ), + ] diff --git a/project/core/migrations/__init__.py b/project/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/core/models.py b/project/core/models.py new file mode 100644 index 0000000..49d858e --- /dev/null +++ b/project/core/models.py @@ -0,0 +1,16 @@ +from django.db import models +from django.contrib.auth.models import AbstractUser +from django.utils.translation import gettext as _ +from django_cryptography.fields import encrypt + + +# provide name, username & kucoin details +class User(AbstractUser): + """ + Custom User model + all KuCoins details have been encrypted and stored in the database. + """ + kucoin_api_key = encrypt(models.CharField(max_length=255, null=True, blank=True)) + kucoin_api_secret = encrypt(models.CharField(max_length=255, null=True, blank=True)) + kucoin_passphrase = encrypt(models.CharField(max_length=255, blank=True, null=True)) + email = models.EmailField(_('email address'), unique=True) diff --git a/project/core/serializers.py b/project/core/serializers.py new file mode 100644 index 0000000..cca24f6 --- /dev/null +++ b/project/core/serializers.py @@ -0,0 +1,20 @@ +from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer, UserSerializer as BaseUserSerializer + + + +class UserCreateSerializer(BaseUserCreateSerializer): + """ + Custom serializer inorder to create a new user based on the custom User data model. + """ + class Meta(BaseUserCreateSerializer.Meta): + fields = ['id', 'first_name', 'last_name', 'email', 'password', 'username', + 'kucoin_api_key', 'kucoin_api_secret', 'kucoin_passphrase'] + + +class UserSerializer(BaseUserSerializer): + """ + Custom serializer for representing users infor + (KuCoin details have been excluded) + """ + class Meta(BaseUserSerializer.Meta): + fields = ['id', 'first_name', 'last_name', 'username', 'email'] diff --git a/project/core/tests.py b/project/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/project/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/project/core/views.py b/project/core/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/project/core/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/project/manage.py b/project/manage.py new file mode 100644 index 0000000..2c49f3a --- /dev/null +++ b/project/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/project/position/__init__.py b/project/position/__init__.py new file mode 100644 index 0000000..88b8c87 --- /dev/null +++ b/project/position/__init__.py @@ -0,0 +1,4 @@ +from .celery import app as celery_app + + +__all__ = ("celery_app",) \ No newline at end of file diff --git a/project/position/admin.py b/project/position/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/project/position/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/project/position/apps.py b/project/position/apps.py new file mode 100644 index 0000000..d6844dc --- /dev/null +++ b/project/position/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class PositionConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'position' diff --git a/project/position/celery.py b/project/position/celery.py new file mode 100644 index 0000000..c745c9d --- /dev/null +++ b/project/position/celery.py @@ -0,0 +1,13 @@ +import os +from celery import Celery + +# Set the default Django settings module +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + +# Create a Celery instance +app = Celery('project') + +app.config_from_object("django.conf:settings", namespace="CELERY") + +# Load task modules from all registered Django app configs +app.autodiscover_tasks() diff --git a/project/position/migrations/0001_initial.py b/project/position/migrations/0001_initial.py new file mode 100644 index 0000000..bb3ed45 --- /dev/null +++ b/project/position/migrations/0001_initial.py @@ -0,0 +1,26 @@ +# Generated by Django 4.2 on 2023-04-15 10:43 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Position', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('symbol', models.CharField(max_length=10)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/project/position/migrations/0002_position_mark_price_position_mark_value_and_more.py b/project/position/migrations/0002_position_mark_price_position_mark_value_and_more.py new file mode 100644 index 0000000..c7b7e93 --- /dev/null +++ b/project/position/migrations/0002_position_mark_price_position_mark_value_and_more.py @@ -0,0 +1,33 @@ +# Generated by Django 4.2 on 2023-04-15 17:20 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('position', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='position', + name='mark_price', + field=models.FloatField(max_length=2, null=True), + ), + migrations.AddField( + model_name='position', + name='mark_value', + field=models.FloatField(max_length=2, null=True), + ), + migrations.AddField( + model_name='position', + name='rist_limit', + field=models.IntegerField(null=True), + ), + migrations.AlterField( + model_name='position', + name='symbol', + field=models.CharField(default='XBTUSDM', max_length=10), + ), + ] diff --git a/project/position/migrations/0003_rename_rist_limit_position_risk_limit.py b/project/position/migrations/0003_rename_rist_limit_position_risk_limit.py new file mode 100644 index 0000000..7b2a01c --- /dev/null +++ b/project/position/migrations/0003_rename_rist_limit_position_risk_limit.py @@ -0,0 +1,18 @@ +# Generated by Django 4.2 on 2023-04-15 23:09 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('position', '0002_position_mark_price_position_mark_value_and_more'), + ] + + operations = [ + migrations.RenameField( + model_name='position', + old_name='rist_limit', + new_name='risk_limit', + ), + ] diff --git a/project/position/migrations/__init__.py b/project/position/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/position/models.py b/project/position/models.py new file mode 100644 index 0000000..222524b --- /dev/null +++ b/project/position/models.py @@ -0,0 +1,15 @@ +from django.conf import settings +from django.db import models + + +class Position(models.Model): + """ + This model is created based partial received data from following api + https://api-futures.kucoin.com/api/v1/position?symbol={symbol_name} + """ + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + symbol = models.CharField(max_length=10, default='XBTUSDM') + created_at = models.DateTimeField(auto_now_add=True) + mark_price = models.FloatField(max_length=2,null=True) + mark_value = models.FloatField(max_length=2, null=True) + risk_limit = models.IntegerField(null=True) diff --git a/project/position/pagination.py b/project/position/pagination.py new file mode 100644 index 0000000..456fa59 --- /dev/null +++ b/project/position/pagination.py @@ -0,0 +1,9 @@ +from rest_framework import pagination + + +class CustomPagination(pagination.LimitOffsetPagination): + default_limit = 10 + limit_query_param = 'l' + offset_query_param = 'o' + max_limit = 50 + order_by = 'created_at' diff --git a/project/position/serializers.py b/project/position/serializers.py new file mode 100644 index 0000000..289a6e9 --- /dev/null +++ b/project/position/serializers.py @@ -0,0 +1,27 @@ +from rest_framework import serializers + +from .models import Position + + +class PositionSerializer(serializers.ModelSerializer): + """ + This serializer has been customized based partial received data from following api + https://api-futures.kucoin.com/api/v1/position?symbol={symbol_name} + """ + class Meta: + model = Position + fields = ('symbol', 'created_at', 'mark_price', 'mark_value', 'risk_limit') + + +class TrackingPositionSerializer(serializers.ModelSerializer): + """ + this serializer is used to filter some additional information in all positions. + It has been applied in serializing_output method in Utility class.( it is located in tasks.py) + """ + class Meta: + model = Position + fields = ('symbol', 'created_at', 'mark_price', 'mark_value', 'risk_limit') + + def create(self, validated_data): + user_id = self.context.get('user_id') + return Position.objects.create(user_id=user_id, **validated_data) diff --git a/project/position/tasks.py b/project/position/tasks.py new file mode 100644 index 0000000..6cbc201 --- /dev/null +++ b/project/position/tasks.py @@ -0,0 +1,102 @@ +import re +import requests +import time +import hmac +import hashlib +import base64 +from dataclasses import dataclass +import json +import pprint +from .serializers import TrackingPositionSerializer +from celery import shared_task +from datetime import timedelta +from django.conf import settings +from django_redis import get_redis_connection + + +@dataclass +class Utility: + """ + This class implements some functionalities that can be used in + tracking task in tracking_task function and caching + """ + camel_pat = re.compile(r'([A-Z])') + serializer = TrackingPositionSerializer + domain = 'https://api-futures.kucoin.com' + + redis_conn: object + symbol_name: str = 'XBTUSDM' + context: dict = None + api_key: str = None + api_secret: str = None + api_passphrase: str = None + user: dict = None + output: dict = None # data is fetched from KuCoins + data: dict = None + + def __post_init__(self): + self.api_key = self.api_key or self.user.get('kucoin_api_key') + self.api_secret = self.api_secret or self.user.get('kucoin_api_secret') + self.api_passphrase = self.api_passphrase or self.user.get('kucoin_passphrase') + self.output = self.get_positions() + # + self._validated_data = self.serializing_output() + + def _set_cache(self) -> None: + if self.output: + _user_id = self.context.get("user_id") + + # the structure of cache key is `cache_key_{symbol_name}_{user_id}` + self.redis_conn.set(f'cache_key_{self.symbol_name}_{_user_id}', json.dumps(self.output)) + self.redis_conn.expire(f'cache_key_{_user_id}', timedelta(seconds=settings.INTERVAL - 5)) + + def serializing_output(self): + if self.output is not None: + s = self.serializer(data=self.output, context=self.context) + s.is_valid(raise_exception=True) + s.save() + # Set cache + self._set_cache() + return s.data + return None + + def _camel_to_underscore(self, name: str) -> str: + return self.camel_pat.sub(lambda x: '_' + x.group(1).lower(), name) + + def _internal_value(self, data: dict) -> dict: + return {self._camel_to_underscore(k): v for k, v in data.items()} + + def get_positions(self) -> dict | None: + # For position details + url = f'{self.domain}/api/v1/position?symbol={self.symbol_name}' + + now = int(time.time() * 1000) + # For position details + str_to_sign = str(now) + 'GET' + f'/api/v1/position?symbol={self.symbol_name}' + + signature = base64.b64encode( + hmac.new(self.api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest()) + passphrase = base64.b64encode( + hmac.new(self.api_secret.encode('utf-8'), self.api_passphrase.encode('utf-8'), hashlib.sha256).digest()) + headers = { + "KC-API-SIGN": signature, + "KC-API-TIMESTAMP": str(now), + "KC-API-KEY": self.api_key, + "KC-API-PASSPHRASE": passphrase, + "KC-API-KEY-VERSION": "2" + } + response = requests.request('get', url, headers=headers).json() + data = response.get('data') + if data: + return self._internal_value(data=data) + else: + print(response) + return None + + +@shared_task +def tracking_task(user, context): + redis_conn = get_redis_connection("default") + print("Tracking task---------> START") + Utility(user=user, context=context, redis_conn=redis_conn) + print("Tracking task---------> Done") diff --git a/project/position/templates/docs.html b/project/position/templates/docs.html new file mode 100644 index 0000000..521105a --- /dev/null +++ b/project/position/templates/docs.html @@ -0,0 +1,24 @@ + + +
+