btrccts


Namebtrccts JSON
Version 0.1.4 PyPI version JSON
download
home_pagehttps://github.com/btrccts/btrccts/
SummaryBackTest and Run CryptoCurrency Trading Strategies
upload_time2023-12-03 01:47:17
maintainer
docs_urlNone
authorSimon Brand
requires_python
license
keywords btrccts
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # btrccts
## BackTest and Run CryptoCurrency Trading Strategies

### [Install](#install) - [Usage](#usage) - [Manual](#manual) - [Development](#development)

This library provides an easy way to backtest trading strategies and run them live with ccxt.
The purpose of this library is to provide a framework and an backtest exchange with the same
interface than ccxt - nothing less and nothing more.
If you want an library to compute performance metrics out of trades/orders,
you need an additional library.

## Install

The easiest way to install the BTRCCTS library is to use a package manager:

- https://pypi.org/project/btrccts/

The python package hashes can be found in the `version_hashes.txt`.

You can also clone the repository, see [Development](development)

## Usage

For example algorithms see in [Examples](examples/)
```python
from btrccts import parse_params_and_execute_algorithm, AlgorithmBase


class Algorithm(AlgorithmBase):

    @staticmethod
    def configure_argparser(argparser):
        # Here you can add additional arguments to the argparser
        argparser.add_argument('--pyramiding', default=1, type=int)

    def __init__(self, context, args):
        # Context is used to create exchanges or get the current time
        self._context = context
        self._args = args

        # This will create a kraken exchange instance
        # The interface in backtesting and live mode is identical to CCXT.
        # See: [CCXT](https://github.com/ccxt/ccxt/wiki)
        # In live mode, this will be a plain ccxt instance of the exchange
        # The exchange keys will be read from the config directory (see --help)
        # You can create sync or async versions of the exchange.
        # If ccxtpro is available in your python environment, the async
        # call will create a ccxtpro instance.
        self._kraken = context.create_exchange('kraken', async_ccxt=True)

        # You can access your own defined parameters
        print('Pyramiding:', args.pyramiding)

        # You can access predefined parameters like exchanges and symbols
        print('Exchanges:', args.exchanges)
        print('Symbols:', args.symbols)

    async def next_iteration(self):
        # This method is executed each time interval
        # This method can be async or a normal method.

        # This is the current context date:
        print('context date', self._context.date())

        # In live mode, markets are not loaded by the library
        # If you need access to the exchanges market object, you need
        # to load them first
        await self._kraken.load_markets()
        # Use the exchange to load OHLCV data
        ohlcv_len = 10
        ohlcv_offset = ohlcv_len * 60 * 1000
        ohlcv_start = int(self._context.date().value / 1000000 - ohlcv_offset)
        print(await self._kraken.fetch_ohlcv(
            'BTC/USD', '1m', ohlcv_start, ohlcv_len))

        # Use the exchange to create a market order
        self._order_id = await self._kraken.create_order(
            type='market', side='buy', symbol='BTC/USD', amount=0.1)

        # If you want to stop the algorithm in context or live mode, you can
        # do this:
        self._context.stop('stop message')

    async def handle_exception(self, e):
        # This method is called, when next_iteration raises an exception, e.g.
        # because of an exchange error or a programming error.
        # If this method raises an exception, the algorithm will stop with
        # reason EXCEPTION
        # This method can be async or a normal method.
        # If you are not in live mode, it is advisable to rethrow the
        # exception to fix the programming error.
        print(e)
        if not self._args.live:
            raise e

    async def exit(self, reason):
        # This method is called, when the algorithm exits and should be used
        # to cleanup (e.g. cancel open orders).
        # This method can be async or a normal method.
        # reason contains information on why the algorithm exits.
        # e.g. STOPPED, EXCEPTION, FINISHED
        print("Done", reason)
        self.closed_orders = await self._kraken.fetch_closed_orders()
        # Async versions of an exchange needs to be closed, because
        # btrccts will close the asyncio loop after the run.
        await self._kraken.close()


# This method parses commandline parameters (see --help)
# and runs the Algorithm according to the parameters
result = parse_params_and_execute_algorithm(Algorithm)
# The result is an instance of Algorithm, you can now use saved
# information. If you used a sync version of the exchange you can
# still use them. For async exchanges the asyncio loop is already
# destroyed.
print(result.closed_orders)
```

