forked from xeroc/stakemachine
-
Notifications
You must be signed in to change notification settings - Fork 126
/
relative_orders.py
200 lines (162 loc) · 6.85 KB
/
relative_orders.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
import math
from dexbot.basestrategy import BaseStrategy, ConfigElement
from dexbot.qt_queue.idle_queue import idle_add
class Strategy(BaseStrategy):
""" Relative Orders strategy
"""
@classmethod
def configure(cls):
return BaseStrategy.configure() + [
ConfigElement('amount_relative', 'bool', False,
'Amount is expressed as a percentage of the account balance of quote/base asset', None),
ConfigElement('amount', 'float', 1.0,
'The amount of buy/sell orders', (0.0, None)),
ConfigElement('center_price_dynamic', 'bool', True,
'Dynamic centre price', None),
ConfigElement('center_price', 'float', 0.0,
'Initial center price', (0, 0, None)),
ConfigElement('center_price_offset', 'bool', False,
'Center price offset based on asset balances', None),
ConfigElement('spread', 'float', 5.0,
'The percentage difference between buy and sell (Spread)', (0.0, 100.0)),
ConfigElement('manual_offset', 'float', 0.0,
'Manual center price offset', (-50.0, 100.0))
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.log.info("Initializing Relative Orders")
# Define Callbacks
self.onMarketUpdate += self.check_orders
self.onAccount += self.check_orders
self.error_ontick = self.error
self.error_onMarketUpdate = self.error
self.error_onAccount = self.error
self.is_center_price_dynamic = self.worker["center_price_dynamic"]
if self.is_center_price_dynamic:
self.center_price = None
else:
self.center_price = self.worker["center_price"]
self.is_relative_order_size = self.worker['amount_relative']
self.is_asset_offset = self.worker.get('center_price_offset', False)
self.manual_offset = self.worker.get('manual_offset', 0) / 100
self.order_size = float(self.worker['amount'])
self.spread = self.worker.get('spread') / 100
self.buy_price = None
self.sell_price = None
self.initial_balance = self['initial_balance'] or 0
self.worker_name = kwargs.get('name')
self.view = kwargs.get('view')
self.check_orders()
def error(self, *args, **kwargs):
self.cancel_all()
self.disabled = True
@property
def amount_quote(self):
""" Get quote amount, calculate if order size is relative
"""
if self.is_relative_order_size:
quote_balance = float(self.balance(self.market["quote"]))
return quote_balance * (self.order_size / 100)
else:
return self.order_size
@property
def amount_base(self):
""" Get base amount, calculate if order size is relative
"""
if self.is_relative_order_size:
base_balance = float(self.balance(self.market["base"]))
# amount = % of balance / buy_price = amount combined with calculated price to give % of balance
return base_balance * (self.order_size / 100) / self.buy_price
else:
return self.order_size
def calculate_order_prices(self):
if self.is_center_price_dynamic:
self.center_price = self.calculate_center_price(
None,
self.is_asset_offset,
self.spread,
self['order_ids'],
self.manual_offset
)
else:
self.center_price = self.calculate_center_price(
self.center_price,
self.is_asset_offset,
self.spread,
self['order_ids'],
self.manual_offset
)
self.buy_price = self.center_price / math.sqrt(1 + self.spread)
self.sell_price = self.center_price * math.sqrt(1 + self.spread)
def update_orders(self):
self.log.info('Change detected, updating orders')
# Recalculate buy and sell order prices
self.calculate_order_prices()
# Cancel the orders before redoing them
self.cancel_all()
self.clear_orders()
order_ids = []
amount_base = self.amount_base
amount_quote = self.amount_quote
# Buy Side
buy_order = self.market_buy(amount_base, self.buy_price, True)
if buy_order:
self.save_order(buy_order)
order_ids.append(buy_order['id'])
# Sell Side
sell_order = self.market_sell(amount_quote, self.sell_price, True)
if sell_order:
self.save_order(sell_order)
order_ids.append(sell_order['id'])
self['order_ids'] = order_ids
self.log.info("Done placing orders")
# Some orders weren't successfully created, redo them
if len(order_ids) < 2 and not self.disabled:
self.update_orders()
def check_orders(self, *args, **kwargs):
""" Tests if the orders need updating
"""
orders = self.fetch_orders()
if not orders:
self.update_orders()
else:
orders_changed = False
# Loop trough the orders and look for changes
for order_id, order in orders.items():
current_order = self.get_order(order_id)
if not current_order:
orders_changed = True
self.write_order_log(self.worker_name, order)
if orders_changed:
self.update_orders()
else:
self.log.info("Orders correct on market")
if self.view:
self.update_gui_profit()
self.update_gui_slider()
# GUI updaters
def update_gui_profit(self):
# Fixme: profit calculation doesn't work this way, figure out a better way to do this.
if self.initial_balance:
profit = round((self.orders_balance(None) - self.initial_balance) / self.initial_balance, 3)
else:
profit = 0
idle_add(self.view.set_worker_profit, self.worker_name, float(profit))
self['profit'] = profit
def update_gui_slider(self):
ticker = self.market.ticker()
latest_price = ticker.get('latest', {}).get('price', None)
if not latest_price:
return
order_ids = None
orders = self.fetch_orders()
if orders:
order_ids = orders.keys()
total_balance = self.total_balance(order_ids)
total = (total_balance['quote'] * latest_price) + total_balance['base']
if not total: # Prevent division by zero
percentage = 50
else:
percentage = (total_balance['base'] / total) * 100
idle_add(self.view.set_worker_slider, self.worker_name, percentage)
self['slider'] = percentage