Begin adding platform support
parent
ac483711c4
commit
1e7d8f6c8d
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,120 @@
|
|||||||
|
# Other library imports
|
||||||
|
from pyotp import TOTP
|
||||||
|
|
||||||
|
from core.clients.base import BaseClient
|
||||||
|
from core.clients.platform import LocalPlatformClient
|
||||||
|
from core.lib.money import Money
|
||||||
|
|
||||||
|
|
||||||
|
class AgoraClient(BaseClient, LocalPlatformClient):
|
||||||
|
"""
|
||||||
|
AgoraDesk API handler.
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def release_funds(self, contact_id):
|
||||||
|
"""
|
||||||
|
Release funds for a contact_id.
|
||||||
|
:param contact_id: trade/contact ID
|
||||||
|
:type contact_id: string
|
||||||
|
:return: response dict
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
print("CALLING RELEASE FUNDS", contact_id)
|
||||||
|
if self.instance.dummy:
|
||||||
|
self.log.error(
|
||||||
|
f"Running in dummy mode, not releasing funds for {contact_id}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
payload = {"tradeId": contact_id, "password": self.sets.Pass}
|
||||||
|
rtrn = await self.api._api_call(
|
||||||
|
api_method=f"contact_release/{contact_id}",
|
||||||
|
http_method="POST",
|
||||||
|
query_values=payload,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check if we can withdraw funds
|
||||||
|
await self.withdraw_funds()
|
||||||
|
|
||||||
|
return rtrn
|
||||||
|
|
||||||
|
# TODO: write test before re-enabling adding total_trades
|
||||||
|
async def withdraw_funds(self):
|
||||||
|
"""
|
||||||
|
Withdraw excess funds to our XMR wallets.
|
||||||
|
"""
|
||||||
|
print("CALLING WITHDRAW FUNDS")
|
||||||
|
totals_all = await self.money.get_total()
|
||||||
|
if totals_all is False:
|
||||||
|
return False
|
||||||
|
|
||||||
|
wallet_xmr, _ = totals_all[2]
|
||||||
|
|
||||||
|
# Get the wallet balances in USD
|
||||||
|
total_usd = totals_all[0][1]
|
||||||
|
|
||||||
|
# total_trades_usd = self.tx.get_open_trades_usd()
|
||||||
|
if not total_usd:
|
||||||
|
return False
|
||||||
|
# total_usd += total_trades_usd
|
||||||
|
|
||||||
|
profit_usd = total_usd - float(settings.Money.BaseUSD)
|
||||||
|
# Get the XMR -> USD exchange rate
|
||||||
|
xmr_usd = self.money.cg.get_price(ids="monero", vs_currencies=["USD"])
|
||||||
|
|
||||||
|
# Convert the USD total to XMR
|
||||||
|
profit_usd_in_xmr = float(profit_usd) / xmr_usd["monero"]["usd"]
|
||||||
|
|
||||||
|
# Check profit is above zero
|
||||||
|
if not profit_usd >= 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not float(wallet_xmr) > profit_usd_in_xmr:
|
||||||
|
# Not enough funds to withdraw
|
||||||
|
self.log.error(
|
||||||
|
(
|
||||||
|
f"Not enough funds to withdraw {profit_usd_in_xmr}, "
|
||||||
|
f"as wallet only contains {wallet_xmr}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.irc.sendmsg(
|
||||||
|
(
|
||||||
|
f"Not enough funds to withdraw {profit_usd_in_xmr}, "
|
||||||
|
f"as wallet only contains {wallet_xmr}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.ux.notify.notify_need_topup(profit_usd_in_xmr)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not profit_usd >= float(settings.Money.WithdrawLimit):
|
||||||
|
# Not enough profit to withdraw
|
||||||
|
return
|
||||||
|
|
||||||
|
half = profit_usd_in_xmr / 2
|
||||||
|
|
||||||
|
half_rounded = round(half, 8)
|
||||||
|
|
||||||
|
# Read OTP secret
|
||||||
|
with open("otp.key", "r") as f:
|
||||||
|
otp_key = f.read()
|
||||||
|
f.close()
|
||||||
|
otp_key = otp_key.replace("\n", "")
|
||||||
|
|
||||||
|
# Get OTP code
|
||||||
|
otp_code = TOTP(otp_key)
|
||||||
|
|
||||||
|
# Set up the format for calling wallet_send_xmr
|
||||||
|
send_cast = {
|
||||||
|
"address": None,
|
||||||
|
"amount": half_rounded,
|
||||||
|
"password": settings.Agora.Pass,
|
||||||
|
"otp": otp_code.now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
send_cast["address"] = settings.XMR.Wallet1
|
||||||
|
rtrn1 = await self.api.wallet_send_xmr(**send_cast)
|
||||||
|
|
||||||
|
send_cast["address"] = settings.XMR.Wallet2
|
||||||
|
rtrn2 = await self.api.wallet_send_xmr(**send_cast)
|
||||||
|
|
||||||
|
self.irc.sendmsg(f"Withdrawal: {rtrn1['success']} | {rtrn2['success']}")
|
||||||
|
self.ux.notify.notify_withdrawal(half_rounded)
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,111 @@
|
|||||||
|
# Project imports
|
||||||
|
from core.lib import db, notify
|
||||||
|
from core.util import logs
|
||||||
|
|
||||||
|
log = logs.get_logger("antifraud")
|
||||||
|
|
||||||
|
|
||||||
|
class AntiFraud(object):
|
||||||
|
async def add_bank_sender(self, platform, platform_buyer, bank_sender):
|
||||||
|
"""
|
||||||
|
Add the bank senders into Redis.
|
||||||
|
:param platform: name of the platform - freeform
|
||||||
|
:param platform_buyer: the username of the buyer on the platform
|
||||||
|
:param bank_sender: the sender name from the bank
|
||||||
|
"""
|
||||||
|
key = f"namemap.{platform}.{platform_buyer}"
|
||||||
|
await db.r.sadd(key, bank_sender)
|
||||||
|
|
||||||
|
async def get_previous_senders(self, platform, platform_buyer):
|
||||||
|
"""
|
||||||
|
Get all the previous bank sender names for the given buyer on the platform.
|
||||||
|
:param platform: name of the platform - freeform
|
||||||
|
:param platform_buyer: the username of the buyer on the platform
|
||||||
|
:return: set of previous buyers
|
||||||
|
:rtype: set
|
||||||
|
"""
|
||||||
|
key = f"namemap.{platform}.{platform_buyer}"
|
||||||
|
senders = await db.r.smembers(key)
|
||||||
|
if not senders:
|
||||||
|
return None
|
||||||
|
senders = db.convert(senders)
|
||||||
|
return senders
|
||||||
|
|
||||||
|
async def check_valid_sender(
|
||||||
|
self, reference, platform, bank_sender, platform_buyer
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Check that either:
|
||||||
|
* The platform buyer has never had a recognised transaction before
|
||||||
|
* The bank sender name matches a previous transaction from the platform buyer
|
||||||
|
:param reference: the trade reference
|
||||||
|
:param platform: name of the platform - freeform
|
||||||
|
:param bank_sender: the sender of the bank transaction
|
||||||
|
:param platform_buyer: the username of the buyer on the platform
|
||||||
|
:return: whether the sender is valid
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
senders = await self.get_previous_senders(platform, platform_buyer)
|
||||||
|
if senders is None: # no senders yet, assume it's valid
|
||||||
|
return True
|
||||||
|
if platform_buyer in senders:
|
||||||
|
return True
|
||||||
|
self.ux.notify.notify_sender_name_mismatch(
|
||||||
|
reference, platform_buyer, bank_sender
|
||||||
|
)
|
||||||
|
title = "Sender name mismatch"
|
||||||
|
message = (
|
||||||
|
f"Sender name mismatch for {reference}:\n"
|
||||||
|
f"Platform buyer: {platform_buyer}"
|
||||||
|
f"Bank sender: {bank_sender}"
|
||||||
|
)
|
||||||
|
# await notify.sendmsg(self.instance.) # TODO
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def check_tx_sender(self, tx, reference):
|
||||||
|
"""
|
||||||
|
Check whether the sender of a given transaction is authorised based on the previous
|
||||||
|
transactions of the username that originated the trade reference.
|
||||||
|
:param tx: the transaction ID
|
||||||
|
:param reference: the trade reference
|
||||||
|
"""
|
||||||
|
stored_trade = await db.get_ref(reference)
|
||||||
|
if not stored_trade:
|
||||||
|
return None
|
||||||
|
stored_tx = await db.get_tx(tx)
|
||||||
|
if not stored_tx:
|
||||||
|
return None
|
||||||
|
bank_sender = stored_tx["sender"]
|
||||||
|
platform_buyer = stored_trade["buyer"]
|
||||||
|
platform = stored_trade["subclass"]
|
||||||
|
is_allowed = await self.check_valid_sender(
|
||||||
|
reference, platform, bank_sender, platform_buyer
|
||||||
|
)
|
||||||
|
if is_allowed is True:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
# def user_verification_successful(self, uid):
|
||||||
|
# """
|
||||||
|
# A user has successfully completed verification.
|
||||||
|
# """
|
||||||
|
# self.log.info(f"User has completed verification: {uid}")
|
||||||
|
# trade_list = self.markets.find_trades_by_uid(uid)
|
||||||
|
# for platform, trade_id, reference, currency in trade_list:
|
||||||
|
# self.markets.send_bank_details(platform, currency, trade_id)
|
||||||
|
# self.markets.send_reference(platform, trade_id, reference)
|
||||||
|
|
||||||
|
# def send_verification_url(self, platform, uid, trade_id):
|
||||||
|
# send_setting, post_message = self.markets.get_send_settings(platform)
|
||||||
|
# if send_setting == "1":
|
||||||
|
# auth_url = self.ux.verify.create_applicant_and_get_link(uid)
|
||||||
|
# if platform == "lbtc":
|
||||||
|
# auth_url = auth_url.replace("https://", "") # hack
|
||||||
|
# post_message(
|
||||||
|
# trade_id,
|
||||||
|
# f"Hi! To continue the trade, please complete the verification form: {auth_url}",
|
||||||
|
# )
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
antifraud = AntiFraud()
|
@ -0,0 +1,497 @@
|
|||||||
|
# Twisted imports
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import urllib3
|
||||||
|
|
||||||
|
# Other library imports
|
||||||
|
from aiocoingecko import AsyncCoinGeckoAPISession
|
||||||
|
from django.conf import settings
|
||||||
|
from elasticsearch import AsyncElasticsearch
|
||||||
|
from forex_python.converter import CurrencyRates
|
||||||
|
|
||||||
|
# TODO: secure ES traffic properly
|
||||||
|
urllib3.disable_warnings()
|
||||||
|
|
||||||
|
tracer = logging.getLogger("opensearch")
|
||||||
|
tracer.setLevel(logging.CRITICAL)
|
||||||
|
tracer = logging.getLogger("elastic_transport.transport")
|
||||||
|
tracer.setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
|
|
||||||
|
class Money(object):
|
||||||
|
"""
|
||||||
|
Generic class for handling money-related matters that aren't Revolut or Agora.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""
|
||||||
|
Initialise the Money object.
|
||||||
|
Set the logger.
|
||||||
|
Initialise the CoinGecko API.
|
||||||
|
"""
|
||||||
|
print("MONEY INIT")
|
||||||
|
self.cr = CurrencyRates()
|
||||||
|
self.cg = AsyncCoinGeckoAPISession()
|
||||||
|
auth = (settings.ELASTICSEARCH_USERNAME, settings.ELASTICSEARCH_PASSWORD)
|
||||||
|
client = AsyncElasticsearch(
|
||||||
|
settings.ELASTICSEARCH_HOST, http_auth=auth, verify_certs=False
|
||||||
|
)
|
||||||
|
self.es = client
|
||||||
|
|
||||||
|
async def run_checks_in_thread(self):
|
||||||
|
"""
|
||||||
|
Run all the balance checks that output into ES in another thread.
|
||||||
|
"""
|
||||||
|
total = await self.get_total()
|
||||||
|
remaining = await self.get_remaining()
|
||||||
|
profit = await self.get_profit()
|
||||||
|
profit_with_trades = await self.get_profit(True)
|
||||||
|
open_trades = await self.get_open_trades_usd()
|
||||||
|
total_remaining = await self.get_total_remaining()
|
||||||
|
total_with_trades = await self.get_total_with_trades()
|
||||||
|
# This will make them all run concurrently, hopefully not hitting rate limits
|
||||||
|
for x in (
|
||||||
|
total,
|
||||||
|
remaining,
|
||||||
|
profit,
|
||||||
|
profit_with_trades,
|
||||||
|
open_trades,
|
||||||
|
total_remaining,
|
||||||
|
total_with_trades,
|
||||||
|
):
|
||||||
|
yield x
|
||||||
|
|
||||||
|
# def setup_loops(self):
|
||||||
|
# """
|
||||||
|
# Set up the LoopingCalls to get the balance so we have data in ES.
|
||||||
|
# """
|
||||||
|
# if settings.ES.Enabled == "1" or settings.Logstash.Enabled == "1":
|
||||||
|
# self.lc_es_checks = LoopingCall(self.run_checks_in_thread)
|
||||||
|
# delay = int(settings.ES.RefreshSec)
|
||||||
|
# self.lc_es_checks.start(delay)
|
||||||
|
# if settings.ES.Enabled == "1":
|
||||||
|
# self.agora.es = self.es
|
||||||
|
# self.lbtc.es = self.es
|
||||||
|
|
||||||
|
async def write_to_es(self, msgtype, cast):
|
||||||
|
cast["type"] = "money"
|
||||||
|
cast["ts"] = str(datetime.now().isoformat())
|
||||||
|
cast["xtype"] = msgtype
|
||||||
|
cast["user_id"] = self.instance.user.id
|
||||||
|
cast["platform_id"] = self.instance.id
|
||||||
|
await self.es.index(index=settings.ELASTICSEARCH_INDEX, body=cast)
|
||||||
|
|
||||||
|
async def lookup_rates(self, platform, ads, rates=None):
|
||||||
|
"""
|
||||||
|
Lookup the rates for a list of public ads.
|
||||||
|
"""
|
||||||
|
if not rates:
|
||||||
|
rates = await self.cg.get_price(
|
||||||
|
ids=["monero", "bitcoin"],
|
||||||
|
vs_currencies=self.markets.get_all_currencies(platform),
|
||||||
|
)
|
||||||
|
# Set the price based on the asset
|
||||||
|
for ad in ads:
|
||||||
|
if ad[4] == "XMR":
|
||||||
|
coin = "monero"
|
||||||
|
elif ad[4] == "BTC":
|
||||||
|
coin = "bitcoin" # No s here
|
||||||
|
currency = ad[5]
|
||||||
|
base_currency_price = rates[coin][currency.lower()]
|
||||||
|
price = float(ad[2])
|
||||||
|
rate = round(price / base_currency_price, 2)
|
||||||
|
ad.append(rate)
|
||||||
|
# TODO: sort?
|
||||||
|
return sorted(ads, key=lambda x: x[2])
|
||||||
|
|
||||||
|
async def get_rates_all(self):
|
||||||
|
"""
|
||||||
|
Get all rates that pair with USD.
|
||||||
|
:return: dictionary of USD/XXX rates
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
rates = await self.cr.get_rates("USD")
|
||||||
|
return rates
|
||||||
|
|
||||||
|
async def get_acceptable_margins(self, platform, currency, amount):
|
||||||
|
"""
|
||||||
|
Get the minimum and maximum amounts we would accept a trade for.
|
||||||
|
:param currency: currency code
|
||||||
|
:param amount: amount
|
||||||
|
:return: (min, max)
|
||||||
|
:rtype: tuple
|
||||||
|
"""
|
||||||
|
sets = util.get_settings(platform)
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
if currency == "USD":
|
||||||
|
min_amount = amount - float(sets.AcceptableUSDMargin)
|
||||||
|
max_amount = amount + float(sets.AcceptableUSDMargin)
|
||||||
|
return (min_amount, max_amount)
|
||||||
|
amount_usd = amount / rates[currency]
|
||||||
|
min_usd = amount_usd - float(sets.AcceptableUSDMargin)
|
||||||
|
max_usd = amount_usd + float(sets.AcceptableUSDMargin)
|
||||||
|
min_local = min_usd * rates[currency]
|
||||||
|
max_local = max_usd * rates[currency]
|
||||||
|
return (min_local, max_local)
|
||||||
|
|
||||||
|
async def get_minmax(self, platform, asset, currency):
|
||||||
|
sets = util.get_settings(platform)
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
if currency not in rates and not currency == "USD":
|
||||||
|
self.log.error(f"Can't create ad without rates: {currency}")
|
||||||
|
return
|
||||||
|
if asset == "XMR":
|
||||||
|
min_usd = float(sets.MinUSDXMR)
|
||||||
|
max_usd = float(sets.MaxUSDXMR)
|
||||||
|
elif asset == "BTC":
|
||||||
|
min_usd = float(sets.MinUSDBTC)
|
||||||
|
max_usd = float(sets.MaxUSDBTC)
|
||||||
|
if currency == "USD":
|
||||||
|
min_amount = min_usd
|
||||||
|
max_amount = max_usd
|
||||||
|
else:
|
||||||
|
min_amount = rates[currency] * min_usd
|
||||||
|
max_amount = rates[currency] * max_usd
|
||||||
|
|
||||||
|
return (min_amount, max_amount)
|
||||||
|
|
||||||
|
async def to_usd(self, amount, currency):
|
||||||
|
if currency == "USD":
|
||||||
|
return float(amount)
|
||||||
|
else:
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
return float(amount) / rates[currency]
|
||||||
|
|
||||||
|
async def multiple_to_usd(self, currency_map):
|
||||||
|
"""
|
||||||
|
Convert multiple curencies to USD while saving API calls.
|
||||||
|
"""
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
cumul = 0
|
||||||
|
for currency, amount in currency_map.items():
|
||||||
|
if currency == "USD":
|
||||||
|
cumul += float(amount)
|
||||||
|
else:
|
||||||
|
cumul += float(amount) / rates[currency]
|
||||||
|
return cumul
|
||||||
|
|
||||||
|
async def get_profit(self, trades=False):
|
||||||
|
"""
|
||||||
|
Check how much total profit we have made.
|
||||||
|
:return: profit in USD
|
||||||
|
:rtype: float
|
||||||
|
"""
|
||||||
|
total_usd = await self.get_total_usd()
|
||||||
|
if not total_usd:
|
||||||
|
return False
|
||||||
|
if trades:
|
||||||
|
trades_usd = await self.get_open_trades_usd()
|
||||||
|
total_usd += trades_usd
|
||||||
|
|
||||||
|
profit = total_usd - float(settings.Money.BaseUSD)
|
||||||
|
if trades:
|
||||||
|
cast_es = {
|
||||||
|
"profit_trades_usd": profit,
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
cast_es = {
|
||||||
|
"profit_usd": profit,
|
||||||
|
}
|
||||||
|
|
||||||
|
await self.write_to_es("get_profit", cast_es)
|
||||||
|
return profit
|
||||||
|
|
||||||
|
async def get_total_usd(self):
|
||||||
|
"""
|
||||||
|
Get total USD in all our accounts, bank and trading.
|
||||||
|
:return: value in USD
|
||||||
|
:rtype float:
|
||||||
|
"""
|
||||||
|
total_sinks_usd = await self.sinks.get_total_usd()
|
||||||
|
agora_wallet_xmr = await self.agora.api.wallet_balance_xmr()
|
||||||
|
agora_wallet_btc = await self.agora.api.wallet_balance()
|
||||||
|
# lbtc_wallet_btc = await self.lbtc.api.wallet_balance()
|
||||||
|
if not agora_wallet_xmr["success"]:
|
||||||
|
return False
|
||||||
|
if not agora_wallet_btc["success"]:
|
||||||
|
return False
|
||||||
|
# if not lbtc_wallet_btc["success"]:
|
||||||
|
# return False
|
||||||
|
if not agora_wallet_xmr["response"]:
|
||||||
|
return False
|
||||||
|
if not agora_wallet_btc["response"]:
|
||||||
|
return False
|
||||||
|
# if not lbtc_wallet_btc["response"]:
|
||||||
|
# return False
|
||||||
|
total_xmr_agora = agora_wallet_xmr["response"]["data"]["total"]["balance"]
|
||||||
|
total_btc_agora = agora_wallet_btc["response"]["data"]["total"]["balance"]
|
||||||
|
# total_btc_lbtc = lbtc_wallet_btc["response"]["data"]["total"]["balance"]
|
||||||
|
# Get the XMR -> USD exchange rate
|
||||||
|
xmr_usd = await self.cg.get_price(ids="monero", vs_currencies=["USD"])
|
||||||
|
|
||||||
|
# Get the BTC -> USD exchange rate
|
||||||
|
btc_usd = await self.cg.get_price(ids="bitcoin", vs_currencies=["USD"])
|
||||||
|
|
||||||
|
# Convert the Agora BTC total to USD
|
||||||
|
total_usd_agora_btc = float(total_btc_agora) * btc_usd["bitcoin"]["usd"]
|
||||||
|
|
||||||
|
# Convert the LBTC BTC total to USD
|
||||||
|
# total_usd_lbtc_btc = float(total_btc_lbtc) * btc_usd["bitcoin"]["usd"]
|
||||||
|
|
||||||
|
# Convert the Agora XMR total to USD
|
||||||
|
total_usd_agora_xmr = float(total_xmr_agora) * xmr_usd["monero"]["usd"]
|
||||||
|
|
||||||
|
# Add it all up
|
||||||
|
total_usd_agora = total_usd_agora_xmr + total_usd_agora_btc
|
||||||
|
# total_usd_lbtc = total_usd_lbtc_btc
|
||||||
|
total_usd = total_usd_agora + total_sinks_usd
|
||||||
|
# total_usd_lbtc +
|
||||||
|
cast_es = {
|
||||||
|
"price_usd": total_usd,
|
||||||
|
"total_usd_agora_xmr": total_usd_agora_xmr,
|
||||||
|
"total_usd_agora_btc": total_usd_agora_btc,
|
||||||
|
# "total_usd_lbtc_btc": total_usd_lbtc_btc,
|
||||||
|
"total_xmr_agora": total_xmr_agora,
|
||||||
|
"total_btc_agora": total_btc_agora,
|
||||||
|
# "total_btc_lbtc": total_btc_lbtc,
|
||||||
|
"xmr_usd": xmr_usd["monero"]["usd"],
|
||||||
|
"btc_usd": btc_usd["bitcoin"]["usd"],
|
||||||
|
"total_sinks_usd": total_sinks_usd,
|
||||||
|
"total_usd_agora": total_usd_agora,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_total_usd", cast_es)
|
||||||
|
return total_usd
|
||||||
|
|
||||||
|
# TODO: possibly refactor this into smaller functions which don't return as much
|
||||||
|
# check if this is all really needed in the corresponding withdraw function
|
||||||
|
async def get_total(self):
|
||||||
|
"""
|
||||||
|
Get all the values corresponding to the amount of money we hold.
|
||||||
|
:return: ((total SEK, total USD, total GBP),
|
||||||
|
(total XMR USD, total BTC USD),
|
||||||
|
(total XMR, total BTC))
|
||||||
|
:rtype: tuple(tuple(float, float, float),
|
||||||
|
tuple(float, float),
|
||||||
|
tuple(float, float))
|
||||||
|
"""
|
||||||
|
total_sinks_usd = await self.sinks.get_total_usd()
|
||||||
|
agora_wallet_xmr = await self.agora.api.wallet_balance_xmr()
|
||||||
|
agora_wallet_btc = await self.agora.api.wallet_balance()
|
||||||
|
# lbtc_wallet_btc = await self.lbtc.api.wallet_balance()
|
||||||
|
if not agora_wallet_xmr["success"]:
|
||||||
|
return False
|
||||||
|
if not agora_wallet_btc["success"]:
|
||||||
|
return False
|
||||||
|
# if not lbtc_wallet_btc["success"]:
|
||||||
|
# return False
|
||||||
|
if not agora_wallet_xmr["response"]:
|
||||||
|
return False
|
||||||
|
if not agora_wallet_btc["response"]:
|
||||||
|
return False
|
||||||
|
# if not lbtc_wallet_btc["response"]:
|
||||||
|
# return False
|
||||||
|
total_xmr_agora = agora_wallet_xmr["response"]["data"]["total"]["balance"]
|
||||||
|
total_btc_agora = agora_wallet_btc["response"]["data"]["total"]["balance"]
|
||||||
|
# total_btc_lbtc = lbtc_wallet_btc["response"]["data"]["total"]["balance"]
|
||||||
|
# Get the XMR -> USD exchange rate
|
||||||
|
xmr_usd = self.cg.get_price(ids="monero", vs_currencies=["USD"])
|
||||||
|
|
||||||
|
# Get the BTC -> USD exchange rate
|
||||||
|
btc_usd = self.cg.get_price(ids="bitcoin", vs_currencies=["USD"])
|
||||||
|
|
||||||
|
# Convert the Agora XMR total to USD
|
||||||
|
total_usd_agora_xmr = float(total_xmr_agora) * xmr_usd["monero"]["usd"]
|
||||||
|
|
||||||
|
# Convert the Agora BTC total to USD
|
||||||
|
total_usd_agora_btc = float(total_btc_agora) * btc_usd["bitcoin"]["usd"]
|
||||||
|
|
||||||
|
# Convert the LBTC BTC total to USD
|
||||||
|
# total_usd_lbtc_btc = float(total_btc_lbtc) * btc_usd["bitcoin"]["usd"]
|
||||||
|
|
||||||
|
# Add it all up
|
||||||
|
total_usd_agora = total_usd_agora_xmr + total_usd_agora_btc
|
||||||
|
# total_usd_lbtc = total_usd_lbtc_btc
|
||||||
|
total_usd = total_usd_agora + total_sinks_usd
|
||||||
|
# total_usd_lbtc
|
||||||
|
|
||||||
|
total_btc_usd = total_usd_agora_btc # + total_usd_lbtc_btc
|
||||||
|
total_xmr_usd = total_usd_agora_xmr
|
||||||
|
|
||||||
|
total_xmr = total_xmr_agora
|
||||||
|
total_btc = total_btc_agora
|
||||||
|
# total_btc_lbtc
|
||||||
|
|
||||||
|
# Convert the total USD price to GBP and SEK
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
price_sek = rates["SEK"] * total_usd
|
||||||
|
price_usd = total_usd
|
||||||
|
price_gbp = rates["GBP"] * total_usd
|
||||||
|
|
||||||
|
cast = (
|
||||||
|
(
|
||||||
|
price_sek,
|
||||||
|
price_usd,
|
||||||
|
price_gbp,
|
||||||
|
), # Total prices in our 3 favourite currencies
|
||||||
|
(
|
||||||
|
total_xmr_usd,
|
||||||
|
total_btc_usd,
|
||||||
|
), # Total USD balance in only Agora
|
||||||
|
(total_xmr, total_btc),
|
||||||
|
) # Total XMR and BTC balance in Agora
|
||||||
|
|
||||||
|
cast_es = {
|
||||||
|
"price_sek": price_sek,
|
||||||
|
"price_usd": price_usd,
|
||||||
|
"price_gbp": price_gbp,
|
||||||
|
"total_usd_agora_xmr": total_usd_agora_xmr,
|
||||||
|
"total_usd_agora_btc": total_usd_agora_btc,
|
||||||
|
# "total_usd_lbtc_btc": total_usd_lbtc_btc,
|
||||||
|
"total_xmr_agora": total_xmr_agora,
|
||||||
|
"total_btc_agora": total_btc_agora,
|
||||||
|
# "total_btc_lbtc": total_btc_lbtc,
|
||||||
|
"xmr_usd": xmr_usd["monero"]["usd"],
|
||||||
|
"btc_usd": btc_usd["bitcoin"]["usd"],
|
||||||
|
"total_sinks_usd": total_sinks_usd,
|
||||||
|
"total_usd_agora": total_usd_agora,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_total", cast_es)
|
||||||
|
return cast
|
||||||
|
|
||||||
|
async def get_remaining(self):
|
||||||
|
"""
|
||||||
|
Check how much profit we need to make in order to withdraw.
|
||||||
|
:return: profit remaining in USD
|
||||||
|
:rtype: float
|
||||||
|
"""
|
||||||
|
total_usd = await self.get_total_usd()
|
||||||
|
if not total_usd:
|
||||||
|
return False
|
||||||
|
|
||||||
|
withdraw_threshold = float(settings.Money.BaseUSD) + float(
|
||||||
|
settings.Money.WithdrawLimit
|
||||||
|
)
|
||||||
|
remaining = withdraw_threshold - total_usd
|
||||||
|
cast_es = {
|
||||||
|
"remaining_usd": remaining,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_remaining", cast_es)
|
||||||
|
return remaining
|
||||||
|
|
||||||
|
async def open_trades_usd_parse_dash(self, platform, dash, rates):
|
||||||
|
cumul_usd = 0
|
||||||
|
for contact_id, contact in dash.items():
|
||||||
|
# We need created at in order to look up the historical prices
|
||||||
|
created_at = contact["data"]["created_at"]
|
||||||
|
|
||||||
|
# Reformat the date how CoinGecko likes
|
||||||
|
# 2022-05-02T11:17:14+00:00
|
||||||
|
if "+" in created_at:
|
||||||
|
date_split = created_at.split("+")
|
||||||
|
date_split[1].replace(".", "")
|
||||||
|
date_split[1].replace(":", "")
|
||||||
|
created_at = "+".join(date_split)
|
||||||
|
date_parsed = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S%z")
|
||||||
|
else:
|
||||||
|
date_parsed = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ")
|
||||||
|
|
||||||
|
date_formatted = date_parsed.strftime("%d-%m-%Y")
|
||||||
|
|
||||||
|
# Get the historical rates for the right asset, extract the price
|
||||||
|
if platform == "agora":
|
||||||
|
asset = contact["data"]["advertisement"]["asset"]
|
||||||
|
elif platform == "lbtc":
|
||||||
|
asset = "BTC"
|
||||||
|
if asset == "XMR":
|
||||||
|
amount_crypto = contact["data"]["amount_xmr"]
|
||||||
|
history = await self.cg.get_coin_history_by_id(
|
||||||
|
id="monero", date=date_formatted
|
||||||
|
)
|
||||||
|
if "market_data" not in history:
|
||||||
|
return False
|
||||||
|
crypto_usd = float(history["market_data"]["current_price"]["usd"])
|
||||||
|
elif asset == "BTC":
|
||||||
|
amount_crypto = contact["data"]["amount_btc"]
|
||||||
|
history = await self.cg.get_coin_history_by_id(
|
||||||
|
id="bitcoin", date=date_formatted
|
||||||
|
)
|
||||||
|
crypto_usd = float(history["market_data"]["current_price"]["usd"])
|
||||||
|
# Convert crypto to fiat
|
||||||
|
amount = float(amount_crypto) * crypto_usd
|
||||||
|
currency = contact["data"]["currency"]
|
||||||
|
if not contact["data"]["is_selling"]:
|
||||||
|
continue
|
||||||
|
if currency == "USD":
|
||||||
|
cumul_usd += float(amount)
|
||||||
|
else:
|
||||||
|
rate = rates[currency]
|
||||||
|
amount_usd = float(amount) / rate
|
||||||
|
cumul_usd += amount_usd
|
||||||
|
return cumul_usd
|
||||||
|
|
||||||
|
async def get_open_trades_usd(self):
|
||||||
|
"""
|
||||||
|
Get total value of open trades in USD.
|
||||||
|
:return: total trade value
|
||||||
|
:rtype: float
|
||||||
|
"""
|
||||||
|
dash_agora = await self.agora.wrap_dashboard()
|
||||||
|
# dash_lbtc = self.lbtc.wrap_dashboard()
|
||||||
|
# dash_lbtc = yield dash_lbtc
|
||||||
|
if dash_agora is False:
|
||||||
|
return False
|
||||||
|
# if dash_lbtc is False:
|
||||||
|
# return False
|
||||||
|
|
||||||
|
rates = await self.get_rates_all()
|
||||||
|
cumul_usd_agora = await self.open_trades_usd_parse_dash(
|
||||||
|
"agora", dash_agora, rates
|
||||||
|
)
|
||||||
|
# cumul_usd_lbtc = await self.open_trades_usd_parse_dash("lbtc", dash_lbtc,
|
||||||
|
# rates)
|
||||||
|
cumul_usd = cumul_usd_agora # + cumul_usd_lbtc
|
||||||
|
|
||||||
|
cast_es = {
|
||||||
|
"trades_usd": cumul_usd,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_open_trades_usd", cast_es)
|
||||||
|
return cumul_usd
|
||||||
|
|
||||||
|
async def get_total_remaining(self):
|
||||||
|
"""
|
||||||
|
Check how much profit we need to make in order to withdraw, taking into account
|
||||||
|
open trade value.
|
||||||
|
:return: profit remaining in USD
|
||||||
|
:rtype: float
|
||||||
|
"""
|
||||||
|
total_usd = await self.get_total_usd()
|
||||||
|
total_trades_usd = await self.get_open_trades_usd()
|
||||||
|
if not total_usd:
|
||||||
|
return False
|
||||||
|
total_usd += total_trades_usd
|
||||||
|
withdraw_threshold = float(settings.Money.BaseUSD) + float(
|
||||||
|
settings.Money.WithdrawLimit
|
||||||
|
)
|
||||||
|
remaining = withdraw_threshold - total_usd
|
||||||
|
|
||||||
|
cast_es = {
|
||||||
|
"total_remaining_usd": remaining,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_total_remaining", cast_es)
|
||||||
|
return remaining
|
||||||
|
|
||||||
|
async def get_total_with_trades(self):
|
||||||
|
total_usd = await self.get_total_usd()
|
||||||
|
if not total_usd:
|
||||||
|
return False
|
||||||
|
total_trades_usd = await self.get_open_trades_usd()
|
||||||
|
total_with_trades = total_usd + total_trades_usd
|
||||||
|
cast_es = {
|
||||||
|
"total_with_trades": total_with_trades,
|
||||||
|
}
|
||||||
|
await self.write_to_es("get_total_with_trades", cast_es)
|
||||||
|
return total_with_trades
|
||||||
|
|
||||||
|
|
||||||
|
money = Money()
|
@ -0,0 +1,42 @@
|
|||||||
|
# Generated by Django 4.1.7 on 2023-03-09 20:50
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('core', '0007_alter_aggregator_account_info_and_more'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Platform',
|
||||||
|
fields=[
|
||||||
|
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||||
|
('name', models.CharField(max_length=255)),
|
||||||
|
('service', models.CharField(choices=[('agora', 'Agora')], max_length=255)),
|
||||||
|
('token', models.CharField(max_length=1024)),
|
||||||
|
('password', models.CharField(max_length=1024)),
|
||||||
|
('otp_token', models.CharField(blank=True, max_length=1024, null=True)),
|
||||||
|
('username', models.CharField(max_length=255)),
|
||||||
|
('send', models.BooleanField(default=True)),
|
||||||
|
('cheat', models.BooleanField(default=False)),
|
||||||
|
('dummy', models.BooleanField(default=False)),
|
||||||
|
('cheat_interval_seconds', models.IntegerField(default=600)),
|
||||||
|
('margin', models.FloatField(default=1.2)),
|
||||||
|
('max_margin', models.FloatField(default=1.3)),
|
||||||
|
('min_margin', models.FloatField(default=1.15)),
|
||||||
|
('min_trade_size_usd', models.FloatField(default=10)),
|
||||||
|
('max_trade_size_usd', models.FloatField(default=4000)),
|
||||||
|
('accept_within_usd', models.FloatField(default=1)),
|
||||||
|
('no_reference_amount_check_max_usd', models.FloatField(default=400)),
|
||||||
|
('enabled', models.BooleanField(default=True)),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
@ -0,0 +1,81 @@
|
|||||||
|
{% load cache %}
|
||||||
|
{% load cachalot cache %}
|
||||||
|
{% get_last_invalidation 'core.Platform' as last %}
|
||||||
|
{% include 'mixins/partials/notify.html' %}
|
||||||
|
{# cache 600 objects_platforms request.user.id object_list type last #}
|
||||||
|
<table
|
||||||
|
class="table is-fullwidth is-hoverable"
|
||||||
|
hx-target="#{{ context_object_name }}-table"
|
||||||
|
id="{{ context_object_name }}-table"
|
||||||
|
hx-swap="outerHTML"
|
||||||
|
hx-trigger="{{ context_object_name_singular }}Event from:body"
|
||||||
|
hx-get="{{ list_url }}">
|
||||||
|
<thead>
|
||||||
|
<th>id</th>
|
||||||
|
<th>user</th>
|
||||||
|
<th>name</th>
|
||||||
|
<th>service</th>
|
||||||
|
<th>enabled</th>
|
||||||
|
<th>actions</th>
|
||||||
|
</thead>
|
||||||
|
{% for item in object_list %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a
|
||||||
|
class="has-text-grey"
|
||||||
|
onclick="window.prompt('Copy to clipboard: Ctrl+C, Enter', '{{ item.id }}/');">
|
||||||
|
<span class="icon" data-tooltip="Copy to clipboard">
|
||||||
|
<i class="fa-solid fa-copy" aria-hidden="true"></i>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>{{ item.user }}</td>
|
||||||
|
<td>{{ item.name }}</td>
|
||||||
|
<td>{{ item.get_service_display }}</td>
|
||||||
|
<td>
|
||||||
|
{% if item.enabled %}
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fa-solid fa-check"></i>
|
||||||
|
</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fa-solid fa-xmark"></i>
|
||||||
|
</span>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div class="buttons">
|
||||||
|
<button
|
||||||
|
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||||
|
hx-get="{% url 'platform_update' type=type pk=item.id %}"
|
||||||
|
hx-trigger="click"
|
||||||
|
hx-target="#{{ type }}s-here"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
class="button">
|
||||||
|
<span class="icon-text">
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fa-solid fa-pencil"></i>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
|
||||||
|
hx-delete="{% url 'platform_delete' type=type pk=item.id %}"
|
||||||
|
hx-trigger="click"
|
||||||
|
hx-target="#modals-here"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-confirm="Are you sure you wish to delete {{ item.name }}?"
|
||||||
|
class="button">
|
||||||
|
<span class="icon-text">
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fa-solid fa-xmark"></i>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
</table>
|
||||||
|
{# endcache #}
|
@ -0,0 +1,50 @@
|
|||||||
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||||
|
from django.http import HttpResponse
|
||||||
|
from django.shortcuts import render
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.views import View
|
||||||
|
from mixins.views import ( # ObjectRead,
|
||||||
|
ObjectCreate,
|
||||||
|
ObjectDelete,
|
||||||
|
ObjectList,
|
||||||
|
ObjectUpdate,
|
||||||
|
)
|
||||||
|
from two_factor.views.mixins import OTPRequiredMixin
|
||||||
|
|
||||||
|
# from core.clients.platforms.agora import AgoraClient
|
||||||
|
from core.forms import PlatformForm
|
||||||
|
from core.models import Platform
|
||||||
|
from core.util import logs
|
||||||
|
|
||||||
|
# from core.views.helpers import synchronize_async_helper
|
||||||
|
|
||||||
|
log = logs.get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformList(LoginRequiredMixin, OTPRequiredMixin, ObjectList):
|
||||||
|
list_template = "partials/platform-list.html"
|
||||||
|
model = Platform
|
||||||
|
page_title = "List of platform connections"
|
||||||
|
|
||||||
|
list_url_name = "platforms"
|
||||||
|
list_url_args = ["type"]
|
||||||
|
|
||||||
|
submit_url_name = "platform_create"
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformCreate(LoginRequiredMixin, OTPRequiredMixin, ObjectCreate):
|
||||||
|
model = Platform
|
||||||
|
form_class = PlatformForm
|
||||||
|
|
||||||
|
submit_url_name = "platform_create"
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformUpdate(LoginRequiredMixin, OTPRequiredMixin, ObjectUpdate):
|
||||||
|
model = Platform
|
||||||
|
form_class = PlatformForm
|
||||||
|
|
||||||
|
submit_url_name = "platform_update"
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformDelete(LoginRequiredMixin, OTPRequiredMixin, ObjectDelete):
|
||||||
|
model = Platform
|
Loading…
Reference in New Issue