-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_exit_pairs.py
205 lines (158 loc) · 6.94 KB
/
func_exit_pairs.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
from constants import CLOSE_AT_ZSOCRE_CROSS
from func_utils import format_number
from func_public import get_candles_recent
from func_cointegration import calculate_zscore
from func_private import place_market_order
from func_bot_agent import BotAgent
import pandas as pd
import json
import time
from pprint import pprint
# Close positions
def manage_trade_exits(client):
"""
Manage exiting open positions
Based upon criteria set in constants
"""
# Initialize saving output
save_output = []
# Opening JSON file
try:
open_positions_file = open("bot_agents.json")
open_positions_dict = json.load(open_positions_file)
except:
return "complete"
# Guard: Exit if no open positions in file
if len(open_positions_dict) < 1:
return "complete"
# Get all open positions per trading platform
exchange_pos = client.private.get_positions(status="OPEN")
all_exc_pos = exchange_pos.data["positions"]
markets_live = []
for p in all_exc_pos:
markets_live.append(p["market"])
# Protect API
time.sleep(0.5)
pprint(markets_live)
# Check all saved positions match order record
# Exit trade according to any exit trade rules
for position in open_positions_dict:
# Initialize is_close trigger
is_close = False
# Extract position matching information from file - market 1
position_market_m1 = position["market_1"]
position_size_m1 = position["order_m1_size"]
position_side_m1 = position["order_m1_side"]
# Extract position matching information from file - market 2
position_market_m2 = position["market_2"]
position_size_m2 = position["order_m2_size"]
position_side_m2 = position["order_m2_side"]
# Protect API
time.sleep(0.5)
# Get order info m1 per exchange
order_m1 = client.private.get_order_by_id(position["order_id_m1"])
order_market_m1 = order_m1.data["order"]["market"]
order_size_m1 = order_m1.data["order"]["size"]
order_side_m1 = order_m1.data["order"]["side"]
# Protect API
time.sleep(0.5)
# Get order info m2 per exchange
order_m2 = client.private.get_order_by_id(position["order_id_m2"])
order_market_m2 = order_m2.data["order"]["market"]
order_size_m2 = order_m2.data["order"]["size"]
order_side_m2 = order_m2.data["order"]["side"]
# Perform matching checks
check_m1 = position_market_m1 == order_market_m1 and position_size_m1 == order_size_m1 and position_side_m1 == order_side_m1
check_m2 = position_market_m2 == order_market_m2 and position_size_m2 == order_size_m2 and position_side_m2 == order_side_m2
check_live = position_market_m1 in markets_live and position_market_m2 in markets_live
# Guard: If not all match exit with error
if not check_m1 or not check_m2 or not check_live:
print(f"Warning: Not all open positions match exchange records for {position_market_m1} and {position_market_m2}")
continue
# Get prices
series_1 = get_candles_recent(client, position_market_m1)
time.sleep(0.2)
series_2 = get_candles_recent(client, position_market_m2)
time.sleep(0.2)
# Get markets for reference of tick size
markets = client.public.get_markets().data
# Protect API
time.sleep(0.2)
# Trigger close based on Z-Score
if CLOSE_AT_ZSOCRE_CROSS:
# Initialize z_scores
hedge_ratio = position["hedge_ratio"]
z_score_traded = position["z_score"]
if len(series_1) > 0 and len(series_1) == len(series_2):
spread = series_1 - (hedge_ratio * series_2)
z_score_current = calculate_zscore(spread).values.tolist()[-1]
# Determine trigger
z_score_level_check = abs(z_score_current) >= abs(z_score_traded)
z_score_cross_check = (z_score_current < 0 and z_score_traded > 0) or (z_score_current > 0 and z_score_traded < 0)
# Close trade
if z_score_level_check and z_score_cross_check:
# Initiate close trigger
is_close = True
###
# Add any other close logic here
# Trigger is_close
###
# Close positions if triggered
if is_close:
# Determine side - m1
side_m1 = "SELL"
if position_side_m1 == "SELL":
side_m1 = "BUY"
# Determine side - m2
side_m2 = "SELL"
if position_side_m2 == "SELL":
side_m2 = "BUY"
# Get and format Price
price_m1 = float(series_1[-1])
price_m2 = float(series_2[-1])
accept_price_m1 = price_m1 * 1.05 if side_m1 == "BUY" else price_m1 * 0.95
accept_price_m2 = price_m2 * 1.05 if side_m2 == "BUY" else price_m2 * 0.95
tick_size_m1 = markets["markets"][position_market_m1]["tickSize"]
tick_size_m2 = markets["markets"][position_market_m2]["tickSize"]
accept_price_m1 = format_number(accept_price_m1, tick_size_m1)
accept_price_m2 = format_number(accept_price_m2, tick_size_m2)
# Close positions
try:
# Close position for market
print(">>> Closing market 1 <<<")
print(f"Closing position for {position_market_m1}")
close_order_m1 = place_market_order(
client,
market=position_market_m1,
side=side_m1,
size=position_size_m1,
price=accept_price_m1,
reduce_only=True,
)
print(close_order_m1["order"]["id"])
print(">>> Closing <<< ")
# Protect API
time.sleep(0.2)
# Close position for market
print(">>> Closing market 2 <<<")
print(f"Closing position for {position_market_m2}")
close_order_m2 = place_market_order(
client,
market=position_market_m2,
side=side_m2,
size=position_size_m2,
price=accept_price_m2,
reduce_only=True,
)
print(close_order_m2["order"]["id"])
print(">>> Closing <<< ")
except Exception as e:
print(f"Exit failed for {position_market_m1} with {position_market_m2}")
save_output.append(position)
# Keep record of items and save
else:
save_output.append(position)
# Save remaining items
print(f"{len(save_output)} Items remaining. Saving file...")
with open("bot_agents.json", "w") as f:
json.dump(save_output, f)