1
0
crypto-seller/crypto_seller/__init__.py

230 lines
7.5 KiB
Python
Raw Normal View History

2024-07-17 19:49:19 +00:00
"""# Automatic Crypto Seller.
2024-07-22 15:02:09 +00:00
Automatic one-way trades.
This is a wrapper about [`fin_depo`](https://gitfub.space/Jmaa/fin-depo/) for
automatically trading one way trades, by using repeated trades
over a period.
2024-07-22 11:21:41 +00:00
The primary motivation is for trading low-volume crypto assets slowly without
affecting the price too much.
Supported sites:
- [KuCoin](https://www.kucoin.com/): Online crypto-currency exchange.
## Installation
Install dependencies:
```shell
pip install -r requirements.txt
```
## Usage
Run using from the top directory:
```shell
python -m crypto_seller
```
The script will now automatically sell assets over time. The interval between
sell-offs are randomized to avoid front-running, and the amounts are also
randomized to avoid too consistent behaviour.
The log will both be displayed in the shell, and be placed in a log file
`output/log.txt`. Every sell-off will be logged to the `output/trades.csv`
file, with as much information as possible. Keep both of these for tax
purposes, if relevant.
## Auditing information
The most relevant libraries for auditing are:
- [`fin_depo`](https://gitfub.space/Jmaa/fin-depo): Library for programmatic
fetching of depository assets and in some cases allows for order placement.
This is the library that reads balances and places market orders.
- [`fin_defs`](https://gitfub.space/Jmaa/fin-defs): Definitions of financial
assets and instruments. Used by `fin_depo`.
- [`python-kucoin`](https://python-kucoin.readthedocs.io/en/latest/) is used by
`fin_depo` for providing KuCoin support.
## Taxation
Some parts of the world suffers from weird and draconian taxation rules on
cryptocurrencies, so it helps to keep track of the relevant trading
information.
As mentioned above, keep (and backup) both the log file (`output/log.txt`) and
the trades file (`output/trades.csv`).
To help with tax reporting, it might be useful to sign up to tax oriented
websites. For example, [CryptoSkat](https://cryptoskat.dk/) seems to be the
most mature on the danish market, and does support KuCoin.
2024-07-22 11:36:52 +00:00
2024-07-22 12:12:05 +00:00
## TODO
2024-07-22 21:07:25 +00:00
- [ ] Present an overview of what the script will be doing
* Sell what for what? How much, how often?
* Give an estimate of how long it will take.
* Wait 20 seconds before starting, to allow the user to review.
2024-07-22 13:48:55 +00:00
- [ ] Ensure that a failure during selling results in a safe winding down of the system.
* Catch runtime errors when selling
* Show errors to log.
* Stop loop and exit with results, and error indicator.
2024-07-22 12:12:05 +00:00
- [ ] Document configuration
2024-07-22 14:05:42 +00:00
- [ ] Document code auditing
2024-07-22 21:02:25 +00:00
- [X] Parse configuration from json.
2024-07-22 14:05:42 +00:00
- [X] Ensure sell time is included in order details
2024-07-22 13:48:55 +00:00
- [X] Log all trades to CSV file.
- [X] Collect information during the run and output after run
2024-07-22 12:12:05 +00:00
2024-07-17 19:49:19 +00:00
"""
2024-07-17 20:21:58 +00:00
__all__ = ['__version__', 'run_auto_sell']
import dataclasses
import datetime
2024-07-17 20:21:58 +00:00
import logging
import random
2024-07-22 11:36:52 +00:00
from collections.abc import Callable
from decimal import Decimal
2024-07-22 11:36:52 +00:00
from typing import Any
2024-07-17 20:21:58 +00:00
import fin_defs
import fin_depo
2024-07-17 19:49:19 +00:00
from ._version import __version__
2024-07-17 20:21:58 +00:00
logger = logging.getLogger(__name__)
################################################################################
# Main code #
2024-07-22 21:05:30 +00:00
2024-07-22 11:36:52 +00:00
@dataclasses.dataclass(frozen=True)
2024-07-17 20:21:58 +00:00
class AutoSellConfig:
2024-07-22 12:31:55 +00:00
"""Configuration for `run_auto_sell`.
Fields:
- `interval_range`: The range to determine sell-off intervals from. After
each sell-off it will sleep an amount of time uniformly sampled from this
range.
- `input_asset`: Asset to sell.
- `input_amount_range`: Range to uniformly sample sell-off sizes from.
- `output_asset`: Asset to "buy".
- `seller`: Depository seller to use.
- `sleep`: Sleep method to use.
- `exit_when_empty`: Whether the system should stop once there is nothing
more to sell. Recommended.
"""
interval_range: tuple[datetime.timedelta, datetime.timedelta]
input_asset: fin_defs.Asset
input_amount_range: tuple[Decimal, Decimal]
output_asset: fin_defs.Asset
2024-07-22 11:31:53 +00:00
seller: fin_depo.defi_kucoin.KucoinDepoFetcher
2024-07-22 11:36:52 +00:00
sleep: Callable[[float], None]
2024-07-22 13:48:55 +00:00
log_order_to_csv: Callable[[fin_depo.data.TradeOrderDetails], None]
2024-07-17 20:21:58 +00:00
exit_when_empty: bool = True
2024-07-22 11:36:52 +00:00
2024-07-22 12:12:05 +00:00
@dataclasses.dataclass(frozen=True)
class AutoSellRunResults:
2024-07-22 12:31:55 +00:00
"""Result information after `run_auto_sell`.
Fields:
- `order_details`: The list of order details.
- `total_duration`: Total duration of the run.
- `total_sleep_duration`: Amount of time spent waiting between sell-offs.
"""
2024-07-22 12:12:05 +00:00
order_details: list[fin_depo.data.TradeOrderDetails]
total_duration: datetime.timedelta
total_sleep_duration: datetime.timedelta
def total_input_amount(self) -> Decimal:
2024-07-22 12:31:55 +00:00
"""Total amount of assets sold."""
2024-07-22 21:05:30 +00:00
return sum((o.input_amount for o in self.order_details), start=Decimal(0))
2024-07-22 12:12:05 +00:00
def total_output_amount(self) -> Decimal:
2024-07-22 12:31:55 +00:00
"""Total amount of assets "bought"."""
2024-07-22 21:05:30 +00:00
return sum((o.output_amount for o in self.order_details), start=Decimal(0))
2024-07-22 12:12:05 +00:00
2024-07-22 21:05:30 +00:00
def sample_from_range(rng: random.Random, rang: tuple[Any, Any]) -> Any:
2024-07-22 12:31:55 +00:00
"""Samples uniformly from the given range."""
multiplier: float | Decimal = rng.random()
2024-07-22 21:05:30 +00:00
if isinstance(rang[0], Decimal):
2024-07-17 20:21:58 +00:00
multiplier = Decimal(multiplier)
2024-07-22 21:05:30 +00:00
return rang[0] + (rang[1] - rang[0]) * multiplier
2024-07-17 20:21:58 +00:00
2024-07-22 11:36:52 +00:00
2024-07-22 12:12:05 +00:00
def run_auto_sell(config: AutoSellConfig) -> AutoSellRunResults:
2024-07-22 12:31:55 +00:00
"""Executes the sell-off.
Sell-offs are performed in rounds of sizes and with intervals randomly
based on the given configuration.
"""
2024-07-17 20:21:58 +00:00
rng = random.SystemRandom()
2024-07-22 12:12:05 +00:00
time_start = datetime.datetime.now(tz=datetime.UTC)
all_executed_orders: list[fin_depo.data.TradeOrderDetails] = []
total_sleep_duration = datetime.timedelta(seconds=0)
2024-07-17 20:21:58 +00:00
while True:
# Check that account has tokens.
2024-07-22 11:36:52 +00:00
input_amount_available = config.seller.get_depo().get_amount_of_asset(
config.input_asset,
)
logger.info('Currently own %s %s', input_amount_available, config.input_asset)
2024-07-17 20:21:58 +00:00
if input_amount_available > 0:
amount_to_sell = sample_from_range(rng, config.input_amount_range)
amount_to_sell = min(input_amount_available, amount_to_sell)
logger.info('Attempting to sell %s %s', amount_to_sell, config.input_asset)
2024-07-17 20:21:58 +00:00
2024-07-22 11:36:52 +00:00
order_details = config.seller.place_market_order(
2024-07-22 12:12:05 +00:00
config.input_asset,
amount_to_sell,
config.output_asset,
2024-07-22 11:36:52 +00:00
)
2024-07-22 11:21:41 +00:00
2024-07-22 13:48:55 +00:00
config.log_order_to_csv(order_details)
2024-07-22 12:12:05 +00:00
all_executed_orders.append(order_details)
2024-07-17 20:21:58 +00:00
del amount_to_sell
2024-07-17 20:21:58 +00:00
elif config.exit_when_empty:
break
# Time out
time_to_sleep = sample_from_range(rng, config.interval_range)
2024-07-17 20:21:58 +00:00
time_to_sleep_secs = time_to_sleep.total_seconds()
logger.info('Sleeping %s (%d seconds)', time_to_sleep, time_to_sleep_secs)
2024-07-22 11:31:53 +00:00
config.sleep(time_to_sleep_secs)
2024-07-22 12:12:05 +00:00
total_sleep_duration += time_to_sleep
2024-07-17 20:21:58 +00:00
del input_amount_available
2024-07-22 12:12:05 +00:00
time_end = datetime.datetime.now(tz=datetime.UTC)
return AutoSellRunResults(
all_executed_orders,
total_duration=time_end - time_start,
total_sleep_duration=total_sleep_duration,
)
def log_results(results: AutoSellRunResults):
logger.info('Stats:')
logger.info('- Num orders: %s', len(results.order_details))
logger.info('- Total sold: %s', results.total_input_amount())
logger.info('- Total gained: %s', results.total_output_amount())
logger.info(
'- Total duration: %s (%s spent sleeping)',
results.total_duration,
results.total_sleep_duration,
)