forked from l0c4t0r/active-strategy-framework
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AutoRegressiveStrategy.py
565 lines (442 loc) · 31.6 KB
/
AutoRegressiveStrategy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import pandas as pd
import numpy as np
import math
import arch
import UNI_v3_funcs
import ActiveStrategyFramework
import scipy
import copy
class AutoRegressiveStrategy:
def __init__(self,model_data,alpha_param,tau_param,volatility_reset_ratio,tokens_outside_reset = .05,data_frequency='D',default_width = .5,days_ar_model = 180,return_forecast_cutoff=0.15,z_score_cutoff=5):
# Allow for different input data frequencies, always get 1 day ahead forecast
# Model data frequency is expressed in minutes
if data_frequency == 'D':
self.annualization_factor = 365**.5
self.resample_option = '1D'
self.window_size = 15
elif data_frequency == 'H':
self.annualization_factor = (24*365)**.5
self.resample_option = '1H'
self.window_size = 30
elif data_frequency == 'M':
self.annualization_factor = (60*24*365)**.5
self.resample_option = '1 min'
self.window_size = 60
self.alpha_param = alpha_param
self.tau_param = tau_param
self.volatility_reset_ratio = volatility_reset_ratio
self.data_frequency = data_frequency
self.tokens_outside_reset = tokens_outside_reset
self.default_width = default_width
self.return_forecast_cutoff = return_forecast_cutoff
self.days_ar_model = days_ar_model
self.z_score_cutoff = z_score_cutoff
self.window_size = 60*24*30
self.model_data = self.clean_data_for_garch(model_data)
#####################################
# Estimate AR model at current timepoint
#####################################
def clean_data_for_garch(self,data_in):
data_filled = ActiveStrategyFramework.fill_time(data_in)
# Filter according to Median Absolute Deviation
# 1. Generate rolling median
data_filled_rolling = data_filled.quotePrice.rolling(window=self.window_size)
data_filled['roll_median'] = data_filled_rolling.median()
# 2. Compute rolling absolute deviation of current price from median under Gaussian
roll_dev = np.abs(data_filled.quotePrice - data_filled.roll_median)
data_filled['median_abs_dev'] = 1.4826*roll_dev.rolling(window=self.window_size).median()
# 3. Identify outliers using MAD
outlier_indices = np.abs(data_filled.quotePrice - data_filled.roll_median) >= self.z_score_cutoff*data_filled['median_abs_dev']
# impute
#data_filled['quotePrice'] = np.where(outlier_indices.values == 0, data_filled['quotePrice'].values,data_filled['roll_median'].values)
# drop
data_filled = data_filled[~outlier_indices]
return data_filled
def generate_model_forecast(self,timepoint):
# Compute returns with data_frequency frequency starting at the current timepoint and looking backwards
current_data = self.model_data.loc[:timepoint].resample(self.resample_option,closed='right',label='right',origin=timepoint).last()
current_data['price_return'] = current_data['quotePrice'].pct_change()
current_data = current_data.dropna(axis=0,subset=['price_return'])
ar_model = arch.univariate.ARX(current_data.price_return[(current_data.index >= (timepoint - pd.Timedelta(str(self.days_ar_model)+' days')))].to_numpy(), lags=1,rescale=True)
ar_model.volatility = arch.univariate.GARCH(p=1,q=1)
res = ar_model.fit(update_freq=0, disp="off")
scale = res.scale
forecasts = res.forecast(horizon=1, reindex=False)
return_forecast = forecasts.mean.to_numpy()[0][-1] / scale
sd_forecast = (forecasts.variance.to_numpy()[0][-1] / np.power(res.scale,2))**0.5 * self.annualization_factor
result_dict = {'return_forecast': return_forecast,
'sd_forecast' : sd_forecast}
return result_dict
def check_compound_possible(self,current_strat_obs):
baseLower = current_strat_obs.liquidity_ranges[0]['lower_bin_tick']
baseUpper = current_strat_obs.liquidity_ranges[0]['upper_bin_tick']
limitLower = current_strat_obs.liquidity_ranges[1]['lower_bin_tick']
limitUpper = current_strat_obs.liquidity_ranges[1]['upper_bin_tick']
base_assets_token_1 = current_strat_obs.liquidity_ranges[0]['token_0'] * current_strat_obs.price + current_strat_obs.liquidity_ranges[0]['token_1']
limit_assets_token_1 = current_strat_obs.liquidity_ranges[0]['token_0'] * current_strat_obs.price + current_strat_obs.liquidity_ranges[0]['token_1']
unused_token_0 = current_strat_obs.token_0_left_over + current_strat_obs.token_0_fees_uncollected
unused_token_1 = current_strat_obs.token_1_left_over + current_strat_obs.token_1_fees_uncollected
#####################################
# Add all possible assets to base
#####################################
liquidity_placed_base = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,baseLower,baseUpper,unused_token_0, \
unused_token_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
base_amount_0_placed,base_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,baseLower,baseUpper,liquidity_placed_base\
,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
#####################################
# Add remaining assets to limit
#####################################
limit_amount_0 = unused_token_0 - base_amount_0_placed
limit_amount_1 = unused_token_1 - base_amount_1_placed
token_0_limit = limit_amount_0*current_strat_obs.price > limit_amount_1
# Place single sided highest value
if token_0_limit:
# Place Token 0
limit_amount_1 = 0.0
else:
# Place Token 1
limit_amount_0 = 0.0
liquidity_placed_limit = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,limitLower,limitUpper, \
limit_amount_0,limit_amount_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
limit_amount_0_placed,limit_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,limitLower,limitUpper,\
liquidity_placed_limit,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
base_assets_after_compound_token_1 = base_amount_0_placed * current_strat_obs.price + base_amount_1_placed + base_assets_token_1
limit_assets_after_compound_token_1 = limit_amount_0_placed * current_strat_obs.price + limit_amount_1_placed + limit_assets_token_1
# if assets changed more than 1%
if ((base_assets_after_compound_token_1+limit_assets_after_compound_token_1)/(base_assets_token_1 + limit_assets_token_1) - 1) > .01:
return True
else:
return False
#####################################
# Check if a rebalance is necessary.
# If it is, remove the liquidity and set new ranges
#####################################
def check_strategy(self,current_strat_obs):
model_forecast = None
LIMIT_ORDER_BALANCE = current_strat_obs.liquidity_ranges[1]['token_0'] * current_strat_obs.price + current_strat_obs.liquidity_ranges[1]['token_1']
BASE_ORDER_BALANCE = current_strat_obs.liquidity_ranges[0]['token_0'] * current_strat_obs.price + current_strat_obs.liquidity_ranges[0]['token_1']
if not 'last_vol_check' in current_strat_obs.strategy_info:
current_strat_obs.strategy_info['last_vol_check'] = current_strat_obs.time
#####################################
#
# This strategy rebalances in these scenarios:
# 1. Leave Reset Range
# 2. Volatility has dropped (volatility_reset_ratio)
# 3. An outside initial reset is forced
# 4. Tokens outside the position will be compounded when they are > tokens_outside_reset % of the LP tokens
#
#####################################
#######################
# 1. Leave Reset Range
#######################
LEFT_RANGE_LOW = current_strat_obs.price < current_strat_obs.strategy_info['reset_range_lower']
LEFT_RANGE_HIGH = current_strat_obs.price > current_strat_obs.strategy_info['reset_range_upper']
#######################
# 2. Volatility has dropped
#######################
# Rebalance if volatility has gone down significantly
# When volatility increases the reset range will be hit
# Check every hour (60 minutes)
ar_check_frequency = 60
time_since_reset = current_strat_obs.time - current_strat_obs.strategy_info['last_vol_check']
VOL_REBALANCE = False
if (time_since_reset.total_seconds() / 60) >= ar_check_frequency:
current_strat_obs.strategy_info['last_vol_check'] = current_strat_obs.time
model_forecast = self.generate_model_forecast(current_strat_obs.time)
if model_forecast['sd_forecast']/current_strat_obs.liquidity_ranges[0]['volatility'] <= self.volatility_reset_ratio:
VOL_REBALANCE = True
else:
VOL_REBALANCE = False
#######################
# 3. Outside reset is forced
#######################
if 'force_initial_reset' in current_strat_obs.strategy_info:
if current_strat_obs.strategy_info['force_initial_reset']:
INITIAL_RESET = True
current_strat_obs.strategy_info['force_initial_reset'] = False
else:
INITIAL_RESET = False
else:
INITIAL_RESET = False
#######################
# 4. Compound when tokens outside of pool greater than tokens_outside_reset% of value of LP position
#######################
left_over_balance = (current_strat_obs.token_0_left_over + current_strat_obs.token_0_fees_uncollected) * current_strat_obs.price \
+ (current_strat_obs.token_1_left_over + current_strat_obs.token_0_fees_uncollected)
if (left_over_balance > self.tokens_outside_reset * (LIMIT_ORDER_BALANCE + BASE_ORDER_BALANCE)):
TOKENS_OUTSIDE_LARGE = True
else:
TOKENS_OUTSIDE_LARGE = False
# If a reset is necessary
if (((LEFT_RANGE_LOW | LEFT_RANGE_HIGH) | VOL_REBALANCE) | INITIAL_RESET):
current_strat_obs.reset_point = True
if (LEFT_RANGE_LOW | LEFT_RANGE_HIGH):
current_strat_obs.reset_reason = 'exited_range'
elif VOL_REBALANCE:
current_strat_obs.reset_reason = 'vol_rebalance'
elif TOKENS_OUTSIDE_LARGE:
current_strat_obs.reset_reason = 'tokens_outside_large'
elif INITIAL_RESET:
current_strat_obs.reset_reason = 'initial_reset'
# Remove liquidity and claim fees
current_strat_obs.remove_liquidity()
# Reset liquidity
liquidity_ranges,strategy_info = self.set_liquidity_ranges(current_strat_obs,model_forecast)
return liquidity_ranges,strategy_info
# If a compound is necessary
elif TOKENS_OUTSIDE_LARGE:
if self.check_compound_possible(current_strat_obs):
# if price allows for a compound
current_strat_obs.compound_point = True
current_strat_obs.reset_reason = 'compound'
# Compound position
self.compound(current_strat_obs)
return current_strat_obs.liquidity_ranges,current_strat_obs.strategy_info
else:
# otherwise rebalance
current_strat_obs.reset_point = True
current_strat_obs.reset_reason = 'tokens_outside_large'
# Remove liquidity and claim fees
current_strat_obs.remove_liquidity()
# Reset liquidity
liquidity_ranges,strategy_info = self.set_liquidity_ranges(current_strat_obs)
return liquidity_ranges,strategy_info
else:
return current_strat_obs.liquidity_ranges,current_strat_obs.strategy_info
########################################################
# Rebalance the position
########################################################
def set_liquidity_ranges(self,current_strat_obs,model_forecast = None):
###########################################################
# STEP 1: Do calculations required to determine base liquidity bounds
###########################################################
# Fit model if not passed from check_strategy
if model_forecast is None:
model_forecast = self.generate_model_forecast(current_strat_obs.time)
# Make sure strategy_info (dict with additional vars exists)
if current_strat_obs.strategy_info is None:
strategy_info_here = dict()
else:
strategy_info_here = copy.deepcopy(current_strat_obs.strategy_info)
# Limit return prediction to a return_forecast_cutoff % change
if np.abs(model_forecast['return_forecast']) > self.return_forecast_cutoff:
model_forecast['return_forecast'] = np.sign(model_forecast['return_forecast']) * self.return_forecast_cutoff
# If error in volatility computation use last or overall standard deviation of returns
if np.isnan(model_forecast['sd_forecast']):
if hasattr(current_strat_obs,'liquidity_ranges'):
model_forecast['sd_forecast'] = current_strat_obs.liquidity_ranges[0]['volatility']
else:
model_forecast['sd_forecast'] = self.model_data.quotePrice.pct_change().std()
target_price = (1 + model_forecast['return_forecast']) * current_strat_obs.price
# Set the base range
base_range_lower = current_strat_obs.price * (1 + model_forecast['return_forecast'] - self.alpha_param*model_forecast['sd_forecast'])
base_range_upper = current_strat_obs.price * (1 + model_forecast['return_forecast'] + self.alpha_param*model_forecast['sd_forecast'])
# Set the reset range
strategy_info_here['reset_range_lower'] = current_strat_obs.price * (1 + model_forecast['return_forecast'] - self.tau_param*self.alpha_param*model_forecast['sd_forecast'])
strategy_info_here['reset_range_upper'] = current_strat_obs.price * (1 + model_forecast['return_forecast'] + self.tau_param*self.alpha_param*model_forecast['sd_forecast'])
# If volatility is high enough reset range is less than zero, set at default_width of current price
if strategy_info_here['reset_range_lower'] < 0.0:
strategy_info_here['reset_range_lower'] = self.default_width * current_strat_obs.price
liquidity_ranges = []
###########################################################
# STEP 2: Set Base Liquidity
###########################################################
# Store each token amount supplied to pool
total_token_0_amount = current_strat_obs.liquidity_in_0
total_token_1_amount = current_strat_obs.liquidity_in_1
# Set baseLower
if base_range_lower > 0.0:
baseLowerPRE = math.log(current_strat_obs.decimal_adjustment*base_range_lower,1.0001)
baseLower = int(math.floor(baseLowerPRE/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing)
else:
# If lower end of base range is negative, fix at 0.0
base_range_lower = 0.0
baseLower = math.ceil(math.log((2**-128),1.0001)/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing
# Set baseUpper
baseUpperPRE = math.log(current_strat_obs.decimal_adjustment*base_range_upper,1.0001)
baseUpper = int(math.floor(baseUpperPRE/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing)
## Sanity Checks
# Make sure baseLower < baseUpper. If not make two tick
if baseLower >= baseUpper:
baseLower = current_strat_obs.price_tick - current_strat_obs.tickSpacing
baseUpper = current_strat_obs.price_tick + current_strat_obs.tickSpacing
liquidity_placed_base = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,baseLower,baseUpper,current_strat_obs.liquidity_in_0, \
current_strat_obs.liquidity_in_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
base_amount_0_placed,base_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,baseLower,baseUpper,liquidity_placed_base\
,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
base_liq_range = {'price' : current_strat_obs.price,
'target_price' : target_price,
'lower_bin_tick' : baseLower,
'upper_bin_tick' : baseUpper,
'lower_bin_price' : base_range_lower,
'upper_bin_price' : base_range_upper,
'time' : current_strat_obs.time,
'token_0' : base_amount_0_placed,
'token_1' : base_amount_1_placed,
'position_liquidity' : liquidity_placed_base,
'volatility' : model_forecast['sd_forecast'],
'reset_time' : current_strat_obs.time,
'return_forecast' : model_forecast['return_forecast']}
liquidity_ranges.append(base_liq_range)
###########################
# Step 3: Set Limit Position
############################
limit_amount_0 = total_token_0_amount - base_amount_0_placed
limit_amount_1 = total_token_1_amount - base_amount_1_placed
token_0_limit = limit_amount_0*current_strat_obs.price > limit_amount_1
# Place singe sided highest value
if token_0_limit:
# Place Token 0
limit_amount_1 = max([0.0,limit_amount_1])
limit_range_lower = current_strat_obs.price
limit_range_upper = base_range_upper
else:
# Place Token 1
limit_amount_0 = max([0.0,limit_amount_0])
limit_range_lower = base_range_lower
limit_range_upper = current_strat_obs.price
# Set limitLower
if limit_range_lower > 0.0:
limitLowerPRE = math.log(current_strat_obs.decimal_adjustment*limit_range_lower,1.0001)
limitLower = int(math.floor(limitLowerPRE/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing)
else:
limit_range_lower = 0.0
limitLower = math.ceil(math.log((2**-128),1.0001)/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing
# Set limitUpper
limitUpperPRE = math.log(current_strat_obs.decimal_adjustment*limit_range_upper,1.0001)
limitUpper = int(math.floor(limitUpperPRE/current_strat_obs.tickSpacing)*current_strat_obs.tickSpacing)
## Sanity Checks
if token_0_limit:
if limitLower <= current_strat_obs.price_tick_current:
# If token 0 in limit, make sure lower tick is above active tick
limitLower = limitLower + current_strat_obs.tickSpacing
elif (limitLower / current_strat_obs.price_tick_current) < 1.25:
# if bottom of limit tick is less than 125% of the current, add one tick space
limitLower = limitLower + current_strat_obs.tickSpacing
else:
# In token 1 in limit, make sure upper tick is below active tick
if limitUpper >= current_strat_obs.price_tick_current:
limitUpper = limitUpper - current_strat_obs.tickSpacing
elif (current_strat_obs.price_tick_current / limitUpper) < 1.25:
# if current is less than 125% of top of limit tick, reduce one tick space
limitUpper = limitUpper - current_strat_obs.tickSpacing
# Make sure limitLower < limitUpper. If not make one tick
if limitLower >= limitUpper:
if token_0_limit:
limitLower += current_strat_obs.tickSpacing
else:
limitUpper -= current_strat_obs.tickSpacing
liquidity_placed_limit = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,limitLower,limitUpper, \
limit_amount_0,limit_amount_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
limit_amount_0_placed,limit_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,limitLower,limitUpper,\
liquidity_placed_limit,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
limit_liq_range = {'price' : current_strat_obs.price,
'target_price' : target_price,
'lower_bin_tick' : limitLower,
'upper_bin_tick' : limitUpper,
'lower_bin_price' : limit_range_lower,
'upper_bin_price' : limit_range_upper,
'time' : current_strat_obs.time,
'token_0' : limit_amount_0_placed,
'token_1' : limit_amount_1_placed,
'position_liquidity' : liquidity_placed_limit,
'volatility' : model_forecast['sd_forecast'],
'reset_time' : current_strat_obs.time,
'return_forecast' : model_forecast['return_forecast']}
liquidity_ranges.append(limit_liq_range)
# How much liquidity is not allcated to ranges
current_strat_obs.token_0_left_over = max([total_token_0_amount - base_amount_0_placed - limit_amount_0_placed,0.0])
current_strat_obs.token_1_left_over = max([total_token_1_amount - base_amount_1_placed - limit_amount_1_placed,0.0])
# Since liquidity was allocated, set to 0
current_strat_obs.liquidity_in_0 = 0.0
current_strat_obs.liquidity_in_1 = 0.0
return liquidity_ranges,strategy_info_here
########################################################
# Compound unused liquidity
########################################################
def compound(self,current_strat_obs):
unused_token_0 = current_strat_obs.token_0_left_over + current_strat_obs.token_0_fees_uncollected
unused_token_1 = current_strat_obs.token_1_left_over + current_strat_obs.token_1_fees_uncollected
baseLower = current_strat_obs.liquidity_ranges[0]['lower_bin_tick']
baseUpper = current_strat_obs.liquidity_ranges[0]['upper_bin_tick']
limitLower = current_strat_obs.liquidity_ranges[1]['lower_bin_tick']
limitUpper = current_strat_obs.liquidity_ranges[1]['upper_bin_tick']
#####################################
# Add all possible assets to base
#####################################
liquidity_placed_base = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,baseLower,baseUpper,unused_token_0, \
unused_token_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
base_amount_0_placed,base_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,baseLower,baseUpper,liquidity_placed_base\
,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
current_strat_obs.liquidity_ranges[0]['token_0'] += base_amount_0_placed
current_strat_obs.liquidity_ranges[0]['token_1'] += base_amount_1_placed
#####################################
# Add remaining assets to limit
#####################################
limit_amount_0 = unused_token_0 - base_amount_0_placed
limit_amount_1 = unused_token_1 - base_amount_1_placed
token_0_limit = limit_amount_0*current_strat_obs.price > limit_amount_1
# Place single sided highest value
if token_0_limit:
# Place Token 0
limit_amount_1 = 0.0
else:
# Place Token 1
limit_amount_0 = 0.0
liquidity_placed_limit = int(UNI_v3_funcs.get_liquidity(current_strat_obs.price_tick_current,limitLower,limitUpper, \
limit_amount_0,limit_amount_1,current_strat_obs.decimals_0,current_strat_obs.decimals_1))
limit_amount_0_placed,limit_amount_1_placed = UNI_v3_funcs.get_amounts(current_strat_obs.price_tick_current,limitLower,limitUpper,\
liquidity_placed_limit,current_strat_obs.decimals_0,current_strat_obs.decimals_1)
current_strat_obs.liquidity_ranges[1]['token_0'] += limit_amount_0_placed
current_strat_obs.liquidity_ranges[1]['token_1'] += limit_amount_1_placed
# Clean up prior accrued fees and tokens outside
current_strat_obs.token_0_fees_uncollected = 0.0
current_strat_obs.token_1_fees_uncollected = 0.0
# Due to price and asset deposit ratio sometimes can't deposit 100% of assets
current_strat_obs.token_0_left_over = max([0.0,unused_token_0 - base_amount_0_placed - limit_amount_0_placed])
current_strat_obs.token_1_left_over = max([0.0,unused_token_1 - base_amount_1_placed - limit_amount_1_placed])
########################################################
# Extract strategy parameters
########################################################
def dict_components(self,strategy_observation):
this_data = dict()
# General variables
this_data['time'] = strategy_observation.time
this_data['price'] = strategy_observation.price
this_data['reset_point'] = strategy_observation.reset_point
this_data['compound_point'] = strategy_observation.compound_point
this_data['reset_reason'] = strategy_observation.reset_reason
this_data['volatility'] = strategy_observation.liquidity_ranges[0]['volatility']
this_data['return_forecast'] = strategy_observation.liquidity_ranges[0]['return_forecast']
# Range Variables
this_data['base_range_lower'] = strategy_observation.liquidity_ranges[0]['lower_bin_price']
this_data['base_range_upper'] = strategy_observation.liquidity_ranges[0]['upper_bin_price']
this_data['limit_range_lower'] = strategy_observation.liquidity_ranges[1]['lower_bin_price']
this_data['limit_range_upper'] = strategy_observation.liquidity_ranges[1]['upper_bin_price']
this_data['reset_range_lower'] = strategy_observation.strategy_info['reset_range_lower']
this_data['reset_range_upper'] = strategy_observation.strategy_info['reset_range_upper']
this_data['price_at_reset'] = strategy_observation.liquidity_ranges[0]['price']
# Fee Varaibles
this_data['token_0_fees'] = strategy_observation.token_0_fees
this_data['token_1_fees'] = strategy_observation.token_1_fees
this_data['token_0_fees_uncollected'] = strategy_observation.token_0_fees_uncollected
this_data['token_1_fees_uncollected'] = strategy_observation.token_1_fees_uncollected
# Asset Variables
this_data['token_0_left_over'] = strategy_observation.token_0_left_over
this_data['token_1_left_over'] = strategy_observation.token_1_left_over
total_token_0 = 0.0
total_token_1 = 0.0
for i in range(len(strategy_observation.liquidity_ranges)):
total_token_0 += strategy_observation.liquidity_ranges[i]['token_0']
total_token_1 += strategy_observation.liquidity_ranges[i]['token_1']
this_data['token_0_allocated'] = total_token_0
this_data['token_1_allocated'] = total_token_1
this_data['token_0_total'] = total_token_0 + strategy_observation.token_0_left_over + strategy_observation.token_0_fees_uncollected
this_data['token_1_total'] = total_token_1 + strategy_observation.token_1_left_over + strategy_observation.token_1_fees_uncollected
# Value Variables
this_data['value_position_in_token_0'] = this_data['token_0_total'] + this_data['token_1_total'] / this_data['price']
this_data['value_allocated_in_token_0'] = this_data['token_0_allocated'] + this_data['token_1_allocated'] / this_data['price']
this_data['value_left_over_in_token_0'] = this_data['token_0_left_over'] + this_data['token_1_left_over'] / this_data['price']
this_data['base_position_value_in_token_0'] = strategy_observation.liquidity_ranges[0]['token_0'] + strategy_observation.liquidity_ranges[0]['token_1'] / this_data['price']
this_data['limit_position_value_in_token_0'] = strategy_observation.liquidity_ranges[1]['token_0'] + strategy_observation.liquidity_ranges[1]['token_1'] / this_data['price']
return this_data