Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing arg #604

Merged
merged 7 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
runs-on: ubuntu-latest
services:
db:
image: mongo
image: mongo:latest
options: >-
--health-cmd mongosh
--health-interval 10s
Expand Down Expand Up @@ -65,7 +65,7 @@ jobs:
run: |
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker push carloswufei/binbot

deploy_streaming:
name: Deploy streaming
runs-on: ubuntu-latest
Expand Down Expand Up @@ -100,7 +100,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Build image
run: docker build --tag binbot_cronjobs -f Dockerfile.cronjobs .
- name: Test run script
Expand All @@ -124,7 +124,6 @@ jobs:
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker push carloswufei/binbot_cronjobs


python-tests:
name: Python code tests
runs-on: ubuntu-latest
Expand Down
33 changes: 30 additions & 3 deletions api/account/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@
from pymongo import MongoClient
import os
import pandas
from decimal import Decimal


class Account(BinbotApi):
def __init__(self):
self.db = setup_db()
self.price_precision = 0
self.qty_precision = 0
pass

def setup_mongocache(self):
Expand All @@ -28,6 +32,22 @@ def setup_mongocache(self):
mongo_cache = MongoCache(connection=mongo)
return mongo_cache

def calculate_price_precision(self, symbol):
self.price_precision = -1 * (
Decimal(str(self.price_filter_by_symbol(symbol, "tickSize")))
.as_tuple()
.exponent
)
return self.price_precision

def calculate_qty_precision(self, symbol):
self.qty_precision = -1 * (
Decimal(str(self.lot_size_by_symbol(symbol, "stepSize")))
.as_tuple()
.exponent
)
return self.qty_precision

def _exchange_info(self, symbol=None):
"""
This must be a separate method because classes use it with inheritance
Expand All @@ -45,7 +65,7 @@ def _exchange_info(self, symbol=None):

mongo_cache = self.setup_mongocache()
# set up a cache that expires in 1440'' (24hrs)
session = CachedSession('http_cache', backend=mongo_cache, expire_after=1440)
session = CachedSession("http_cache", backend=mongo_cache, expire_after=1440)
exchange_info_res = session.get(url=f"{self.exchangeinfo_url}", params=params)
exchange_info = handle_binance_errors(exchange_info_res)
return exchange_info
Expand All @@ -72,7 +92,6 @@ def get_ticker_price(self, symbol: str):
data = handle_binance_errors(res)
return data["price"]


def find_quoteAsset(self, symbol):
"""
e.g. BNBBTC: base asset = BTC
Expand Down Expand Up @@ -207,6 +226,14 @@ def get_one_balance(self, symbol="BTC"):
)
return symbol_balance

def get_margin_balance(self, symbol="BTC"):
# Response after request
data = self.get_isolated_balance(symbol)
symbol_balance = next(
(x["free"] for x in data["data"] if x["asset"] == symbol), None
)
return symbol_balance

def matching_engine(self, symbol: str, order_side: bool, qty=None):
"""
Match quantity with available 100% fill order price,
Expand All @@ -221,7 +248,7 @@ def matching_engine(self, symbol: str, order_side: bool, qty=None):
params = [("symbol", symbol)]
res = requests.get(url=self.order_book_url, params=params)
data = handle_binance_errors(res)

if order_side:
df = pandas.DataFrame(data["bids"], columns=["price", "qty"])
else:
Expand Down
30 changes: 20 additions & 10 deletions api/account/assets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime, timedelta
from bson.objectid import ObjectId
from fastapi.responses import JSONResponse
from account.controller import AssetsController
from tools.handle_error import json_response, json_response_error, json_response_message
from tools.round_numbers import round_numbers
Expand Down Expand Up @@ -52,7 +53,10 @@ def _check_locked(self, b):

def store_balance(self) -> dict:
"""
Alternative PnL data that runs as a cronjob everyday once at 12:00. Stores current balance in DB and estimated
Alternative PnL data that runs as a cronjob everyday once at 12:00.
This works outside of context.

Stores current balance in DB and estimated
total balance in fiat (USDC) for the day.

Better than deprecated store_balance_snapshot
Expand All @@ -61,21 +65,27 @@ def store_balance(self) -> dict:
- the result of total_usdc is pretty much the same, the difference is in 0.001 USDC
- however we don't need a loop and we decreased one network request (also added one, because we still need the raw_balance to display charts)
"""
# Store balance works outside of context as cronjob
fiat = self.get_fiat_coin()
wallet_balance = self.get_wallet_balance()
bin_balance = self.get_raw_balance()
rate = self.get_ticker_price('BTCUSDC')
itemized_balance = self.get_raw_balance()

rate = self.get_ticker_price(f'BTC{fiat}')

total_wallet_balance = 0
for item in wallet_balance:
if item["balance"] and float(item["balance"]) > 0:
total_wallet_balance += float(item["balance"])

total_wallet_balance = next((float(item["balance"]) for item in wallet_balance if float(item["balance"]) > 0), 0)
total_usdc = total_wallet_balance * float(rate)
response = self.create_balance_series(bin_balance, round_numbers(total_usdc, 4))
response = self.create_balance_series(itemized_balance, round_numbers(total_usdc, 4))
return response


def balance_estimate(self, fiat="USDC"):
def balance_estimate(self):
"""
Estimated balance in given fiat coin
"""
fiat = self.get_fiat_coin()
balances = self.get_raw_balance()
total_fiat = 0
left_to_allocate = 0
Expand Down Expand Up @@ -261,6 +271,7 @@ def get_total_fiat(self, fiat="USDC"):
float: total BTC estimated in the SPOT wallet
then converted into USDC
"""
fiat = self.get_fiat_coin()
wallet_balance = self.get_wallet_balance()
get_usdc_btc_rate = self.ticker(symbol=f"BTC{fiat}", json=False)
total_balance = 0
Expand Down Expand Up @@ -316,7 +327,7 @@ def disable_isolated_accounts(self, symbol=None):

return json_response_message(msg)

def one_click_liquidation(self, pair: str):
def one_click_liquidation(self, pair: str) -> JSONResponse:
"""
Emulate Binance Dashboard
One click liquidation function
Expand All @@ -327,8 +338,7 @@ def one_click_liquidation(self, pair: str):
"""

try:
self.symbol = pair
self.margin_liquidation(pair, self.qty_precision)
self.margin_liquidation(pair, self.qty_precision(pair))
return json_response_message(f"Successfully liquidated {pair}")
except MarginLoanNotFound as error:
return json_response_message(f"{error}. Successfully cleared isolated pair {pair}")
Expand Down
3 changes: 2 additions & 1 deletion api/autotrade/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
json_response_error,
json_response_message,
)
from tools.enum_definitions import AutotradeSettingsDocument

class AutotradeSettingsController(Database):
"""
Autotrade settings
"""

def __init__(
self, document_id: Literal["test_autotrade_settings", "settings"] = "settings"
self, document_id: AutotradeSettingsDocument = AutotradeSettingsDocument.settings
):
self.document_id = document_id
self.db = self._db
Expand Down
4 changes: 4 additions & 0 deletions api/bots/bots.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Test deactivation

DELETE http://localhost:8008/bot/deactivate/66edb7789c9b682fbfcd53cf HTTP/1.1
content-Type: application/json
Loading
Loading