To run this algorithm, just execute the file with python.
e.g.
```bash
.venv/bin/python examples/algo_readme.py --start-date 2017-12-01 --end-date 2017-12-02 --interval 1h \
                                         --exchanges kraken --symbols BTC/USD \
                                         --start-balances '{"kraken": {"USD": 10000}}'
```
To execute orders in exchanges, you can run the algorithm in live mode with the command-line parameter `--live`.
For other parameters, see `.venv/bin/python examples/algo_readme.py --help`.

If you dont want the function to parse commandline parameters for you, you can use
```python
from btrccts.run import execute_algorithm
execute_algorithm(...)
```


## Manual

### Data and directories

Run your algorithm with `--help` to see the path to your config and data directories.

The data directory contains the ohlcv data:
`data_directory/ohlcv/EXCHANGE/BASE/QUOTE.csv`
e.g.
`data_directory/ohlcv/binance/BTC/USD.csv`

Data files are in the following format (readable with `pandas.read_csv`)
```csv
,open,high,low,close,volume
2019-10-01 10:10:00+00:00,200,300,100,300,1000
2019-10-01 10:11:00+00:00,300,400,200,400,2000
2019-10-01 10:12:00+00:00,400,500,300,500,3000
```
The data files are not yet provided with this library. You have to provide them yourself.
The data file needs to cover the complete period (you want to run the bot) in 1 minute interval.
You can specify the period with `--start-date` and `--end-date`.


