Skip to content

Commit

Permalink
Merge pull request #229 from napse-invest/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
Xenepix authored Nov 28, 2023
2 parents c29ee32 + 596d2f4 commit 7d8b10f
Show file tree
Hide file tree
Showing 54 changed files with 3,008 additions and 262 deletions.
33 changes: 29 additions & 4 deletions .github/workflows/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,39 @@ on:
push:
branches:
- main
- feature/mkdocs

permissions:
contents: write

jobs:
api-schema:
name: API schema
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
with:
python-version: 3.11

- name: Set up python
uses: actions/setup-python@v4
with:
python-version: "3.11"
architecture: "x64"

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pip-tools
pip-compile ./requirements/development.txt --output-file ./full-requirements.txt --resolver=backtracking
pip install -r ./full-requirements.txt
- name: Write open-api schema
run: python tests/test_app/manage.py spectacular --file docs/schema.yml

deploy:
needs: api-schema
name: Deploy documentation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Expand All @@ -25,6 +51,5 @@ jobs:
restore-keys: |
mkdocs-material-
- run: |
pip install mkdocs-material
pip install mkdocs-plugin-inline-svg
- run: mkdocs gh-deploy --force
pip install -r requirements/development.txt
mkdocs gh-deploy --force
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ MANIFEST
# pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
# htmlcov/
.tox/
.nox/
.coverage
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<h1 align="center">
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/napse-invest/Napse/blob/main/desktop-app/renderer/public/images/NapseInvestLogoSVGWhite.svg">
<source media="(prefers-color-scheme: light)" srcset="https://github.com/napse-invest/Napse/blob/main/desktop-app/renderer/public/images/NapseInvestLogoSVG.svg">
<source media="(prefers-color-scheme: dark)" srcset="docs/theme/assets/napse_invest_logo_white.svg">
<source media="(prefers-color-scheme: light)" srcset="docs/theme/assets/napse_invest_logo_black.svg">
<img alt="Napse's logo" src="" width=500>
</picture>
</div>

<!-- <img src="./branding/napse_white.svg" width=500/> -->
</h1><br>
<br>

<p align="center">
<a href="https://twitter.com/NapseInvest">
Expand Down
3 changes: 1 addition & 2 deletions django_napse/api/api_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ class ConflictingUrlNames(Exception):
def build_main_router() -> DefaultRouter:
"""Create a main router object and register the appropriate viewsets to it based on the modules and classes found in the `api` directory.
Returns
-------
Returns:
DefaultRouter: The main router object with registered URL patterns.
"""
main_router = DefaultRouter()
Expand Down
3 changes: 2 additions & 1 deletion django_napse/api/bots/serializers/bot_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@


class BotSerializer(serializers.ModelSerializer):
StrategySerializer = StrategySerializer()
strategy = StrategySerializer()

class Meta:
model = Bot
fields = [
"name",
"uuid",
"strategy",
]
read_only_fields = fields
16 changes: 14 additions & 2 deletions django_napse/api/keys/views/key_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

class KeyView(CustomViewSet):
permission_classes = [HasMasterKey]
serializer_class = NapseAPIKeySerializer

def get_queryset(self):
return NapseAPIKey.objects.all()
Expand Down Expand Up @@ -42,7 +43,12 @@ def retrieve(self, request, pk):
if "space" not in request.query_params:
serializer = NapseAPIKeySerializer(key)
return Response(serializer.data, status=status.HTTP_200_OK)
serializer = NapseAPIKeySpaceSerializer(key, context={"space": request.query_params["space"]})
serializer = NapseAPIKeySpaceSerializer(
key,
context={
"space": request.query_params["space"],
},
)
return Response(serializer.data, status=status.HTTP_200_OK)

