-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcopytradesubscribe.py
211 lines (170 loc) · 7.46 KB
/
copytradesubscribe.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
import json
from operator import pos
import pickle
from pydoc_data.topics import topics
import queue
from typing import Dict
from backend.operations.binance_futures import BinanceFuturesOps
import threading
from app import app
from backend.operations.bot import sendMessage
from backend.operations.db import getAllUserConfigs
import redis
from backend.operations.price import convert_usdt_to_base_asset, get_last_price_ticker
from config import Config
from tasks import startPriceStreams
red = redis.from_url(Config.REDIS_URL)
redsub= redis.from_url(Config.REDES_SUB_URL)
bot_token = Config.BOT_TOKEN
Data =[]
def orderDataTemplateProcessor(data:Dict):
orders ={}
position = data["position"]
pair = data["pair"].upper().replace("USDT_", "")
amount =data["position"]["units"]["value"]
volume_per_tp = data["take_profit"]["steps"][0]["volume"]
position_side =data["position"]["type"]
if position_side=="sell":
data["position"]["type"]="buy"
elif position_side =="buy":
data["position"]["type"]="sell"
position_side =data["position"]["type"]
if position_side == "sell":
tp_side = "buy"
if position_side =="buy":
tp_side = "sell"
position_data={
"symbol":pair.upper(),
"side":position["type"].upper(),
"quantity":None,#to be inserted for a specific user while send order
"type":position["order_type"].upper(),
# "type":"MARKET",
"price":position["price"]['value']
}
close_position_data={
"symbol":pair.upper(),
"side":tp_side.upper(),
"quantity":None,#to be inserted for a specific user while send order
"type":'MARKET',
}
#updating position order
orders.update({"position":position_data, 'close_position_data':close_position_data})
take_profits = data["take_profit"]["steps"]
tp_orders =[]
for tp in take_profits:
tp_order={
"symbol":pair,
"side":tp_side.upper() ,
"quantity":None,#to be inserted for a specific user while send order
"type":tp["order_type"].upper(),
"price":tp["price"]["value"],
"reduceOnly":"true"
}
tp_orders.append(tp_order)
orders.update({"take_profit_orders":tp_orders})
#updating stoploss order
stop_loss = data["stop_loss"]
stop_loss_order = {"symbol":pair.upper(),"side":tp_side.upper(), "quantity":None, "type":stop_loss["order_type"].upper(), "price":stop_loss["price"]["value"]}
orders.update({"stop_loss_order":stop_loss_order})
return orders
def tps_n_sls(data, qty):
# placing the takeprofits and stoploss orders
tp_length = len(data["take_profit_orders"])
for tp in range(tp_length):
data['take_profit_orders'][tp]["quantity"]=float(qty)/tp_length
data["stop_loss_order"]["quantity"]=float(qty)
return data
def send_orders(api_key, api_secret, qty, data, telegram_id):
print("quantity", qty)
"""
#Order template
"""
print(data)
trade_symbol= data['position']['symbol']
client = BinanceFuturesOps(api_key=api_key, api_secret=api_secret, trade_symbol=trade_symbol)
data["position"]["quantity"]=float(qty)
print("Data after updating the quantiy", data)
# send the position order
position_params = data["position"]
print("the data, ", position_params)
try:
resp = client.sendOrder(position_params)
print("the response",resp)
position_resp = f"[Binance Futures USDT-M]\n{position_params['symbol']}/USDT placed at {position_params['price']}"
sendMessage(telegram_id, position_resp )
# results = tps_n_sls(data, qty)
results = {"key":api_key, "secret":api_secret,"telegram_id":telegram_id }
return results
except Exception as e:
print("The position Error", str(e))
position_resp=f"[Binance Futures USDT-M]\n{position_params['symbol']}/USDT Order Failed\nError:{str(e)}"
sendMessage(telegram_id, position_resp )
return None
def user_counter():
pass
sub = redsub.pubsub()
sub.subscribe('smart-signals')
for signal_data in sub.listen():
if signal_data is not None and isinstance(signal_data, dict):
try:
order_data = json.loads(signal_data['data'])
data = orderDataTemplateProcessor(order_data) #missing parts in amount, takeprofit amounts and stop loss amounts
symbolredis =data['position']['symbol']
# priceredis = str(data['position']['price'])+"-"+str(data['position']['side'])
priceredis = str(data['position']['price'])
print("price redis key", priceredis)
if signal_data is not False:
with app.app_context():
users = getAllUserConfigs()
if users ==[]:#if no data
pass
else:
threads =[]
# for user in users:
# api_key =user.key
# api_secret=user.secret
# amount=user.amount
# t1 = threading.Thread(target=send_orders, args=(api_key,api_secret,amount, data, user.telegram_id))
# threads.append(t1)
# print("threads:", threads)
# for thread in threads:
# thread.start()
# all_results =[]
# for thread in threads:
# thread.join()
# my_data = my_queue.get()
# all_results.append(my_data)
# print("my_Data",my_data)
# print("Done!")
# print(all_results)
# red.set(str(all_results[0]['position']['price']), pickle.dumps(all_results))
# without threads implementation
# check where is the price of the position from the entry
# last_price = get_last_price_ticker(symbolredis)
# if float(last_price)>=float(data['position']['price']):
# price_state ="ETOP"#above the entry
# else:
# price_state="ELOW"#below the entry
all_results =[]
for user in users:
api_key =user.key
api_secret=user.secret
leverage=20
amount=convert_usdt_to_base_asset(symbolredis, user.amount, leverage)
resp =send_orders(api_key,api_secret,amount, data, user.telegram_id)
if resp is not None:
all_results.append(resp)
print(all_results)
#save the orders to redis and start monitoring the price changes immediately
records = {
"position_close_data":data['close_position_data'],
"users":all_results
}
red.set(str(priceredis), pickle.dumps(records))
# task_instance = startPriceStreams.apply_async(args=(symbolredis, priceredis,price_state))
# print(task_instance)
print("Cache update successifully")
except Exception as e:
print("error found", str(e))
while True:
user_counter()