The config directory contains exchange keys.
e.g. `config_directory/binance.json`:
```json
{
    "apiKey": "key material",
    "secret": "secret stuff"
}
```
If an alias is provided (e.g. `--auth-aliases '{"kraken": "kraken_wma"}'`,
the file `config_directory/kraken_wma.json` is used.


### Differences between live and backtesting mode

- In backtesting mode the markets from the exchanges are loaded upon exchange creation.
This needs to be done, because market information is needed for order handling.
In live mode, the markets are not loaded via the library, because the library does not
know how you want to handle e.g. errors or reloading the market.


### How orders get filled

- Market order

Market orders are executed immediately with a price a little worse than current low/high.
Since we only have ohlcv data, we cannot use the next data, because this would introduce
a look-ahead bias
Some other backtesting libraries would wait until the next round to fill market orders,
but this is not what is happening in the real world (executing market orders immediately).

- Limit order

Limit orders are filled, when the price is reached. Limit orders get filled
all at once, there is no volume calculation yet. If your bot uses huge limit orders,
keep in mind that the behavior on the exchange can be a partiall fill and leaving the
order open until filled.


### When next round is initiated in live mode / How interval is handled in live mode

When the algorithm is started, it will immediately execute `next_iteration`.
Now the library waits until the next time interval and executes `next_iteration`.
If the `next_iteration` call takes longer than the interval, `next_iteration` is
called immediately again. If `next_iteration` takes longer than multiple intervals,
only the last interval is rescheduled.

## Development

Setup a virtualenv:

```shell
git clone git@github.com:btrccts/btrccts.git
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
.venv/bin/pip install -e . --no-deps
```

### Run tests

Install the dev dependencies:
```shell
.venv/bin/pip install -e .[dev]
```
Run the tests:
```shell
.venv/bin/python -m unittest tests/unit/tests.py
.venv/bin/python -m unittest tests/integration/tests.py
```

## Contact us

btrccts@e.email

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/btrccts/btrccts/",
    "name": "btrccts",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "btrccts",
    "author": "Simon Brand",
    "author_email": "simon.brand@postadigitale.de",
    "download_url": "https://files.pythonhosted.org/packages/72/51/102a3506a631dabc39c60465abe54b3844aaef635557d45d821a8145b470/btrccts-0.1.4.tar.gz",
    "platform": null,
    "description": "# btrccts\n## BackTest and Run CryptoCurrency Trading Strategies\n\n### [Install](#install) - [Usage](#usage) - [Manual](#manual) - [Development](#development)\n\nThis library provides an easy way to backtest trading strategies and run them live with ccxt.\nThe purpose of this library is to provide a framework and an backtest exchange with the same\ninterface than ccxt - nothing less and nothing more.\nIf you want an library to compute performance metrics out of trades/orders,\nyou need an additional library.\n\n## Install\n\nThe easiest way to install the BTRCCTS library is to use a package manager:\n\n- https://pypi.org/project/btrccts/\n\nThe python package hashes can be found in the `version_hashes.txt`.\n\nYou can also clone the repository, see [Development](development)\n\n## Usage\n\nFor example algorithms see in [Examples](examples/)\n```python\nfrom btrccts import parse_params_and_execute_algorithm, AlgorithmBase\n\n\nclass Algorithm(AlgorithmBase):\n\n    @staticmethod\n    def configure_argparser(argparser):\n        # Here you can add additional arguments to the argparser\n        argparser.add_argument('--pyramiding', default=1, type=int)\n\n    def __init__(self, context, args):\n        # Context is used to create exchanges or get the current time\n        self._context = context\n        self._args = args\n\n        # This will create a kraken exchange instance\n        # The interface in backtesting and live mode is identical to CCXT.\n        # See: [CCXT](https://github.com/ccxt/ccxt/wiki)\n        # In live mode, this will be a plain ccxt instance of the exchange\n        # The exchange keys will be read from the config directory (see --help)\n        # You can create sync or async versions of the exchange.\n        # If ccxtpro is available in your python environment, the async\n        # call will create a ccxtpro instance.\n        self._kraken = context.create_exchange('kraken', async_ccxt=True)\n\n        # You can access your own defined parameters\n        print('Pyramiding:', args.pyramiding)\n\n        # You can access predefined parameters like exchanges and symbols\n        print('Exchanges:', args.exchanges)\n        print('Symbols:', args.symbols)\n\n    async def next_iteration(self):\n        # This method is executed each time interval\n        # This method can be async or a normal method.\n\n        # This is the current context date:\n        print('context date', self._context.date())\n\n        # In live mode, markets are not loaded by the library\n        # If you need access to the exchanges market object, you need\n        # to load them first\n        await self._kraken.load_markets()\n        # Use the exchange to load OHLCV data\n        ohlcv_len = 10\n        ohlcv_offset = ohlcv_len * 60 * 1000\n        ohlcv_start = int(self._context.date().value / 1000000 - ohlcv_offset)\n        print(await self._kraken.fetch_ohlcv(\n            'BTC/USD', '1m', ohlcv_start, ohlcv_len))\n\n        # Use the exchange to create a market order\n        self._order_id = await self._kraken.create_order(\n            type='market', side='buy', symbol='BTC/USD', amount=0.1)\n\n        # If you want to stop the algorithm in context or live mode, you can\n        # do this:\n        self._context.stop('stop message')\n\n    async def handle_exception(self, e):\n        # This method is called, when next_iteration raises an exception, e.g.\n        # because of an exchange error or a programming error.\n        # If this method raises an exception, the algorithm will stop with\n        # reason EXCEPTION\n        # This method can be async or a normal method.\n        # If you are not in live mode, it is advisable to rethrow the\n        # exception to fix the programming error.\n        print(e)\n        if not self._args.live:\n            raise e\n\n    async def exit(self, reason):\n        # This method is called, when the algorithm exits and should be used\n        # to cleanup (e.g. cancel open orders).\n        # This method can be async or a normal method.\n        # reason contains information on why the algorithm exits.\n        # e.g. STOPPED, EXCEPTION, FINISHED\n        print(\"Done\", reason)\n        self.closed_orders = await self._kraken.fetch_closed_orders()\n        # Async versions of an exchange needs to be closed, because\n        # btrccts will close the asyncio loop after the run.\n        await self._kraken.close()\n\n\n# This method parses commandline parameters (see --help)\n# and runs the Algorithm according to the parameters\nresult = parse_params_and_execute_algorithm(Algorithm)\n# The result is an instance of Algorithm, you can now use saved\n# information. If you used a sync version of the exchange you can\n# still use them. For async exchanges the asyncio loop is already\n# destroyed.\nprint(result.closed_orders)\n```\n\nTo run this algorithm, just execute the file with python.\ne.g.\n```bash\n.venv/bin/python examples/algo_readme.py --start-date 2017-12-01 --end-date 2017-12-02 --interval 1h \\\n                                         --exchanges kraken --symbols BTC/USD \\\n                                         --start-balances '{\"kraken\": {\"USD\": 10000}}'\n```\nTo execute orders in exchanges, you can run the algorithm in live mode with the command-line parameter `--live`.\nFor other parameters, see `.venv/bin/python examples/algo_readme.py --help`.\n\nIf you dont want the function to parse commandline parameters for you, you can use\n```python\nfrom btrccts.run import execute_algorithm\nexecute_algorithm(...)\n```\n\n\n## Manual\n\n### Data and directories\n\nRun your algorithm with `--help` to see the path to your config and data directories.\n\nThe data directory contains the ohlcv data:\n`data_directory/ohlcv/EXCHANGE/BASE/QUOTE.csv`\ne.g.\n`data_directory/ohlcv/binance/BTC/USD.csv`\n\nData files are in the following format (readable with `pandas.read_csv`)\n```csv\n,open,high,low,close,volume\n2019-10-01 10:10:00+00:00,200,300,100,300,1000\n2019-10-01 10:11:00+00:00,300,400,200,400,2000\n2019-10-01 10:12:00+00:00,400,500,300,500,3000\n```\nThe data files are not yet provided with this library. You have to provide them yourself.\nThe data file needs to cover the complete period (you want to run the bot) in 1 minute interval.\nYou can specify the period with `--start-date` and `--end-date`.\n\n\nThe config directory contains exchange keys.\ne.g. `config_directory/binance.json`:\n```json\n{\n    \"apiKey\": \"key material\",\n    \"secret\": \"secret stuff\"\n}\n```\nIf an alias is provided (e.g. `--auth-aliases '{\"kraken\": \"kraken_wma\"}'`,\nthe file `config_directory/kraken_wma.json` is used.\n\n\n### Differences between live and backtesting mode\n\n- In backtesting mode the markets from the exchanges are loaded upon exchange creation.\nThis needs to be done, because market information is needed for order handling.\nIn live mode, the markets are not loaded via the library, because the library does not\nknow how you want to handle e.g. errors or reloading the market.\n\n\n### How orders get filled\n\n- Market order\n\nMarket orders are executed immediately with a price a little worse than current low/high.\nSince we only have ohlcv data, we cannot use the next data, because this would introduce\na look-ahead bias\nSome other backtesting libraries would wait until the next round to fill market orders,\nbut this is not what is happening in the real world (executing market orders immediately).\n\n- Limit order\n\nLimit orders are filled, when the price is reached. Limit orders get filled\nall at once, there is no volume calculation yet. If your bot uses huge limit orders,\nkeep in mind that the behavior on the exchange can be a partiall fill and leaving the\norder open until filled.\n\n\n### When next round is initiated in live mode / How interval is handled in live mode\n\nWhen the algorithm is started, it will immediately execute `next_iteration`.\nNow the library waits until the next time interval and executes `next_iteration`.\nIf the `next_iteration` call takes longer than the interval, `next_iteration` is\ncalled immediately again. If `next_iteration` takes longer than multiple intervals,\nonly the last interval is rescheduled.\n\n## Development\n\nSetup a virtualenv:\n\n```shell\ngit clone git@github.com:btrccts/btrccts.git\npython3 -m venv .venv\n.venv/bin/pip install -r requirements.txt\n.venv/bin/pip install -e . --no-deps\n```\n\n### Run tests\n\nInstall the dev dependencies:\n```shell\n.venv/bin/pip install -e .[dev]\n```\nRun the tests:\n```shell\n.venv/bin/python -m unittest tests/unit/tests.py\n.venv/bin/python -m unittest tests/integration/tests.py\n```\n\n## Contact us\n\nbtrccts@e.email\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "BackTest and Run CryptoCurrency Trading Strategies",
    "version": "0.1.4",
    "project_urls": {
        "Homepage": "https://github.com/btrccts/btrccts/"
    },
    "split_keywords": [
        "btrccts"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3245611be6757ddb489b38ed0f7f5a2d067f0a963b5978dbee81850f95a89c33",
                "md5": "46b5834a7896f21f2507baf3b81603d8",
                "sha256": "bb4472f3159438711f75fae49a1c07ae3c05e4232e3401c05dfe2f3f4beedce6"
            },
            "downloads": -1,
            "filename": "btrccts-0.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "46b5834a7896f21f2507baf3b81603d8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 19797,
            "upload_time": "2023-12-03T01:47:15",
            "upload_time_iso_8601": "2023-12-03T01:47:15.391114Z",
            "url": "https://files.pythonhosted.org/packages/32/45/611be6757ddb489b38ed0f7f5a2d067f0a963b5978dbee81850f95a89c33/btrccts-0.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7251102a3506a631dabc39c60465abe54b3844aaef635557d45d821a8145b470",
                "md5": "3616852fff2e7e653606f26a3ea42054",
                "sha256": "f9fa663156119efdcdfa07c7413f5bf32d22ebe6a1632daae2069aabbcdc50e9"
            },
            "downloads": -1,
            "filename": "btrccts-0.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "3616852fff2e7e653606f26a3ea42054",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 18997,
            "upload_time": "2023-12-03T01:47:17",
            "upload_time_iso_8601": "2023-12-03T01:47:17.938464Z",
            "url": "https://files.pythonhosted.org/packages/72/51/102a3506a631dabc39c60465abe54b3844aaef635557d45d821a8145b470/btrccts-0.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-03 01:47:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "btrccts",
    "github_project": "btrccts",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "btrccts"
}
        
Elapsed time: 0.14444s