1
0
crypto-seller/crypto_seller/__init__.py

266 lines
9.2 KiB
Python
Raw Normal View History

2024-07-17 19:49:19 +00:00
"""# Automatic Crypto Seller.
2024-08-02 15:17:25 +00:00
Crypto Seller, I am going into finance, and I want only your strongest tokens.
2024-07-22 15:02:09 +00:00
2024-07-22 22:15:01 +00:00
This program is a wrapper around
[`fin_depo`](https://gitfub.space/Jmaa/fin-depo/) for automatically trading
one-way trades, by using repeated trades over a period. Can be used to slowly
enter or exit positions, for example low-volume crypto currencies, or as an
automated investment savings system.
Supported sites:
- [KuCoin](https://www.kucoin.com/): Online crypto-currency exchange.
## Installation
Install dependencies:
```shell
pip install -r requirements.txt
```
## Usage
2024-07-22 22:15:01 +00:00
1. Create configuration file. See below and in `examples/` folder for inspiration.
2. [Create KuCoin API key](https://www.kucoin.com/account/api) with **General**
and **Spot Trading** permissions.
3. Add KuCoin API key secrets (`KUCOIN_KEY`, `KUCOIN_SECRET`, `KUCOIN_PASS`) to
an [`secret_loader` accessible
location](https://gitfub.space/Jmaa/secret_loader#user-content-accessible) .
4. Run script using `python -m crypto_seller --config CONFIG_FILE`.
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
2024-07-22 22:15:01 +00:00
randomized to avoid certain attacks (only relevant for smallish intervals of
less than a week).
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.
2024-07-22 22:15:01 +00:00
## Configuration
Example configurations can be found in the `examples/` folder.
Configurations are `.json` files, with the following fields:
```json
{
"input_asset": str,
"output_asset": str,
"input_amount_low": float,
"input_amount_high": float,
"interval_minutes_low": int,
"interval_minutes_high": int
}
```
While `input_amount_low` and `input_amount_high` can be identical (and
the same for `interval_minutes_XX`) it is discouraged, to avoid frontrunning attacks.
## Auditing information
2024-07-22 22:15:01 +00:00
As mentioned before, this program is mostly glue code and wrappering around
library functionality. The glue application code allows for running the main
loop of checking balance, selling amount and sleeping until the next iteration,
with some argument and configuration parsing thrown in.
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`.
2024-07-22 22:15:01 +00:00
- [`secret_loader`](https://gitfub.space/Jmaa/secret_loader): Library for
loading of secrets (passwords, API keys, secret keys, configuration files,
etc.) from standardized locations.
- [`python-kucoin`](https://python-kucoin.readthedocs.io/en/latest/): Used by
`fin_depo` to provide KuCoin backend.
## 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 22:15:01 +00:00
- [X] Document configuration
- [X] 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__)
2024-12-02 16:59:10 +00:00
################################################################################
# Constants
QUANTIZE_DECIMALS = Decimal('1.00')
################################################################################
# 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-12-02 16:34:18 +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-12-02 16:34:18 +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-12-02 16:59:10 +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,
)
2024-12-02 16:59:10 +00:00
logger.info('Currently own %s %s', input_amount_available, config.input_asset.raw_short_name())
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)
2024-12-02 16:59:10 +00:00
amount_to_sell = amount_to_sell.quantize(QUANTIZE_DECIMALS)
logger.info('Selling %s %s', amount_to_sell, config.input_asset.raw_short_name())
2024-07-17 20:21:58 +00:00
2024-07-22 11:36:52 +00:00
order_details = config.seller.place_market_order(
fin_defs.AssetAmount(config.input_asset, amount_to_sell),
2024-07-22 12:12:05 +00:00
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,
)