2021-12-23 18:46:39 +00:00
|
|
|
# Twisted/Klein imports
|
2022-02-18 08:41:32 +00:00
|
|
|
from twisted.internet.task import LoopingCall
|
|
|
|
from twisted.internet.threads import deferToThread
|
2021-12-23 18:46:39 +00:00
|
|
|
|
|
|
|
# Other library imports
|
|
|
|
from json import dumps
|
2021-12-28 15:29:15 +00:00
|
|
|
from random import choices
|
|
|
|
from string import ascii_uppercase
|
2022-02-17 22:03:48 +00:00
|
|
|
from elasticsearch import Elasticsearch
|
|
|
|
from datetime import datetime
|
2022-02-17 22:10:31 +00:00
|
|
|
import urllib3
|
2022-02-25 00:06:10 +00:00
|
|
|
import logging
|
2022-02-17 22:10:31 +00:00
|
|
|
|
2021-12-23 18:46:39 +00:00
|
|
|
# Project imports
|
2021-12-28 23:58:00 +00:00
|
|
|
from settings import settings
|
2021-12-23 18:46:39 +00:00
|
|
|
from db import r
|
2022-03-05 21:52:31 +00:00
|
|
|
import util
|
2021-12-27 21:04:57 +00:00
|
|
|
|
2022-02-17 22:59:11 +00:00
|
|
|
# TODO: secure ES traffic properly
|
|
|
|
urllib3.disable_warnings()
|
|
|
|
|
2022-02-25 00:06:10 +00:00
|
|
|
tracer = logging.getLogger("elasticsearch")
|
|
|
|
tracer.setLevel(logging.CRITICAL)
|
|
|
|
tracer = logging.getLogger("elastic_transport.transport")
|
|
|
|
tracer.setLevel(logging.CRITICAL)
|
|
|
|
|
2021-12-27 21:04:57 +00:00
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
class Transactions(util.Base):
|
2021-12-23 18:46:39 +00:00
|
|
|
"""
|
|
|
|
Handler class for incoming Revolut transactions.
|
|
|
|
"""
|
|
|
|
|
2021-12-27 20:59:24 +00:00
|
|
|
def __init__(self):
|
2021-12-27 21:28:49 +00:00
|
|
|
"""
|
|
|
|
Initialise the Transaction object.
|
|
|
|
Set the logger.
|
|
|
|
"""
|
2022-03-05 21:52:31 +00:00
|
|
|
super().__init__()
|
2022-02-22 19:21:29 +00:00
|
|
|
if settings.ES.Enabled == "1":
|
|
|
|
self.es = Elasticsearch(
|
|
|
|
f"https://{settings.ES.Host}:9200",
|
|
|
|
verify_certs=False,
|
|
|
|
basic_auth=(settings.ES.Username, settings.ES.Pass),
|
|
|
|
# ssl_assert_fingerprint=("6b264fd2fd107d45652d8add1750a8a78f424542e13b056d0548173006260710"),
|
|
|
|
ca_certs="certs/ca.crt",
|
|
|
|
)
|
2021-12-27 20:59:24 +00:00
|
|
|
|
2022-02-18 08:41:32 +00:00
|
|
|
def run_checks_in_thread(self):
|
|
|
|
"""
|
|
|
|
Run all the balance checks that output into ES in another thread.
|
|
|
|
"""
|
|
|
|
deferToThread(self.get_total)
|
|
|
|
deferToThread(self.get_remaining)
|
2022-02-25 00:06:10 +00:00
|
|
|
deferToThread(self.money.get_profit)
|
|
|
|
deferToThread(self.money.get_profit, True)
|
2022-02-18 08:41:32 +00:00
|
|
|
deferToThread(self.get_open_trades_usd)
|
|
|
|
deferToThread(self.get_total_remaining)
|
|
|
|
deferToThread(self.get_total_with_trades)
|
|
|
|
|
|
|
|
def setup_loops(self):
|
|
|
|
"""
|
|
|
|
Set up the LoopingCalls to get the balance so we have data in ES.
|
|
|
|
"""
|
2022-02-22 19:21:29 +00:00
|
|
|
if settings.ES.Enabled == "1":
|
|
|
|
self.lc_es_checks = LoopingCall(self.run_checks_in_thread)
|
|
|
|
delay = int(settings.ES.RefreshSec)
|
|
|
|
self.lc_es_checks.start(delay)
|
2022-02-28 19:59:18 +00:00
|
|
|
self.agora.es = self.es
|
2022-02-18 08:41:32 +00:00
|
|
|
|
2022-02-15 21:50:34 +00:00
|
|
|
# TODO: write tests then refactor, this is terribly complicated!
|
2021-12-23 18:46:39 +00:00
|
|
|
def transaction(self, data):
|
|
|
|
"""
|
2021-12-28 23:58:00 +00:00
|
|
|
Store details of transaction and post notifications to IRC.
|
|
|
|
Matches it up with data stored in Redis to attempt to reconcile with an Agora trade.
|
2021-12-27 21:20:15 +00:00
|
|
|
:param data: details of transaction
|
|
|
|
:type data: dict
|
2021-12-23 18:46:39 +00:00
|
|
|
"""
|
|
|
|
event = data["event"]
|
|
|
|
ts = data["timestamp"]
|
|
|
|
|
2022-02-24 22:26:16 +00:00
|
|
|
if "data" not in data:
|
|
|
|
return
|
2021-12-23 18:46:39 +00:00
|
|
|
inside = data["data"]
|
2022-01-25 18:39:35 +00:00
|
|
|
|
2021-12-23 18:46:39 +00:00
|
|
|
txid = inside["id"]
|
2022-01-25 18:39:35 +00:00
|
|
|
|
2022-01-05 19:24:15 +00:00
|
|
|
if "type" not in inside:
|
2022-02-14 20:37:17 +00:00
|
|
|
# stored_trade here is actually TX
|
2022-01-25 17:53:56 +00:00
|
|
|
stored_trade = r.hgetall(f"tx.{txid}")
|
|
|
|
if not stored_trade:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error(f"Could not find entry in DB for typeless transaction: {txid}")
|
2022-01-25 17:53:56 +00:00
|
|
|
return
|
2022-03-05 21:52:31 +00:00
|
|
|
stored_trade = util.convert(stored_trade)
|
2022-01-25 17:53:56 +00:00
|
|
|
if "old_state" in inside:
|
|
|
|
if "new_state" in inside:
|
|
|
|
# We don't care unless we're being told a transaction is now completed
|
|
|
|
if not inside["new_state"] == "completed":
|
|
|
|
return
|
|
|
|
# We don't care unless the existing trade is pending
|
|
|
|
if not stored_trade["state"] == "pending":
|
|
|
|
return
|
|
|
|
# Check the old state is what we also think it is
|
|
|
|
if inside["old_state"] == stored_trade["state"]:
|
|
|
|
# Set the state to the new state
|
|
|
|
stored_trade["state"] = inside["new_state"]
|
|
|
|
# Store the updated state
|
|
|
|
r.hmset(f"tx.{txid}", stored_trade)
|
|
|
|
# Check it's all been previously validated
|
|
|
|
if "valid" not in stored_trade:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error(f"Valid not in stored trade for {txid}, aborting.")
|
2022-02-15 21:30:45 +00:00
|
|
|
return
|
2022-02-14 06:52:31 +00:00
|
|
|
if stored_trade["valid"] == "1":
|
2022-02-14 20:37:17 +00:00
|
|
|
# Make it invalid immediately, as we're going to release now
|
|
|
|
stored_trade["valid"] = "0"
|
|
|
|
r.hmset(f"tx.{txid}", stored_trade)
|
|
|
|
reference = self.tx_to_ref(stored_trade["trade_id"])
|
|
|
|
self.release_funds(stored_trade["trade_id"], reference)
|
2022-03-04 22:47:06 +00:00
|
|
|
self.ux.notify.notify_complete_trade(stored_trade["amount"], stored_trade["currency"])
|
2022-01-25 17:53:56 +00:00
|
|
|
return
|
|
|
|
# If type not in inside and we haven't hit any more returns
|
2022-01-05 19:24:15 +00:00
|
|
|
return
|
2022-02-13 23:01:44 +00:00
|
|
|
else:
|
|
|
|
txtype = inside["type"]
|
|
|
|
if txtype == "card_payment":
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Ignoring card payment: {txid}")
|
2022-02-13 23:01:44 +00:00
|
|
|
return
|
2022-01-25 18:39:35 +00:00
|
|
|
|
2021-12-23 18:46:39 +00:00
|
|
|
state = inside["state"]
|
2021-12-28 14:09:33 +00:00
|
|
|
if "reference" in inside:
|
|
|
|
reference = inside["reference"]
|
|
|
|
else:
|
|
|
|
reference = "not_given"
|
2021-12-23 18:46:39 +00:00
|
|
|
|
|
|
|
leg = inside["legs"][0]
|
|
|
|
|
2021-12-28 14:09:33 +00:00
|
|
|
if "counterparty" in leg:
|
|
|
|
account_type = leg["counterparty"]["account_type"]
|
|
|
|
else:
|
|
|
|
account_type = "not_given"
|
2021-12-23 18:46:39 +00:00
|
|
|
|
|
|
|
amount = leg["amount"]
|
2022-01-25 13:01:39 +00:00
|
|
|
if amount <= 0:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Ignoring transaction with negative/zero amount: {txid}")
|
2022-01-25 13:01:39 +00:00
|
|
|
return
|
2021-12-23 18:46:39 +00:00
|
|
|
currency = leg["currency"]
|
|
|
|
description = leg["description"]
|
|
|
|
|
|
|
|
to_store = {
|
|
|
|
"event": event,
|
2022-01-25 17:53:56 +00:00
|
|
|
"trade_id": "",
|
2021-12-23 18:46:39 +00:00
|
|
|
"ts": ts,
|
|
|
|
"txid": txid,
|
|
|
|
"txtype": txtype,
|
|
|
|
"state": state,
|
|
|
|
"reference": reference,
|
|
|
|
"account_type": account_type,
|
|
|
|
"amount": amount,
|
|
|
|
"currency": currency,
|
|
|
|
"description": description,
|
2022-01-25 17:53:56 +00:00
|
|
|
"valid": 0, # All checks passed and we can release escrow?
|
2021-12-23 18:46:39 +00:00
|
|
|
}
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Transaction processed: {dumps(to_store, indent=2)}")
|
2022-01-01 16:39:36 +00:00
|
|
|
self.irc.sendmsg(f"AUTO Incoming transaction: {amount}{currency} ({reference}) - {state} - {description}")
|
2022-01-01 19:33:15 +00:00
|
|
|
# Partial reference implementation
|
2022-01-01 19:20:20 +00:00
|
|
|
# Account for silly people not removing the default string
|
|
|
|
# Split the reference into parts
|
|
|
|
ref_split = reference.split(" ")
|
|
|
|
# Get all existing references
|
|
|
|
existing_refs = self.get_refs()
|
|
|
|
# Get all parts of the given reference split that match the existing references
|
|
|
|
stored_trade_reference = set(existing_refs).intersection(set(ref_split))
|
|
|
|
if len(stored_trade_reference) > 1:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error(f"Multiple references valid for TXID {txid}: {reference}")
|
2022-01-01 19:20:20 +00:00
|
|
|
self.irc.sendmsg(f"Multiple references valid for TXID {txid}: {reference}")
|
|
|
|
return
|
|
|
|
|
|
|
|
stored_trade = False
|
2022-01-01 19:33:15 +00:00
|
|
|
looked_up_without_reference = False
|
|
|
|
|
|
|
|
# Amount/currency lookup implementation
|
2022-01-01 19:20:20 +00:00
|
|
|
if not stored_trade_reference:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"No reference in DB refs for {reference}")
|
2022-01-01 19:20:20 +00:00
|
|
|
self.irc.sendmsg(f"No reference in DB refs for {reference}")
|
|
|
|
# Try checking just amount and currency, as some people (usually people buying small amounts)
|
|
|
|
# are unable to put in a reference properly.
|
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Checking against amount and currency for TXID {txid}")
|
2022-01-01 19:20:20 +00:00
|
|
|
self.irc.sendmsg(f"Checking against amount and currency for TXID {txid}")
|
|
|
|
stored_trade = self.find_trade(txid, currency, amount)
|
|
|
|
if not stored_trade:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Failed to get reference by amount and currency: {txid} {currency} {amount}")
|
2022-01-01 19:20:20 +00:00
|
|
|
self.irc.sendmsg(f"Failed to get reference by amount and currency: {txid} {currency} {amount}")
|
|
|
|
return
|
2022-01-01 20:01:01 +00:00
|
|
|
if currency == "USD":
|
|
|
|
amount_usd = amount
|
|
|
|
else:
|
2022-02-22 20:10:47 +00:00
|
|
|
rates = self.money.get_rates_all()
|
2022-01-01 20:01:01 +00:00
|
|
|
amount_usd = amount / rates[currency]
|
|
|
|
# Amount is reliable here as it is checked by find_trade, so no need for stored_trade["amount"]
|
2022-01-01 20:22:53 +00:00
|
|
|
if float(amount_usd) > float(settings.Agora.AcceptableAltLookupUSD):
|
2022-01-01 19:20:20 +00:00
|
|
|
self.log.info("Not checking against amount and currency as amount exceeds MAX")
|
|
|
|
self.irc.sendmsg(f"Not checking against amount and currency as amount exceeds MAX")
|
|
|
|
# Close here if the amount exceeds the allowable limit for no reference
|
|
|
|
return
|
2022-01-01 19:33:15 +00:00
|
|
|
# Note that we have looked it up without reference so we don't use +- below
|
2022-01-01 20:01:01 +00:00
|
|
|
# This might be redundant given the amount checks in find_trade, but better safe than sorry!
|
2022-01-01 19:33:15 +00:00
|
|
|
looked_up_without_reference = True
|
2022-01-01 19:20:20 +00:00
|
|
|
if not stored_trade:
|
|
|
|
stored_trade = self.get_ref(stored_trade_reference.pop())
|
2021-12-28 17:47:07 +00:00
|
|
|
if not stored_trade:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"No reference in DB for {reference}")
|
2022-01-01 16:39:36 +00:00
|
|
|
self.irc.sendmsg(f"No reference in DB for {reference}")
|
2021-12-28 17:47:07 +00:00
|
|
|
return
|
2021-12-29 15:26:23 +00:00
|
|
|
|
2021-12-28 17:47:07 +00:00
|
|
|
amount = float(amount)
|
|
|
|
stored_trade["amount"] = float(stored_trade["amount"])
|
2021-12-29 15:32:38 +00:00
|
|
|
|
|
|
|
# Make sure it was sent in the expected currency
|
2021-12-28 15:29:15 +00:00
|
|
|
if not stored_trade["currency"] == currency:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}")
|
2022-03-04 22:21:12 +00:00
|
|
|
self.irc.sendmsg(f"Currency mismatch, Agora: {stored_trade['currency']} / Sink: {currency}")
|
2021-12-28 15:29:15 +00:00
|
|
|
return
|
2021-12-29 15:32:38 +00:00
|
|
|
|
|
|
|
# Make sure the expected amount was sent
|
2021-12-28 15:29:15 +00:00
|
|
|
if not stored_trade["amount"] == amount:
|
2022-01-01 19:33:15 +00:00
|
|
|
if looked_up_without_reference:
|
|
|
|
return
|
2021-12-28 23:58:00 +00:00
|
|
|
# If the amount does not match exactly, get the min and max values for our given acceptable margins for trades
|
2022-02-24 22:26:16 +00:00
|
|
|
min_amount, max_amount = self.money.get_acceptable_margins(currency, stored_trade["amount"])
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}")
|
2022-01-01 16:39:36 +00:00
|
|
|
self.irc.sendmsg(f"Amount does not match exactly, trying with margins: min: {min_amount} / max: {max_amount}")
|
2022-02-24 22:26:16 +00:00
|
|
|
if not min_amount < amount < max_amount:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info("Amount mismatch - not in margins: {stored_trade['amount']} (min: {min_amount} / max: {max_amount}")
|
2022-01-01 16:39:36 +00:00
|
|
|
self.irc.sendmsg(f"Amount mismatch - not in margins: {stored_trade['amount']} (min: {min_amount} / max: {max_amount}")
|
2021-12-28 23:58:00 +00:00
|
|
|
return
|
2022-01-25 17:53:56 +00:00
|
|
|
|
|
|
|
# We have made it this far without hitting any of the returns, so let's set valid = True
|
|
|
|
# This will let us instantly release if the type is pending, and it is subsequently updated to completed with a callback.
|
|
|
|
to_store["valid"] = 1
|
|
|
|
# Store the trade ID so we can release it easily
|
|
|
|
to_store["trade_id"] = stored_trade["id"]
|
|
|
|
if not state == "completed":
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Storing incomplete trade: {txid}")
|
2022-01-25 17:53:56 +00:00
|
|
|
r.hmset(f"tx.{txid}", to_store)
|
|
|
|
# Don't procees further if state is not "completed"
|
2021-12-28 15:29:15 +00:00
|
|
|
return
|
2022-01-25 17:53:56 +00:00
|
|
|
|
|
|
|
r.hmset(f"tx.{txid}", to_store)
|
|
|
|
self.release_funds(stored_trade["id"], stored_trade["reference"])
|
2022-03-04 22:47:06 +00:00
|
|
|
self.ux.notify.notify_complete_trade(amount, currency)
|
2022-01-25 17:53:56 +00:00
|
|
|
|
|
|
|
def release_funds(self, trade_id, reference):
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"All checks passed, releasing funds for {trade_id} {reference}")
|
2022-01-25 17:53:56 +00:00
|
|
|
self.irc.sendmsg(f"All checks passed, releasing funds for {trade_id} / {reference}")
|
|
|
|
rtrn = self.agora.release_funds(trade_id)
|
|
|
|
self.agora.agora.contact_message_post(trade_id, "Thanks! Releasing now :)")
|
|
|
|
|
|
|
|
# Parse the escrow release response
|
2022-01-20 14:48:14 +00:00
|
|
|
message = rtrn["message"]
|
|
|
|
message_long = rtrn["response"]["data"]["message"]
|
|
|
|
self.irc.sendmsg(f"{message} - {message_long}")
|
2021-12-28 15:29:15 +00:00
|
|
|
|
2022-02-17 12:18:05 +00:00
|
|
|
def new_trade(self, asset, trade_id, buyer, currency, amount, amount_crypto, provider):
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
|
|
|
Called when we have a new trade in Agora.
|
|
|
|
Store details in Redis, generate a reference and optionally let the customer know the reference.
|
|
|
|
"""
|
2021-12-28 15:29:15 +00:00
|
|
|
reference = "".join(choices(ascii_uppercase, k=5))
|
2022-01-21 13:54:47 +00:00
|
|
|
reference = f"{asset}-{reference}"
|
2021-12-28 15:29:15 +00:00
|
|
|
existing_ref = r.get(f"trade.{trade_id}.reference")
|
2021-12-29 14:32:06 +00:00
|
|
|
if not existing_ref:
|
2021-12-28 15:29:15 +00:00
|
|
|
r.set(f"trade.{trade_id}.reference", reference)
|
|
|
|
to_store = {
|
|
|
|
"id": trade_id,
|
2022-01-21 13:54:47 +00:00
|
|
|
"asset": asset,
|
2021-12-28 15:29:15 +00:00
|
|
|
"buyer": buyer,
|
|
|
|
"currency": currency,
|
|
|
|
"amount": amount,
|
2022-01-21 13:54:47 +00:00
|
|
|
"amount_crypto": amount_crypto,
|
2021-12-28 15:29:15 +00:00
|
|
|
"reference": reference,
|
2022-02-17 12:18:05 +00:00
|
|
|
"provider": provider,
|
2021-12-28 15:29:15 +00:00
|
|
|
}
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Storing trade information: {str(to_store)}")
|
2021-12-28 15:29:15 +00:00
|
|
|
r.hmset(f"trade.{reference}", to_store)
|
2022-01-01 16:39:36 +00:00
|
|
|
self.irc.sendmsg(f"Generated reference for {trade_id}: {reference}")
|
2022-03-04 22:47:06 +00:00
|
|
|
self.ux.notify.notify_new_trade(amount, currency)
|
2021-12-28 23:58:00 +00:00
|
|
|
if settings.Agora.Send == "1":
|
|
|
|
self.agora.agora.contact_message_post(trade_id, f"Hi! When sending the payment please use reference code: {reference}")
|
2021-12-29 18:40:44 +00:00
|
|
|
if existing_ref:
|
2022-03-05 21:52:31 +00:00
|
|
|
return util.convert(existing_ref)
|
2021-12-29 18:40:44 +00:00
|
|
|
else:
|
|
|
|
return reference
|
2021-12-23 18:46:39 +00:00
|
|
|
|
2022-01-01 19:20:20 +00:00
|
|
|
def find_trade(self, txid, currency, amount):
|
|
|
|
"""
|
|
|
|
Get a trade reference that matches the given currency and amount.
|
|
|
|
Only works if there is one result.
|
2022-03-04 22:21:12 +00:00
|
|
|
:param txid: Sink transaction ID
|
2022-01-01 19:20:20 +00:00
|
|
|
:param currency: currency
|
|
|
|
:param amount: amount
|
|
|
|
:type txid: string
|
|
|
|
:type currency: string
|
|
|
|
:type amount: int
|
|
|
|
:return: matching trade object or False
|
|
|
|
:rtype: dict or bool
|
|
|
|
"""
|
|
|
|
refs = self.get_refs()
|
|
|
|
matching_refs = []
|
2022-02-15 21:50:34 +00:00
|
|
|
# TODO: use get_ref_map in this function instead of calling get_ref multiple times
|
2022-01-01 19:20:20 +00:00
|
|
|
for ref in refs:
|
|
|
|
stored_trade = self.get_ref(ref)
|
2022-01-01 20:22:53 +00:00
|
|
|
if stored_trade["currency"] == currency and float(stored_trade["amount"]) == float(amount):
|
2022-01-01 19:20:20 +00:00
|
|
|
matching_refs.append(stored_trade)
|
|
|
|
if len(matching_refs) != 1:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.error(f"Find trade returned multiple results for TXID {txid}: {matching_refs}")
|
2022-01-01 19:20:20 +00:00
|
|
|
return False
|
|
|
|
return matching_refs[0]
|
|
|
|
|
2021-12-28 23:58:00 +00:00
|
|
|
def get_refs(self):
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
|
|
|
Get all reference IDs for trades.
|
|
|
|
:return: list of trade IDs
|
|
|
|
:rtype: list
|
|
|
|
"""
|
2021-12-28 23:58:00 +00:00
|
|
|
references = []
|
|
|
|
ref_keys = r.keys("trade.*.reference")
|
|
|
|
for key in ref_keys:
|
|
|
|
references.append(r.get(key))
|
2022-03-05 21:52:31 +00:00
|
|
|
return util.convert(references)
|
2021-12-28 23:58:00 +00:00
|
|
|
|
2021-12-29 15:03:47 +00:00
|
|
|
def get_ref_map(self):
|
|
|
|
"""
|
|
|
|
Get all reference IDs for trades.
|
|
|
|
:return: dict of references keyed by TXID
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
|
|
|
references = {}
|
|
|
|
ref_keys = r.keys("trade.*.reference")
|
|
|
|
for key in ref_keys:
|
2022-03-05 21:52:31 +00:00
|
|
|
tx = util.convert(key).split(".")[1]
|
2021-12-29 15:03:47 +00:00
|
|
|
references[tx] = r.get(key)
|
2022-03-05 21:52:31 +00:00
|
|
|
return util.convert(references)
|
2021-12-29 15:03:47 +00:00
|
|
|
|
2021-12-28 23:58:00 +00:00
|
|
|
def get_ref(self, reference):
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
2022-02-15 21:50:34 +00:00
|
|
|
Get the trade information for a reference.
|
|
|
|
:param reference: trade reference
|
|
|
|
:type reference: string
|
|
|
|
:return: dict of trade information
|
|
|
|
:rtype: dict
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
2021-12-30 14:15:07 +00:00
|
|
|
ref_data = r.hgetall(f"trade.{reference}")
|
2022-03-05 21:52:31 +00:00
|
|
|
ref_data = util.convert(ref_data)
|
2021-12-28 23:58:00 +00:00
|
|
|
if not ref_data:
|
|
|
|
return False
|
|
|
|
return ref_data
|
|
|
|
|
|
|
|
def del_ref(self, reference):
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
|
|
|
Delete a given reference from the Redis database.
|
2022-02-15 21:50:34 +00:00
|
|
|
:param reference: trade reference to delete
|
|
|
|
:type reference: string
|
2021-12-29 00:04:24 +00:00
|
|
|
"""
|
2021-12-29 15:03:47 +00:00
|
|
|
tx = self.ref_to_tx(reference)
|
2021-12-28 23:58:00 +00:00
|
|
|
r.delete(f"trade.{reference}")
|
2021-12-29 15:03:47 +00:00
|
|
|
r.delete(f"trade.{tx}.reference")
|
|
|
|
|
|
|
|
def cleanup(self, references):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Reconcile the internal reference database with a given list of references.
|
|
|
|
Delete all internal references not present in the list and clean up artifacts.
|
|
|
|
:param references: list of references to reconcile against
|
|
|
|
:type references: list
|
|
|
|
"""
|
2021-12-29 15:03:47 +00:00
|
|
|
for tx, reference in self.get_ref_map().items():
|
|
|
|
if reference not in references:
|
2022-03-05 21:52:31 +00:00
|
|
|
self.log.info(f"Archiving trade reference: {reference} / TX: {tx}")
|
2021-12-29 15:03:47 +00:00
|
|
|
r.rename(f"trade.{tx}.reference", f"archive.trade.{tx}.reference")
|
|
|
|
r.rename(f"trade.{reference}", f"archive.trade.{reference}")
|
2021-12-28 23:58:00 +00:00
|
|
|
|
|
|
|
def tx_to_ref(self, tx):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Convert a trade ID to a reference.
|
|
|
|
:param tx: trade ID
|
|
|
|
:type tx: string
|
|
|
|
:return: reference
|
|
|
|
:rtype: string
|
|
|
|
"""
|
2021-12-29 14:32:06 +00:00
|
|
|
refs = self.get_refs()
|
|
|
|
for reference in refs:
|
2022-03-05 21:52:31 +00:00
|
|
|
ref_data = util.convert(r.hgetall(f"trade.{reference}"))
|
2021-12-29 14:32:06 +00:00
|
|
|
if not ref_data:
|
|
|
|
continue
|
|
|
|
if ref_data["id"] == tx:
|
|
|
|
return reference
|
2021-12-28 23:58:00 +00:00
|
|
|
|
|
|
|
def ref_to_tx(self, reference):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Convert a reference to a trade ID.
|
|
|
|
:param reference: trade reference
|
|
|
|
:type reference: string
|
|
|
|
:return: trade ID
|
|
|
|
:rtype: string
|
|
|
|
"""
|
2022-03-05 21:52:31 +00:00
|
|
|
ref_data = util.convert(r.hgetall(f"trade.{reference}"))
|
2021-12-29 14:32:06 +00:00
|
|
|
if not ref_data:
|
|
|
|
return False
|
|
|
|
return ref_data["id"]
|
2022-01-25 17:53:56 +00:00
|
|
|
|
2022-01-31 11:32:47 +00:00
|
|
|
def get_total_usd(self):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Get total USD in all our accounts, bank and trading.
|
|
|
|
:return: value in USD
|
|
|
|
:rtype float:
|
|
|
|
"""
|
2022-03-04 22:21:12 +00:00
|
|
|
# TODO: get Sink totals
|
2022-01-31 11:32:47 +00:00
|
|
|
agora_wallet_xmr = self.agora.agora.wallet_balance_xmr()
|
|
|
|
if not agora_wallet_xmr["success"]:
|
|
|
|
return False
|
|
|
|
agora_wallet_btc = self.agora.agora.wallet_balance()
|
|
|
|
if not agora_wallet_btc["success"]:
|
|
|
|
return False
|
|
|
|
total_xmr_agora = agora_wallet_xmr["response"]["data"]["total"]["balance"]
|
|
|
|
total_btc_agora = agora_wallet_btc["response"]["data"]["total"]["balance"]
|
|
|
|
# Get the XMR -> USD exchange rate
|
|
|
|
xmr_usd = self.agora.cg.get_price(ids="monero", vs_currencies=["USD"])
|
|
|
|
|
|
|
|
# Get the BTC -> USD exchange rate
|
|
|
|
btc_usd = self.agora.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"]
|
|
|
|
|
2022-03-05 21:52:31 +00:00
|
|
|
# Convert the Agora XMR total to USD
|
|
|
|
total_usd_agora_xmr = float(total_xmr_agora) * xmr_usd["monero"]["usd"]
|
|
|
|
|
2022-01-31 11:32:47 +00:00
|
|
|
# Add it all up
|
|
|
|
total_usd_agora = total_usd_agora_xmr + total_usd_agora_btc
|
2022-03-04 22:21:12 +00:00
|
|
|
# total_usd = total_usd_agora + total_usd_revolut
|
|
|
|
# TODO: add sinks value here
|
|
|
|
total_usd = total_usd_agora
|
2022-02-17 22:59:11 +00:00
|
|
|
cast_es = {
|
|
|
|
"price_usd": total_usd,
|
|
|
|
"total_usd_agora_xmr": total_usd_agora_xmr,
|
|
|
|
"total_usd_agora_btc": total_usd_agora_btc,
|
|
|
|
"total_xmr_agora": total_xmr_agora,
|
|
|
|
"total_btc_agora": total_btc_agora,
|
|
|
|
"xmr_usd": xmr_usd["monero"]["usd"],
|
|
|
|
"btc_usd": btc_usd["bitcoin"]["usd"],
|
2022-03-04 22:21:12 +00:00
|
|
|
# "total_usd_sinks": total_usd_sinks,
|
2022-02-17 22:59:11 +00:00
|
|
|
"total_usd_agora": total_usd_agora,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_total_usd", cast_es)
|
2022-01-31 11:32:47 +00:00
|
|
|
return total_usd
|
|
|
|
|
2022-02-15 21:50:34 +00:00
|
|
|
# TODO: possibly refactor this into smaller functions which don't return as much stuff
|
|
|
|
# check if this is all really needed in the corresponding withdraw function
|
2022-01-25 17:53:56 +00:00
|
|
|
def get_total(self):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
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))
|
|
|
|
"""
|
2022-03-04 22:21:12 +00:00
|
|
|
# TODO: get sinks value here
|
|
|
|
# total_usd_revolut = self.revolut.get_total_usd()
|
2022-01-25 17:53:56 +00:00
|
|
|
agora_wallet_xmr = self.agora.agora.wallet_balance_xmr()
|
|
|
|
if not agora_wallet_xmr["success"]:
|
2022-02-14 20:37:17 +00:00
|
|
|
self.log.error("Could not get Agora XMR wallet total.")
|
2022-01-25 17:53:56 +00:00
|
|
|
return False
|
|
|
|
agora_wallet_btc = self.agora.agora.wallet_balance()
|
|
|
|
if not agora_wallet_btc["success"]:
|
2022-02-14 20:37:17 +00:00
|
|
|
self.log.error("Could not get Agora BTC wallet total.")
|
2022-01-25 17:53:56 +00:00
|
|
|
return False
|
|
|
|
total_xmr_agora = agora_wallet_xmr["response"]["data"]["total"]["balance"]
|
|
|
|
total_btc_agora = agora_wallet_btc["response"]["data"]["total"]["balance"]
|
|
|
|
# Get the XMR -> USD exchange rate
|
|
|
|
xmr_usd = self.agora.cg.get_price(ids="monero", vs_currencies=["USD"])
|
|
|
|
|
|
|
|
# Get the BTC -> USD exchange rate
|
|
|
|
btc_usd = self.agora.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"]
|
|
|
|
|
|
|
|
# Add it all up
|
|
|
|
total_usd_agora = total_usd_agora_xmr + total_usd_agora_btc
|
2022-03-04 22:21:12 +00:00
|
|
|
# total_usd = total_usd_agora + total_usd_revolut
|
|
|
|
# TODO: add sinks value here
|
|
|
|
total_usd = total_usd_agora
|
2022-01-25 17:53:56 +00:00
|
|
|
|
|
|
|
# Convert the total USD price to GBP and SEK
|
2022-02-22 20:10:47 +00:00
|
|
|
rates = self.money.get_rates_all()
|
2022-01-25 17:53:56 +00:00
|
|
|
price_sek = rates["SEK"] * total_usd
|
|
|
|
price_usd = total_usd
|
|
|
|
price_gbp = rates["GBP"] * total_usd
|
|
|
|
|
2022-02-17 22:03:48 +00:00
|
|
|
cast = (
|
2022-01-25 18:39:35 +00:00
|
|
|
(price_sek, price_usd, price_gbp), # Total prices in our 3 favourite currencies
|
|
|
|
(total_usd_agora_xmr, total_usd_agora_btc), # Total USD balance in only Agora
|
|
|
|
(total_xmr_agora, total_btc_agora),
|
|
|
|
) # Total XMR and BTC balance in Agora
|
2022-02-17 22:59:11 +00:00
|
|
|
|
|
|
|
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_xmr_agora": total_xmr_agora,
|
|
|
|
"total_btc_agora": total_btc_agora,
|
|
|
|
"xmr_usd": xmr_usd["monero"]["usd"],
|
|
|
|
"btc_usd": btc_usd["bitcoin"]["usd"],
|
2022-03-04 22:21:12 +00:00
|
|
|
# "total_usd_revolut": total_usd_revolut,
|
2022-02-17 22:59:11 +00:00
|
|
|
"total_usd_agora": total_usd_agora,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_total", cast_es)
|
2022-02-17 22:03:48 +00:00
|
|
|
return cast
|
|
|
|
|
|
|
|
def write_to_es(self, msgtype, cast):
|
2022-02-22 19:21:29 +00:00
|
|
|
if settings.ES.Enabled == "1":
|
|
|
|
cast["type"] = msgtype
|
|
|
|
cast["ts"] = str(datetime.now().isoformat())
|
|
|
|
cast["xtype"] = "tx"
|
|
|
|
self.es.index(index=settings.ES.Index, document=cast)
|
2022-01-31 11:32:47 +00:00
|
|
|
|
|
|
|
def get_remaining(self):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Check how much profit we need to make in order to withdraw.
|
|
|
|
:return: profit remaining in USD
|
|
|
|
:rtype: float
|
|
|
|
"""
|
2022-01-31 11:32:47 +00:00
|
|
|
total_usd = 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
|
2022-02-17 22:59:11 +00:00
|
|
|
cast_es = {
|
|
|
|
"remaining_usd": remaining,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_remaining", cast_es)
|
2022-01-31 11:32:47 +00:00
|
|
|
return remaining
|
2022-02-09 18:45:43 +00:00
|
|
|
|
|
|
|
def get_open_trades_usd(self):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
Get total value of open trades in USD.
|
|
|
|
:return: total trade value
|
|
|
|
:rtype: float
|
|
|
|
"""
|
2022-02-09 18:45:43 +00:00
|
|
|
dash = self.agora.wrap_dashboard()
|
|
|
|
if dash is False:
|
|
|
|
return False
|
|
|
|
|
2022-02-22 20:10:47 +00:00
|
|
|
rates = self.money.get_rates_all()
|
2022-02-09 18:45:43 +00:00
|
|
|
cumul_usd = 0
|
|
|
|
for contact_id, contact in dash.items():
|
2022-02-22 19:21:29 +00:00
|
|
|
# We need created at in order to look up the historical prices
|
|
|
|
created_at = contact["data"]["created_at"]
|
|
|
|
|
|
|
|
# Reformat the date how CoinGecko likes
|
|
|
|
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
|
|
|
|
asset = contact["data"]["advertisement"]["asset"]
|
|
|
|
if asset == "XMR":
|
|
|
|
amount_crypto = contact["data"]["amount_xmr"]
|
|
|
|
history = self.agora.cg.get_coin_history_by_id(id="monero", date=date_formatted)
|
|
|
|
crypto_usd = float(history["market_data"]["current_price"]["usd"])
|
|
|
|
elif asset == "BTC":
|
|
|
|
amount_crypto = contact["data"]["amount_btc"]
|
|
|
|
history = self.agora.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
|
2022-02-09 18:45:43 +00:00
|
|
|
currency = contact["data"]["currency"]
|
|
|
|
if not contact["data"]["is_selling"]:
|
|
|
|
continue
|
|
|
|
if currency == "USD":
|
2022-02-21 10:02:20 +00:00
|
|
|
cumul_usd += float(amount)
|
2022-02-09 18:45:43 +00:00
|
|
|
else:
|
|
|
|
rate = rates[currency]
|
|
|
|
amount_usd = float(amount) / rate
|
|
|
|
cumul_usd += amount_usd
|
2022-02-17 22:59:11 +00:00
|
|
|
|
|
|
|
cast_es = {
|
|
|
|
"trades_usd": cumul_usd,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_open_trades_usd", cast_es)
|
2022-02-09 18:45:43 +00:00
|
|
|
return cumul_usd
|
|
|
|
|
|
|
|
def get_total_remaining(self):
|
2022-02-15 21:50:34 +00:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
"""
|
2022-02-09 18:45:43 +00:00
|
|
|
total_usd = self.get_total_usd()
|
|
|
|
total_trades_usd = 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
|
2022-02-17 22:59:11 +00:00
|
|
|
|
|
|
|
cast_es = {
|
|
|
|
"total_remaining_usd": remaining,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_total_remaining", cast_es)
|
2022-02-09 18:45:43 +00:00
|
|
|
return remaining
|
2022-02-15 22:27:42 +00:00
|
|
|
|
|
|
|
def get_total_with_trades(self):
|
|
|
|
total_usd = self.get_total_usd()
|
|
|
|
if not total_usd:
|
|
|
|
return False
|
|
|
|
total_trades_usd = self.get_open_trades_usd()
|
2022-02-17 22:59:11 +00:00
|
|
|
total_with_trades = total_usd + total_trades_usd
|
|
|
|
cast_es = {
|
|
|
|
"total_with_trades": total_with_trades,
|
|
|
|
}
|
|
|
|
self.write_to_es("get_total_with_trades", cast_es)
|
|
|
|
return total_with_trades
|