def list(self, request):
Expand All @@ -51,7 +57,13 @@ def list(self, request):
serializer = NapseAPIKeySerializer(keys, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

serializer = NapseAPIKeySpaceSerializer(keys, many=True, context={"space": request.query_params["space"]})
serializer = NapseAPIKeySpaceSerializer(
keys,
many=True,
context={
"space": request.query_params["space"],
},
)
data = {"keys": []}
for key in serializer.data:
if key["permissions"]:
Expand Down
10 changes: 10 additions & 0 deletions django_napse/api/wallets/serializers/currency_serializer.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
from rest_framework import serializers

from django_napse.core.models import Currency
from django_napse.core.models.bots.controller import Controller


class CurrencySerializer(serializers.ModelSerializer):
value = serializers.SerializerMethodField(read_only=True)

class Meta:
model = Currency
fields = [
"mbp",
"ticker",
"amount",
"value",
]
read_only_fields = fields

def get_value(self, instance):
return instance.amount * Controller.get_asset_price(
exchange_account=instance.wallet.exchange_account,
base=instance.ticker,
)
9 changes: 8 additions & 1 deletion django_napse/core/models/accounts/managers/exchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@


class ExchangeAccountManager(models.Manager):
def create(self, exchange, testing: bool, name: str, description: str = "", **kwargs):
def create(
self,
exchange,
testing: bool,
name: str,
description: str = "",
**kwargs,
):
NapseSpace = apps.get_model("django_napse_core", "NapseSpace")
exchange_account = self.model(
exchange=exchange,
Expand Down
1 change: 1 addition & 0 deletions django_napse/core/models/accounts/managers/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

class NapseSpaceManager(models.Manager):
def create(self, name: str, exchange_account, description: str = ""):
"""Create a Space instance."""
SpaceWallet = apps.get_model("django_napse_core", "SpaceWallet")
SpaceSimulationWallet = apps.get_model("django_napse_core", "SpaceSimulationWallet")

Expand Down
47 changes: 43 additions & 4 deletions django_napse/core/models/accounts/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,36 @@


class NapseSpace(models.Model):
"""Categorize and manage money.
Attributes:
name: Name of the space.
uuid: Unique identifier of the space.
description: Description of the space.
exchange_account: Exchange account of the space.
created_at: Date of creation of the space.
Examples:
Create a space:
```python
import django_napse.core.models import NapseSpace, ExchangeAccount
exchange_account: ExchangeAccount = ...
space = NapseSpace.objects.create(
name="Space",
description="Space description",
exchange_account=exchange_account,
)
```
"""

name = models.CharField(max_length=200)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
)
description = models.TextField()
exchange_account = models.ForeignKey("ExchangeAccount", on_delete=models.CASCADE, related_name="spaces")
created_at = models.DateTimeField(auto_now_add=True)
Expand All @@ -25,7 +53,13 @@ class Meta:
def __str__(self):
return f"SPACE: {self.name}"

def info(self, verbose=True, beacon=""):
def info(self, verbose: bool = True, beacon: str = "") -> str:
"""Info documentation.
Params:
verbose: Print to console.
beacon: Indentation for printing.
"""
string = ""
string += f"{beacon}Space ({self.pk=}):\n"
string += f"{beacon}Args:\n"
Expand All @@ -40,20 +74,24 @@ def info(self, verbose=True, beacon=""):
return string

@property
def testing(self):
def testing(self) -> bool:
"""Testing property."""
return self.exchange_account.testing

@property
def value(self) -> float:
"""Value market of space's wallet."""
connections = self.wallet.connections.all()
return sum([connection.wallet.value_market() for connection in connections])

@property
def fleets(self) -> models.QuerySet:
"""Fleets of the space."""
connections = self.wallet.connections.all()
return Fleet.objects.filter(clusters__links__bot__connections__in=connections).distinct()

def get_stats(self) -> dict:
def get_stats(self) -> dict[str, int | float | str]:
"""Statistics of space."""
order_count_30 = Order.objects.filter(
connection__in=self.wallet.connections.all(),
created_at__gt=datetime.now(tz=get_default_timezone()) - timedelta(days=30),
Expand All @@ -66,6 +104,7 @@ def get_stats(self) -> dict:
}

def delete(self) -> None:
"""Delete space."""
if self.testing:
return super().delete()
if self.value > 0:
Expand Down
12 changes: 5 additions & 7 deletions django_napse/core/models/bots/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ def send_candles_to_bots(self, closed_candle, current_candle) -> list:
Args:
----
closed_candle (dict): The candle that just closed.
current_candle (dict): The candle that is currently open.
closed_candle : The candle that just closed.
current_candle : The candle that is currently open.
Returns:
-------
Expand Down Expand Up @@ -257,8 +257,7 @@ def _get_price(self) -> float:
Always calls the exchange API. (Can be costly)
Returns
-------
Returns:
float: The price of the pair.
"""
exchange_controller = self.exchange_controller
Expand All @@ -284,9 +283,8 @@ def get_price(self) -> float:
Only updates the price if it is older than 1 minute.
Returns
-------
float: The price of the pair.
Returns:
price: The price of the pair.
"""
if self.last_price_update is None or self.last_price_update < datetime.now(tz=timezone.utc) - timedelta(minutes=1):
self._get_price()
Expand Down
10 changes: 4 additions & 6 deletions django_napse/core/tasks/base_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ def run(self):
def create_task(self) -> None:
"""Build task feed_bots_with_candles.
Raises
------
ValidationError: if task already exist
Raises:
ValidationError: if task already exist
"""
try:
schedule = IntervalSchedule.objects.get(every=self.interval_time, period=IntervalSchedule.SECONDS)
Expand All @@ -38,9 +37,8 @@ def create_task(self) -> None:
def delete_task(self) -> None:
"""Destroy task feed_bots_with_candles.
Raises
------
ValidationError: if task doesn't exist
Raises:
ValidationError: if task doesn't exist
"""
try:
PeriodicTask.objects.get(task=self.name).delete()
Expand Down
3 changes: 1 addition & 2 deletions django_napse/simulations/models/datasets/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ def create_candles(self, candles: list):
def set_downloading(self):
"""Set the dataset status to downloading.
Raises
------
Raises:
ValueError: If the dataset isn't in IDLE status.
"""
if self.status == DOWNLOAD_STATUS.IDLE:
Expand Down
1 change: 1 addition & 0 deletions django_napse/utils/api_test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def __init__(self, testcase_instance: APITestCase, *args, **kwargs):

def setup(self, data: dict | None = None):
def _setup(data=data):
# TODO: Add other methods (post, put, patch, delete)
return self.testcase_instance.client.get(
path=self.testcase_instance.url,
data=data,
Expand Down
8 changes: 8 additions & 0 deletions docs/SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Security

If you discover a security issue, no matter how big or small, please **do not open an issue or a pull request** !
Contact us asap at `[email protected]` or contact an administrator on the official discord server.

Thanks you in advance.

The Napse Team
1 change: 1 addition & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[OAD(./docs/schema.yml)]
Loading

0 comments on commit 7d8b10f

Please sign in to comment.