Synchronize portfolio after buying in live mode
Dear Catalyst Maintainers,
Before I tell you about my issue, let me describe my environment:
Environment
- Operating System: ubuntu 16.04
- Python Version: 2.7
- Python Bitness: 64
- How did you install Catalyst: pip
- Python packages:
alembic==0.9.6 bcolz==0.12.1 boto3==1.5.1 botocore==1.8.15 Bottleneck==1.2.1 ccxt==1.10.400 certifi==2017.11.5 chardet==3.0.4 click==6.7 contextlib2==0.5.5 cyordereddict==1.0.0 Cython==0.27.3 decorator==4.1.2 docutils==0.14 empyrical==0.2.1 enigma-catalyst==0.4.0 futures==3.2.0 idna==2.6 int-date==0.1.8 intervaltree==2.1.0 jmespath==0.9.3 Logbook==1.1.0 lru-dict==1.1.6 Mako==1.0.7 MarkupSafe==1.0 multipledispatch==0.4.9 networkx==2.0 numexpr==2.6.4 numpy==1.13.3 pandas==0.19.2 pandas-datareader==0.5.0 patsy==0.4.1 pkg-resources==0.0.0 python-dateutil==2.6.1 python-editor==1.0.3 pytz==2017.3 requests==2.18.4 requests-file==1.4.2 requests-ftp==0.3.1 s3transfer==0.1.12 scipy==1.0.0 six==1.11.0 sortedcontainers==1.5.9 SQLAlchemy==1.1.15 statsmodels==0.8.0 stockstats==0.2.0 tables==3.4.2 toolz==0.9.0 urllib3==1.22
Now that you know a little about me, let me tell you about the issue I am having:
Description of Issue
I am running a live bot on binance and evertime the bot buys something it will crash
-
What did you expect to happen? The bot would continue after buying
-
What happened instead?
for capital_change_packet in every_bar(dt):
File "/home/catalyst/catalyst-venv/local/lib/python2.7/site-packages/catalyst/gens/tradesimulation.py", line 137, in every_bar
handle_data(algo, current_data, dt_to_use)
File "/home/catalyst/catalyst-venv/local/lib/python2.7/site-packages/catalyst/utils/events.py", line 216, in handle_data
dt,
File "/home/catalyst/catalyst-venv/local/lib/python2.7/site-packages/catalyst/utils/events.py", line 235, in handle_data
self.callback(context, data)
File "/home/catalyst/catalyst-venv/local/lib/python2.7/site-packages/catalyst/exchange/exchange_algorithm.py", line 641, in handle_data
cash, positions_value = self.synchronize_portfolio()
File "/home/catalyst/catalyst-venv/local/lib/python2.7/site-packages/catalyst/exchange/exchange_algorithm.py", line 523, in synchronize_portfolio
raise ValueError('Cash on exchanges is lower than the algo.')
ValueError: Cash on exchanges is lower than the algo.
Here is how you can reproduce this issue on your machine:
Reproduction Steps
- Run the mean_reversion_simple on live mode
- The bot will find something to buy
- It will crash
What steps have you taken to resolve this already?
Couldnt think of anything to solvce this
Sincerely, Vincent
I just tried commenting the ValueError in my catalyst, This seems to do the trick. It doesnt crash anymore.
When i look at the output of my console I notice it will take binance takes a few minutes to give the new cash value.
Maybe there should be some room of error, where the bot waits till the cash is the same as the in the exchange and only errors when it takes to long
I have the same error when trying to buy two or more assets in my portfolio algo. By the way, how I can save and load actual positions when I restart the bot?
When running live mode it already creates a file that keeps track of this. The file is named after the namespace of the algo. Myself i had problems with this because when i adjusted the algo and traded again it would get incorrect cash and postition numbers. (I also made a issue about this right after this issue)
It seems like you are saying that the algo raises a ValueError when it tries to fetch the cash balance from Binance?
Catalysts does fetch a balance after every frame. That's how it can keep stats like p&l up to date. It's always aware of the latest price of a position. It also ensures that the cash and positions in the algo are equal or larger than in the exchange account.
When there is an error fetching data from an exchange, Catalyst should retry at least five times before giving up. Do you have an error trace of this error so I can have a better idea of where it is failing? We do have an algo trading live on Binance. We have not experienced this issue so far.
Right now i cannot test it. I will look at it later to see if i can add some more details.
From what i remember the algo crashed right after buying without first rechecking.
Some comments about this bug. I met it too in Bittrex live mode. Just after the deal cash didn't updated (I checked exchange balance and exposure_stats.csv in live_algos folder). Deal executed perfectly, I saw it in orders history at exchange.
Moreover, there are additional bugs:
- If you buy multiple assets in same time, current price updated only for first asset.
- If you try to get current prices for list of assets (for example: prices = data.current(context.assets, 'price') where context.assets is a list), you can see differnt behaivor in live and backtest modes. In backtest mode all is fine (each column in DataFrame contains prices for corresponding asset), but in live mode all columns filled with prices of the first asset.
Think, it will help to locate the bug.
Yes, that helps. We’ll resolve this asap. On Thu, Dec 21, 2017 at 1:21 AM camanio [email protected] wrote:
Some comments about this bug. I met it too in Bittrex live mode. Just after the deal cash didn't updated (I checked exchange balance and exposure_stats.csv in live_algos folder). Deal executed perfectly, I saw it in orders history at exchange.
Moreover, there are additional bugs:
- If you buy multiple assets in same time, current price updated only for first asset.
- If you try to get current prices for list of assets (for example: prices = data.current(context.assets, 'price') where context.assets is a list), you can see differnt behaivor in live and backtest modes. In backtest mode all is fine (each column in DataFrame contains prices for corresponding asset), but in live mode all columns filled with prices of the first asset.
Think, it will help to locate the bug.
— You are receiving this because you commented.
Reply to this email directly, view it on GitHub https://github.com/enigmampc/catalyst/issues/111#issuecomment-353300532, or mute the thread https://github.com/notifications/unsubscribe-auth/ABZ-QvrTUdYM76oZT-9mPQXrmx2fS3P7ks5tCiMVgaJpZM4RIJcQ .
I'm also experiencing this on Binance. I'm executing multiple sells and multiple buys on different assets in one go... then the sync fails.
The original issue (cash synchronization) is resolved (in the develop branch for now, but we'll do a release tonight). Looking into @camanio 's comment.
@camanio what do you mean by this: "If you buy multiple assets in same time, current price updated only for first asset.". Are you talking about the stats being printed at the bottom of the algo output for each frame. If you, how do you record the two prices?
@camanio we've improved the stats printing to support multiple assets. See commit attached to this issue for example. The command data.current(assets, 'price) does return the correct values for the specified assets in live and backtest. This is from the develop branch but we will release tonight.
Here is the stats output for this example:
symbol amount cost_basis last_sale_price price
period_close starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions
2018-01-04 01:25:00+00:00 0.01 -0.11475568 0.00968858 -0.00031142 0.12444426 0 1 1 eth_btc 2 0.06237784 0.06222213 0.06222213
1 eth_usdt 0 0.00000000 0.00000000 936.12540593
The modified example:
from catalyst import run_algorithm
from catalyst.api import order, record, symbol
import pandas as pd
from catalyst.exchange.utils.stats_utils import get_pretty_stats
def initialize(context):
context.assets = [symbol('eth_btc'), symbol('eth_usdt')]
def handle_data(context, data):
order(context.assets[0], 1)
prices = data.current(context.assets, 'price')
record(price=prices)
pass
def analyze(context, perf):
stats = get_pretty_stats(perf)
print(stats)
pass
if __name__ == '__main__':
live = True
if live:
run_algorithm(
capital_base=0.01,
initialize=initialize,
handle_data=handle_data,
exchange_name='poloniex',
algo_namespace='buy_btc_polo_jh',
base_currency='btc',
analyze=analyze,
live=True,
simulate_orders=True,
)
else:
run_algorithm(
capital_base=1000,
data_frequency='daily',
initialize=initialize,
handle_data=handle_data,
exchange_name='poloniex',
algo_namespace='buy_btc_polo_jh',
base_currency='usd',
analyze=analyze,
start=pd.to_datetime('2017-01-01', utc=True),
end=pd.to_datetime('2017-12-25', utc=True),
)
Please reopen if it's still happening in version 0.4.2.
@fredfortier Thanks a lot! All stats calcs perfectly, I just tested it in live mode at Bittrex.
@fredfortier Hello! This problem arise again. Please, try to reproduce these steps in live mode:
- Open some positions, two positions in different assets are enough. You will see correct stats update and at this stage all OK.
- Interrupt algo. It is usual situation - exception may arise due some problems with exchange, you wish fix some bugs in algo, etc.
- Run the algo again (you must decrease capital_base and turn off condition in exchange.exchange.py, line 693) and try to sell any asset (for example, you can buy & sell assets by timer). You will see very strange behaivor:
- sell order accepted by exchange
- total assets remain same (catalyst does not see the deal)
I traced execution in debugger - sync with exchange is OK, but portfolio does not update. Without interruption catalyst works well. May be something wrong with save/restore procedure?
By the way, can you allow restarting algos without hacking of catalyst?
Thanks @camanio ! I got it. We'll issue a new release when fixed (tentatively today).
If by restarting algos, you mean clearing their state, use this command:
catalyst clean-algo -n [your algo namespace]
Fixed. Basically, Zipline uses PositionTracker object to keep track of positions. This object is an attribute of three other objects, two of which are being pickled to keep the algo state. When restoring the state, I had to propagate one of the saved PerformanceTracker to all three objects.
I'll take care of one more thing before releasing this.
This wasn't an issue a few versions back because we were pickling the entire PerformanceTracker object. We made it more granular because of Python 3 pickling issues. This granularity also makes things easier to unit test.
Thanks, @fredfortier ! I'll test the patch ASAP.
About restarting an algo. If I not mistaken, clean-algo delete all information about algo state. But what's about restarting the same algo with its current state? If I run clean-algo, I must close all postions manually via exchange web interface and after that run the algo again. But I want to restart the algo automatically - for example, in case of some troubles at exchange side (as a rule, catalyst crashes if exchange does not respond for some time). Now I'm using for these cases try - exception block around run_algorithm function and small hack mentioned above (disable check for minimum capital amount). But I think it is very dirty way and this wonderful platform can support restarting out-of-the-box.
@fredfortier ! I just tested your patch in live mode at Bittrex. There is a part of logs:
[2018-01-08 11:26:15.009718] INFO: port_eaa_btc_v5p: BAR 2018-01-08 11:25:00+00:00 BUY: TradingPair(833710 [salt_btc]) @0.00080461 amount: 32.38477931483457 (0)
[2018-01-08 11:26:15.010303] INFO: CCXT: adjusted order amount 32.3847793148 to 32.38477931 based on lot size
[2018-01-08 11:26:15.272044] INFO: exchange_algorithm: statistics for the last 1 minutes:
starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions leverage
period_close
2018-01-08 11:26:00+00:00 0.03 0.03 0.03 0.0 0 0 0 0 0.0
[2018-01-08 11:26:15.518703] INFO: CCXT: order deb9112f-b01e-4593-8339-e1ac4a3e5e44 executed in full: 32.38477931 salt_btc
[2018-01-08 11:26:15.731238] WARNING: Exchange: detected lower balance for salt_btc on bittrex: 0.0 < 32.38477931, updating position amount
[2018-01-08 11:26:15.734103] INFO: exchange_algorithm: portfolio balances, cash: 0.0281014, positions: 0.0260571172806
[2018-01-08 11:26:15.815477] INFO: exchange_algorithm: statistics for the last 1 minutes:
starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions leverage
period_close
2018-01-08 11:27:00+00:00 0.03 0.00381983 0.00381983 -0.02618017 0 0 2 1 0.87267233
[2018-01-08 11:27:01.199748] INFO: exchange_algorithm: portfolio balances, cash: 0.02863124, positions: 0.0
[2018-01-08 11:27:01.277624] INFO: exchange_algorithm: statistics for the last 1 minutes:
starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions leverage
period_close
2018-01-08 11:28:00+00:00 0.03 0.00381983 0.00381983 -0.02618017 0 0 0 0 0.0
[2018-01-08 11:28:00.644121] INFO: exchange_algorithm: portfolio balances, cash: 0.02863124, positions: 0.0
[2018-01-08 11:28:00.698451] INFO: exchange_algorithm: statistics for the last 1 minutes:
starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions leverage
period_close
2018-01-08 11:29:00+00:00 0.03 0.00381983 0.00381983 -0.02618017 0 0 0 0 0.0
As you can see, algo succefully bought some salt_btc (I checked the deal via exchange web interface), but apropriate amount does not appear at stats table. The same problem was before the patch after restarting an algo, but now it arises at first run. I tried rerun algo again (sold all assets manually and run clean-algo) and it works well. I can not figure out the roots of this problem.
Not sure if this is related - but for some reason my portfolio amounts are also way off.
[2018-01-10 09:08:01.418589] INFO: goose1: 2018-01-10 09:08:00+00:00: buying - price: 7.7e-06
[2018-01-10 09:08:01.418728] INFO: goose1: 7.93e-06: limit - stop: 7.585e-06
[2018-01-10 09:08:01.548843] INFO: CCXT: adjusted order amount 389.61038961 to 389.0 based on lot size
[2018-01-10 09:08:01.706259] INFO: exchange_algorithm: statistics for the last 1 minutes:
starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions price price_change cash
period_close
2018-01-10 09:09:00+00:00 0.003 0.003 0.003 0.0 0 0 0 0 0.0000077 0.04904632 0.003
[2018-01-10 09:08:01.710049] WARNING: exchange_algorithm: unable save stats locally: 'price'
[2018-01-10 09:09:00.872266] INFO: CCXT: order 16542720 executed in full: 389.0 trx_btc
[2018-01-10 09:09:01.154222] WARNING: Exchange: detected lower balance for trx_btc on binance: 388.679 < 389.0, updating position amount
[2018-01-10 09:09:01.155661] INFO: exchange_algorithm: got totals from exchanges, cash: 0.06450654 positions: 0.00292528
[2018-01-10 09:09:02.345206] INFO: goose1: 2018-01-10 09:09:00+00:00: selling - price: 7.52e-06 - bought at: 7.7e-06
[2018-01-10 09:09:02.478747] INFO: CCXT: adjusted order amount 388.679 to 388.0 based on lot size
[2018-01-10 09:09:02.645483] INFO: exchange_algorithm: statistics for the last 1 minutes:
period_close starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions price price_change cash
2018-01-10 09:10:00+00:00 0.003 0.003 0.00592287 0.00292287 0.00292287 0 1 1 0.00000752 0.02452316 0.003 trx_btc 388.679 0.0 0.00000752
I sold at a loss, but my portfolio value is now double?
We haven't pushed the patch yet as we had to focus on something else. We'll do this today. Which exchange are you trading with?
On Wed, Jan 10, 2018 at 4:11 AM Ericxgao [email protected] wrote:
Not sure if this is related - but for some reason my portfolio amounts are also way off.
[2018-01-10 09:08:01.418589] INFO: goose1: 2018-01-10 09:08:00+00:00: buying - price: 7.7e-06 [2018-01-10 09:08:01.418728] INFO: goose1: 7.93e-06: limit - stop: 7.585e-06 [2018-01-10 09:08:01.548843] INFO: CCXT: adjusted order amount 389.61038961 to 389.0 based on lot size [2018-01-10 09:08:01.706259] INFO: exchange_algorithm: statistics for the last 1 minutes: starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions price price_change cash period_close 2018-01-10 09:09:00+00:00 0.003 0.003 0.003 0.0 0 0 0 0 0.0000077 0.04904632 0.003 [2018-01-10 09:08:01.710049] WARNING: exchange_algorithm: unable save stats locally: 'price' [2018-01-10 09:09:00.872266] INFO: CCXT: order 16542720 executed in full: 389.0 trx_btc [2018-01-10 09:09:01.154222] WARNING: Exchange: detected lower balance for trx_btc on binance: 388.679 < 389.0, updating position amount [2018-01-10 09:09:01.155661] INFO: exchange_algorithm: got totals from exchanges, cash: 0.06450654 positions: 0.00292528 [2018-01-10 09:09:02.345206] INFO: goose1: 2018-01-10 09:09:00+00:00: selling - price: 7.52e-06 - bought at: 7.7e-06 [2018-01-10 09:09:02.478747] INFO: CCXT: adjusted order amount 388.679 to 388.0 based on lot size [2018-01-10 09:09:02.645483] INFO: exchange_algorithm: statistics for the last 1 minutes: period_close starting_cash ending_cash portfolio_value pnl long_exposure short_exposure orders transactions price price_change cash 2018-01-10 09:10:00+00:00 0.003 0.003 0.00592287 0.00292287 0.00292287 0 1 1 0.00000752 0.02452316 0.003 trx_btc 388.679 0.0 0.00000752
I sold at a loss, but my portfolio value is now double?
— You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/enigmampc/catalyst/issues/111#issuecomment-356543970, or mute the thread https://github.com/notifications/unsubscribe-auth/ABZ-Qvud9dxEpkGwL2DRwu_x_3pUZO-5ks5tJH7CgaJpZM4RIJcQ .