diff --git a/DJpositionTR/.env b/DJpositionTR/.env new file mode 100644 index 0000000..e69de29 diff --git a/DJpositionTR/DJpositionTR/__init__.py b/DJpositionTR/DJpositionTR/__init__.py new file mode 100644 index 0000000..46b592d --- /dev/null +++ b/DJpositionTR/DJpositionTR/__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/DJpositionTR/DJpositionTR/__pycache__/__init__.cpython-310.pyc b/DJpositionTR/DJpositionTR/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..6878a3d Binary files /dev/null and b/DJpositionTR/DJpositionTR/__pycache__/__init__.cpython-310.pyc differ diff --git a/DJpositionTR/DJpositionTR/__pycache__/celery.cpython-310.pyc b/DJpositionTR/DJpositionTR/__pycache__/celery.cpython-310.pyc new file mode 100644 index 0000000..1e6ce42 Binary files /dev/null and b/DJpositionTR/DJpositionTR/__pycache__/celery.cpython-310.pyc differ diff --git a/DJpositionTR/DJpositionTR/__pycache__/settings.cpython-310.pyc b/DJpositionTR/DJpositionTR/__pycache__/settings.cpython-310.pyc new file mode 100644 index 0000000..73fb70f Binary files /dev/null and b/DJpositionTR/DJpositionTR/__pycache__/settings.cpython-310.pyc differ diff --git a/DJpositionTR/DJpositionTR/__pycache__/urls.cpython-310.pyc b/DJpositionTR/DJpositionTR/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..d98239a Binary files /dev/null and b/DJpositionTR/DJpositionTR/__pycache__/urls.cpython-310.pyc differ diff --git a/DJpositionTR/DJpositionTR/__pycache__/wsgi.cpython-310.pyc b/DJpositionTR/DJpositionTR/__pycache__/wsgi.cpython-310.pyc new file mode 100644 index 0000000..e09031a Binary files /dev/null and b/DJpositionTR/DJpositionTR/__pycache__/wsgi.cpython-310.pyc differ diff --git a/DJpositionTR/DJpositionTR/asgi.py b/DJpositionTR/DJpositionTR/asgi.py new file mode 100644 index 0000000..e972e51 --- /dev/null +++ b/DJpositionTR/DJpositionTR/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for DJpositionTR project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DJpositionTR.settings') + +application = get_asgi_application() diff --git a/DJpositionTR/DJpositionTR/celery.py b/DJpositionTR/DJpositionTR/celery.py new file mode 100644 index 0000000..c029fc1 --- /dev/null +++ b/DJpositionTR/DJpositionTR/celery.py @@ -0,0 +1,24 @@ +import os +from datetime import timedelta +from celery import Celery + + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DJpositionTR.settings") + +app = Celery("DJpositionTR") + +app.config_from_object("django.conf:settings", namespace="CELERY") + +app.autodiscover_tasks() + +# Celery settings +CELERY_BROKER_URL = "redis://localhost:6379" +CELERY_RESULT_BACKEND = "redis://localhost:6379" + + +app.conf.beat_schedule = { + 'read-open-positions-every-30-sec': { + 'task': 'DjReader.tasks.trackPositions', + 'schedule': timedelta(seconds=30), + }, +} \ No newline at end of file diff --git a/DJpositionTR/DJpositionTR/settings.py b/DJpositionTR/DJpositionTR/settings.py new file mode 100644 index 0000000..c824db1 --- /dev/null +++ b/DJpositionTR/DJpositionTR/settings.py @@ -0,0 +1,178 @@ +from pathlib import Path +from datetime import timedelta + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-!=lwm)s7-ost@^cgizl^ey2uevhr-ar!yw(pu(%+$37=aowa-n' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + 'rest_framework_simplejwt', + 'useAuthApp', + 'rest_framework', + 'DjReader', +] + +AUTH_USER_MODEL = 'useAuthApp.UserForkucoin' + + +REST_FRAMEWORK = { + + 'DEFAULT_AUTHENTICATION_CLASSES': ( + + 'rest_framework_simplejwt.authentication.JWTAuthentication', + ) + +} + +SIMPLE_JWT = { + "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), + "REFRESH_TOKEN_LIFETIME": timedelta(days=1), + "ROTATE_REFRESH_TOKENS": False, + "BLACKLIST_AFTER_ROTATION": False, + "UPDATE_LAST_LOGIN": False, + + "ALGORITHM": "HS256", + "VERIFYING_KEY": "", + "AUDIENCE": None, + "ISSUER": None, + "JSON_ENCODER": None, + "JWK_URL": None, + "LEEWAY": 0, + + "AUTH_HEADER_TYPES": ("Bearer",), + "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", + "USER_ID_FIELD": "id", + "USER_ID_CLAIM": "user_id", + "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", + + "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), + "TOKEN_TYPE_CLAIM": "token_type", + "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", + + "JTI_CLAIM": "jti", + + "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", + "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), + "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), + + "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", + "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", + "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", + "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", + "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", + "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", +} + + + + + + + + + + + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'DJpositionTR.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'DJpositionTR.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.1/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/DJpositionTR/DJpositionTR/urls.py b/DJpositionTR/DJpositionTR/urls.py new file mode 100644 index 0000000..bca39b2 --- /dev/null +++ b/DJpositionTR/DJpositionTR/urls.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('auth/', include('useAuthApp.urls')), + path('api/', include('DjReader.urls')), + +] diff --git a/DJpositionTR/DJpositionTR/wsgi.py b/DJpositionTR/DJpositionTR/wsgi.py new file mode 100644 index 0000000..f59c616 --- /dev/null +++ b/DJpositionTR/DJpositionTR/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for DJpositionTR project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DJpositionTR.settings') + +application = get_wsgi_application() diff --git a/DJpositionTR/DjReader/__init__.py b/DJpositionTR/DjReader/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/DJpositionTR/DjReader/__pycache__/__init__.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..74136c8 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/__init__.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/__pycache__/admin.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/admin.cpython-310.pyc new file mode 100644 index 0000000..4f784c3 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/admin.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/__pycache__/apps.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/apps.cpython-310.pyc new file mode 100644 index 0000000..0985024 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/apps.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/__pycache__/models.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000..c74cc60 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/models.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/__pycache__/urls.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..ed72bd5 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/urls.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/__pycache__/views.cpython-310.pyc b/DJpositionTR/DjReader/__pycache__/views.cpython-310.pyc new file mode 100644 index 0000000..9ca27b9 Binary files /dev/null and b/DJpositionTR/DjReader/__pycache__/views.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/admin.py b/DJpositionTR/DjReader/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/DJpositionTR/DjReader/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/DJpositionTR/DjReader/apps.py b/DJpositionTR/DjReader/apps.py new file mode 100644 index 0000000..cb6cd42 --- /dev/null +++ b/DJpositionTR/DjReader/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class DjreaderConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'DjReader' diff --git a/DJpositionTR/DjReader/migrations/__init__.py b/DJpositionTR/DjReader/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/DJpositionTR/DjReader/migrations/__pycache__/__init__.cpython-310.pyc b/DJpositionTR/DjReader/migrations/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..4b223d0 Binary files /dev/null and b/DJpositionTR/DjReader/migrations/__pycache__/__init__.cpython-310.pyc differ diff --git a/DJpositionTR/DjReader/models.py b/DJpositionTR/DjReader/models.py new file mode 100644 index 0000000..4167352 --- /dev/null +++ b/DJpositionTR/DjReader/models.py @@ -0,0 +1,3 @@ +from django.db import models + + diff --git a/DJpositionTR/DjReader/serializers.py b/DJpositionTR/DjReader/serializers.py new file mode 100644 index 0000000..e85bb75 --- /dev/null +++ b/DJpositionTR/DjReader/serializers.py @@ -0,0 +1,10 @@ +from rest_framework import serializers +from useAuthApp.models import Position + + +class PositionsSerializer(serializers.ModelSerializer): + class Meta: + model = Position + fields = '__all__' + + diff --git a/DJpositionTR/DjReader/tasks.py b/DJpositionTR/DjReader/tasks.py new file mode 100644 index 0000000..a84ff7f --- /dev/null +++ b/DJpositionTR/DjReader/tasks.py @@ -0,0 +1,14 @@ +from DJpositionTR.celery import app +from . import views + +@app.task +def trackPositions(): + users=UserForkucoin.objects.filter(activePositionTracking=True) + + for user in users: + api_key = user.api_key + api_secret = user.api_secret + api_passphrase = user.api_passphrase + positions=views.kucoinReader(views.api_key,api_secret,api_passphrase) + views.saveToRedisAndDB_paraler(positions,views.host,views.port,views.db) + diff --git a/DJpositionTR/DjReader/tests.py b/DJpositionTR/DjReader/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/DJpositionTR/DjReader/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/DJpositionTR/DjReader/urls.py b/DJpositionTR/DjReader/urls.py new file mode 100644 index 0000000..524e476 --- /dev/null +++ b/DJpositionTR/DjReader/urls.py @@ -0,0 +1,9 @@ +from django.urls import path +from . import views + + +urlpatterns = [ + path('activePositionTracking/',views.activePositionTracking), + path('positions/',views.positions), + +] \ No newline at end of file diff --git a/DJpositionTR/DjReader/views.py b/DJpositionTR/DjReader/views.py new file mode 100644 index 0000000..f847494 --- /dev/null +++ b/DJpositionTR/DjReader/views.py @@ -0,0 +1,129 @@ +#DRF +from rest_framework.decorators import api_view, permission_classes +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +#DRF-JWT +from rest_framework_simplejwt.authentication import JWTAuthentication +#My apps +from useAuthApp.models import UserForkucoin , Position +from .serializers import YourModelSerializer + +numberOfTreads=7 +host="127.0.0.1" +port=6379 +db=0 + +@api_view(['GET']) +@permission_classes((IsAuthenticated, )) +def activePositionTracking(request): + username=get_username_from_token(request) + user = User.objects.get(username=username) + user.activePositionTracking=True + user.save() + return Response({'msg':"activePositionTracking activeted"}) + +def get_username_from_token(request): + authentication = JWTAuthentication() + try: + user, _ = authentication.authenticate(request) # Authenticate the request + username = user.username # Access the username from the authenticated user object + return username + except: + # Handle authentication errors + return None + +def kucoinReader(api_key,api_secret,api_passphrase): + totalpositions=int(callKucon(api_key,api_secret,api_passphrase)['totalNum']) + items=[] + currentPage=range(0,totalpositions) + with Pool(numberOfTreads) as p: + data=p.starmap(callKucon, zip(repeat(api_key), repeat(api_secret) , repeat(api_passphrase),repeat(endpoint),currentPage)) + items+=data['data'] + return items + +def callKucon(api_key,api_secret,api_passphrase,currentPage=1): + + url = 'https://api-futures.kucoin.com/api/v1/positions?status=active¤tPage='+str(currentPage)+'&pageSize=1' + now = int(time.time() * 1000) + + str_to_sign = str(now) + 'GET' + '/api/v1/positions?status=active¤tPage='+str(currentPage)+'&pageSize=1' + signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest()) + + passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest()) + headers = { + "KC-API-SIGN": signature, + "KC-API-TIMESTAMP": str(now), + "KC-API-KEY": api_key, + "KC-API-PASSPHRASE": passphrase, + "KC-API-KEY-VERSION": "2" + } + + response = requests.request('get', url, headers=headers) + + return response.json() + +def saveToRedisAndDB(dataArry,host,port,db,userid): + r = redis.Redis(host, port, db) + r.set(userid,dataArry) + + for data in dataArry: + q=Position() + q.owner=UserForkucoin.objects.get(pk=1) + q.id = data['id'] + q.symbol = data['symbol'] + q.autoDeposit = data['autoDeposit'] + q.maintMarginReq = data['maintMarginReq'] + q.riskLimit = data['riskLimit'] + q.realLeverage = data['realLeverage'] + q.crossMode = data['crossMode'] + q.delevPercentage = data['delevPercentage'] + q.openingTimestamp = data['openingTimestamp'] + q.currentQty = data['currentQty'] + q.currentCost = data['currentCost'] + q.currentComm = data['currentComm'] + q.unrealisedCost = data['unrealisedCost'] + q.realisedGrossCost = data['realisedGrossCost'] + q.realisedCost = data['realisedCost'] + q.isOpen = data['isOpen'] + q.markPrice = data['markPrice'] + q.markValue = data['markValue'] + q.posCost = data['posCost'] + q.posCross = data['posCross'] + q.posInit = data['posInit'] + q.posComm = data['posComm'] + q.posLoss = data['posLoss'] + q.posMargin = data['posMargin'] + q.posMaint = data['posMaint'] + q.maintMargin = data['maintMargin'] + q.realisedGrossPnl = data['realisedGrossPnl'] + q.realisedPnl = data['realisedPnl'] + q.unrealisedPnl = data['unrealisedPnl'] + q.unrealisedPnlPcnt = data['unrealisedPnlPcnt'] + q.unrealisedRoePcnt = data['realisedGrossPnl'] + q.avgEntryPrice = data['realisedPnl'] + q.liquidationPrice = data['unrealisedPnl'] + q.settleCurrency = data['unrealisedPnlPcnt'] + q.isInverse = data['realisedGrossPnl'] + q.userId = data['realisedPnl'] + q.maintainMargin = data['unrealisedPnl'] + q.save()#or update + +def saveToRedisAndDB_paraler(dataArry,host,port,db): + with Pool(numberOfTreads) as p: + p.starmap(saveToRedisAndDB, zip(dataArry, repeat(host), repeat(port) , repeat(db),repeat(userid))) + +@api_view(['GET']) +@permission_classes((IsAuthenticated, )) +def positions(request): + responseData='' + username=get_username_from_token(request) + user = User.objects.get(username=username) + + try: + responseData = redis_client.get(user.id) + except: + positions = Position.objects.filter(owner=user) + serializer = YourModelSerializer(positions, many=True) + responseData = serializer.data + return Response(responseData) + \ No newline at end of file diff --git a/DJpositionTR/db.sqlite3 b/DJpositionTR/db.sqlite3 new file mode 100644 index 0000000..cebdad3 Binary files /dev/null and b/DJpositionTR/db.sqlite3 differ diff --git a/DJpositionTR/manage.py b/DJpositionTR/manage.py new file mode 100755 index 0000000..a89198d --- /dev/null +++ b/DJpositionTR/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', 'DJpositionTR.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/DJpositionTR/useAuthApp/__init__.py b/DJpositionTR/useAuthApp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/DJpositionTR/useAuthApp/__pycache__/__init__.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..c09dc72 Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/__init__.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/admin.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/admin.cpython-310.pyc new file mode 100644 index 0000000..1de713c Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/admin.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/apps.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/apps.cpython-310.pyc new file mode 100644 index 0000000..a6e9b45 Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/apps.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/models.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000..f881788 Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/models.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/serializers.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/serializers.cpython-310.pyc new file mode 100644 index 0000000..b0a051d Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/serializers.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/urls.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..1d450c0 Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/urls.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/__pycache__/views.cpython-310.pyc b/DJpositionTR/useAuthApp/__pycache__/views.cpython-310.pyc new file mode 100644 index 0000000..af4cea9 Binary files /dev/null and b/DJpositionTR/useAuthApp/__pycache__/views.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/admin.py b/DJpositionTR/useAuthApp/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/DJpositionTR/useAuthApp/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/DJpositionTR/useAuthApp/apps.py b/DJpositionTR/useAuthApp/apps.py new file mode 100644 index 0000000..cd3dd93 --- /dev/null +++ b/DJpositionTR/useAuthApp/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class UseauthappConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'useAuthApp' diff --git a/DJpositionTR/useAuthApp/migrations/0001_initial.py b/DJpositionTR/useAuthApp/migrations/0001_initial.py new file mode 100644 index 0000000..f1a786e --- /dev/null +++ b/DJpositionTR/useAuthApp/migrations/0001_initial.py @@ -0,0 +1,48 @@ +# Generated by Django 4.2.1 on 2023-05-19 11:59 + +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='UserForkucoin', + 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')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('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')), + ('api_name', models.CharField(max_length=40)), + ('api_key', models.CharField(max_length=40)), + ('api_secret', models.CharField(max_length=50)), + ('api_email', models.EmailField(max_length=254)), + ('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/DJpositionTR/useAuthApp/migrations/__init__.py b/DJpositionTR/useAuthApp/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/DJpositionTR/useAuthApp/migrations/__pycache__/0001_initial.cpython-310.pyc b/DJpositionTR/useAuthApp/migrations/__pycache__/0001_initial.cpython-310.pyc new file mode 100644 index 0000000..ff57e29 Binary files /dev/null and b/DJpositionTR/useAuthApp/migrations/__pycache__/0001_initial.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/migrations/__pycache__/__init__.cpython-310.pyc b/DJpositionTR/useAuthApp/migrations/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..521dea1 Binary files /dev/null and b/DJpositionTR/useAuthApp/migrations/__pycache__/__init__.cpython-310.pyc differ diff --git a/DJpositionTR/useAuthApp/models.py b/DJpositionTR/useAuthApp/models.py new file mode 100644 index 0000000..bc549b2 --- /dev/null +++ b/DJpositionTR/useAuthApp/models.py @@ -0,0 +1,55 @@ +from django.db import models +from django.contrib.auth.models import AbstractUser + + +class UserForkucoin(AbstractUser): + api_name = models.CharField(max_length=40) + api_key = models.CharField(max_length=40) + api_secret = models.CharField(max_length=50) + api_email = models.EmailField() + activePositionTracking=models.BooleanField() + +class Position(models.Model): + owner=models.ForeignKey(UserForkucoin, on_delete=models.CASCADE) + id = models.CharField(max_length=50, primary_key=True) + symbol = models.CharField(max_length=50) + autoDeposit = models.BooleanField() + maintMarginReq = models.FloatField() + riskLimit = models.IntegerField() + realLeverage = models.FloatField() + crossMode = models.BooleanField() + delevPercentage = models.FloatField() + openingTimestamp = models.BigIntegerField() + currentTimestamp = models.BigIntegerField() + currentQty = models.IntegerField() + currentCost = models.FloatField() + currentComm = models.FloatField() + unrealisedCost = models.FloatField() + realisedGrossCost = models.FloatField() + realisedCost = models.FloatField() + isOpen = models.BooleanField() + markPrice = models.FloatField() + markValue = models.FloatField() + posCost = models.FloatField() + posCross = models.FloatField() + posInit = models.FloatField() + posComm = models.FloatField() + posLoss = models.FloatField() + posMargin = models.FloatField() + posMaint = models.FloatField() + maintMargin = models.FloatField() + realisedGrossPnl = models.FloatField() + realisedPnl = models.FloatField() + unrealisedPnl = models.FloatField() + unrealisedPnlPcnt = models.FloatField() + unrealisedRoePcnt = models.FloatField() + avgEntryPrice = models.FloatField() + liquidationPrice = models.FloatField() + bankruptPrice = models.FloatField() + settleCurrency = models.CharField(max_length=10) + isInverse = models.BooleanField() + userId = models.IntegerField() + maintainMargin = models.FloatField() + + def __str__(self): + return self.symbol \ No newline at end of file diff --git a/DJpositionTR/useAuthApp/serializers.py b/DJpositionTR/useAuthApp/serializers.py new file mode 100644 index 0000000..c3606be --- /dev/null +++ b/DJpositionTR/useAuthApp/serializers.py @@ -0,0 +1,15 @@ +from rest_framework import serializers +from . import models + +UserForkucoin=models.UserForkucoin() +class UserSerializer(serializers.ModelSerializer): + password = serializers.CharField(write_only=True) + + class Meta: + model = UserForkucoin + fields = ('username', 'password','api_name','api_key','api_secret','api_email') + + def create(self, validated_data): + user = UserForkucoin.objects.create_user(**validated_data) + return user + diff --git a/DJpositionTR/useAuthApp/tests.py b/DJpositionTR/useAuthApp/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/DJpositionTR/useAuthApp/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/DJpositionTR/useAuthApp/urls.py b/DJpositionTR/useAuthApp/urls.py new file mode 100644 index 0000000..63d7303 --- /dev/null +++ b/DJpositionTR/useAuthApp/urls.py @@ -0,0 +1,18 @@ +from rest_framework_simplejwt.views import (TokenObtainPairView,TokenRefreshView,) +from rest_framework_simplejwt.views import TokenVerifyView +from django.urls import path, include +from . import views + + + +urlpatterns = [ + + path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), + path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), + path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), + path('tst',views.my_view), + path('register/', views.UserRegistrationView.as_view(), name ='register'), + path('logout/', views.LogoutView.as_view(), name ='logout'), + + +] \ No newline at end of file diff --git a/DJpositionTR/useAuthApp/views.py b/DJpositionTR/useAuthApp/views.py new file mode 100644 index 0000000..68d4017 --- /dev/null +++ b/DJpositionTR/useAuthApp/views.py @@ -0,0 +1,39 @@ +from django.shortcuts import render +from rest_framework.decorators import api_view, permission_classes +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from .serializers import UserSerializer +from rest_framework.views import APIView +from rest_framework import status +from rest_framework_simplejwt.tokens import RefreshToken + + + + +@api_view(['GET']) # Specify the HTTP methods allowed for this view +@permission_classes([IsAuthenticated]) # Set the permission classes +def my_view(request): + # Your view logic here + return Response("Authenticated user can access this view.") + + + +class UserRegistrationView(APIView): + def post(self, request): + serializer = UserSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + +class LogoutView(APIView): + permission_classes = (IsAuthenticated,) + def post(self, request): + try: + refresh_token = request.data["refresh_token"] + token = RefreshToken(refresh_token) + token.blacklist() + return Response(status=status.HTTP_205_RESET_CONTENT) + except Exception as e: + return Response(status=status.HTTP_400_BAD_REQUEST) \ No newline at end of file