-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathexchange.py
executable file
·287 lines (235 loc) · 8.7 KB
/
exchange.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
import youengine.settings as settings
from youengine.helpers.helpers import rnd
PRECISION = getattr(settings, "PRECISION", 8)
FEES = getattr(settings, "FEES", dict())
class OpenedTrade:
"""
Open trades main class
"""
def __init__(self, type_, date, price=None, size=None, fee=None):
self.type_ = type_
self.date = date
self.price = price
self.size = size
self.fee = fee
def __str__(self):
return "OpenedTrade: {0} {1} {2:.8f} x {3:.8f} Fee: {4:.8f}".format(
self.date, self.type_, self.price, self.size, self.fee)
class ClosedTrade(OpenedTrade):
"""
Closed trade class
"""
def __init__(self, type_, date, shares, entry, exit, fee):
super().__init__(type_, date)
self.shares = float(shares) # position shares
self.entry = float(entry) # enter price
self.exit = float(exit) # exit price
self.fee = fee # open + close fee
def __str__(self):
return "{0}\n{1}\n{2}\n{3}\n{4}".format(self.type_, self.date,
self.shares, self.entry,
self.exit)
class Position:
"""
Position main class
"""
def __init__(self, number, entry_price, shares, exit_price=0, stop_loss=0):
self.number = number
self.type_ = "None"
self.entry_price = float(entry_price)
self.shares = float(shares)
self.exit_price = float(exit_price)
self.stop_loss = float(stop_loss)
def show(self):
"""
Print position info
:return:
"""
print("No. {0}".format(self.number))
print("Type: {0}".format(self.type_))
print("Entry: {0}".format(self.entry_price))
print("Shares: {0}".format(self.shares))
print("Exit: {0}".format(self.exit_price))
print("Stop: {0}\n".format(self.stop_loss))
def __str__(self):
return "{} {}x{}".format(self.type_, self.shares, self.entry_price)
class LongPosition(Position):
"""
Long position class
"""
def __init__(self, number, entry_price, shares, fee, exit_price=0,
stop_loss=0):
super().__init__(number, entry_price, shares, exit_price, stop_loss)
self.type_ = 'Long'
self.fee = fee
def close(self, percent, current_price):
"""
Decrease shares count by percent and return value of closed shares.
:param percent:
:param current_price:
:return:
"""
shares = self.shares
self.shares *= 1.0 - percent
return shares * percent * current_price
class ShortPosition(Position):
"""
Short position class
"""
def __init__(self, number, entry_price, shares, fee, exit_price=0,
stop_loss=0):
super().__init__(number, entry_price, shares, exit_price, stop_loss)
self.type_ = 'Short'
self.fee = fee
def close(self, percent, current_price):
"""
Decrease shares count by percent and return value of closed shares.
:param percent:
:param current_price:
:return:
"""
entry = self.shares * percent * self.entry_price
exit_ = self.shares * percent * current_price
self.shares *= 1.0 - percent
if entry - exit_ + entry <= 0:
return 0
else:
return entry - exit_ + entry
class Account:
"""
Main account class
Store settings and trades data
"""
fee = FEES
def __init__(self, initial_capital, fee=None):
self.initial_capital = initial_capital
self.buying_power = initial_capital
self.number = 0
self.date = None
self.equity = []
self.positions = []
self.opened_trades = []
self.closed_trades = []
if isinstance(fee, dict):
self.fee = fee
def enter_position(self, type_, entry_capital, entry_price, exit_price=0,
stop_loss=0):
"""
Open position
:param type_:
:param entry_capital:
:param entry_price:
:param exit_price:
:param stop_loss:
:return:
"""
if entry_capital < 0:
raise ValueError("Error: Entry capital must be positive")
elif entry_price < 0:
raise ValueError("Error: Entry price cannot be negative.")
elif self.buying_power < entry_capital:
raise ValueError("Error: Not enough buying power to enter position")
else:
# apply fee to price
price_with_fee = self.apply_fee(entry_price, type_, 'Open')
# round shares and calculate position capital
size = rnd(entry_capital / price_with_fee)
pos_amount = rnd(entry_price * size)
# calculate trading fee for position
trade_fee = rnd(pos_amount * self.fee.get(type_, 0))
# calc buying power
self.buying_power -= pos_amount + trade_fee
if type_ == 'Long':
position = LongPosition(
self.number, entry_price, size, trade_fee, exit_price,
stop_loss)
elif type_ == 'Short':
position = ShortPosition(
self.number, entry_price, size, trade_fee, exit_price,
stop_loss)
else:
raise TypeError("Invalid position type.")
self.positions.append(position)
self.opened_trades.append(
OpenedTrade(type_, self.date, entry_price, size, trade_fee))
self.number += 1
def close_position(self, position, percent, price):
"""
close position
:param position:
:param percent:
:param price:
:return:
"""
# TODO Change order logic to:
# order_percent(asset, percent > 0)
# if >0: check and buy/close if necessary
# if 0: check and close if position exists
if percent > 1 or percent < 0:
raise ValueError(
"Error: Percent must range between 0-1.")
elif price < 0:
raise ValueError("Error: Current price cannot be negative.")
else:
# get trade fee
# FIXME Use type by direction: buy-Long, sell-Short
trade_fee = rnd(
price * position.shares * self.fee.get(position.type_, 0))
self.closed_trades.append(
ClosedTrade(position.type_, self.date,
position.shares * percent,
position.entry_price, price, trade_fee + position.fee))
self.buying_power += position.close(percent, price) - trade_fee
def apply_fee(self, price, type_, direction):
"""
Apply fee to price by position type & transaction direction
Position types:
* Long
* Short
Directions:
* Open : Add fee to Long price, subtract fee from Short price
* Close : Subtract fee from Long price, add fee to Short price
:param price:
:param type_:
:param direction:
:return:
"""
sign = 1 if direction == 'Open' else -1
# change price with fee
fee = self.fee.get(type_, 0)
if type_ == 'Long':
price *= 1 + sign * fee
elif type_ == 'Short':
price *= 1 - sign * fee
# round price
return rnd(price)
def purge_positions(self):
"""
Delete positions without shares?
:return:
"""
# FIXME Fix to remove positions on close
self.positions = [p for p in self.positions if p.shares > 0]
def show_positions(self):
"""
Show open position info
:return:
"""
for p in self.positions:
p.show()
def total_value(self, current_price):
"""
Return total balance with open positions
:param current_price:
:return:
"""
# print(self.buying_power)
# for p in self.positions: print(p) # positions
# for ot in self.opened_trades: print(ot) # open trades
in_pos = sum(
[p.shares * current_price for p in self.positions
if p.type_ == 'Long']) + sum(
[p.shares * (p.entry_price - current_price + p.entry_price)
for p in self.positions
if p.type_ == 'Short'])
return self.buying_power + in_pos