Skip to content

Commit

Permalink
fix the canceled orders bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
51bitquant committed Sep 4, 2021
1 parent c7103b8 commit ccfb06c
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 20 deletions.
16 changes: 9 additions & 7 deletions gateway/binance_future.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ def request(self, req_method: RequestMethod, path: str, requery_dict=None, verif

for i in range(0, self.try_counts):
try:
response = requests.request(req_method.value, url=url, headers=headers, timeout=self.timeout, proxies=self.proxies)
response = requests.request(req_method.value, url=url, headers=headers, timeout=self.timeout,
proxies=self.proxies)
if response.status_code == 200:
return response.json()
else:
Expand Down Expand Up @@ -211,6 +212,7 @@ def get_kline(self, symbol, interval: Interval, start_time=None, end_time=None,
if isinstance(data, list) and len(data):
return data
return []

def get_latest_price(self, symbol):
path = "/fapi/v1/ticker/price"
query_dict = {"symbol": symbol}
Expand Down Expand Up @@ -299,23 +301,23 @@ def place_order(self, symbol: str, order_side: OrderSide, order_type: OrderType,
# print(params)
return self.request(RequestMethod.POST, path=path, requery_dict=params, verify=True)

def get_order(self, symbol, client_order_id=None):
def get_order(self, symbol, client_order_id: str = ""):
path = "/fapi/v1/order"
query_dict = {"symbol": symbol, "timestamp": self._timestamp()}
params = {"symbol": symbol, "timestamp": self._timestamp()}
if client_order_id:
query_dict["origClientOrderId"] = client_order_id
params["origClientOrderId"] = client_order_id

return self.request(RequestMethod.GET, path, query_dict, verify=True)
return self.request(RequestMethod.GET, path, params, verify=True)

def cancel_order(self, symbol, client_order_id=None):
def cancel_order(self, symbol, client_order_id: str = ""):
path = "/fapi/v1/order"
params = {"symbol": symbol, "timestamp": self._timestamp()}
if client_order_id:
params["origClientOrderId"] = client_order_id

return self.request(RequestMethod.DELETE, path, params, verify=True)

def get_open_orders(self, symbol=None):
def get_open_orders(self, symbol: str = ""):
path = "/fapi/v1/openOrders"

params = {"timestamp": self._timestamp()}
Expand Down
19 changes: 13 additions & 6 deletions gateway/binance_spot.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

"""
币安推荐码: 返佣10%
Expand All @@ -17,7 +16,6 @@
服务器购买地址: https://www.ucloud.cn/site/global.html?invitation_code=C1x2EA81CD79B8C#dongjing
"""


import requests
import time
import hmac
Expand Down Expand Up @@ -88,7 +86,7 @@ def __init__(self, api_key=None, secret=None, host=None, proxy_host=None, proxy_
self.timeout = timeout
self.order_count_lock = Lock()
self.order_count = 1_000_000
self.try_counts = try_counts # 失败尝试的次数.
self.try_counts = try_counts # 失败尝试的次数.
self.proxy_host = proxy_host
self.proxy_port = proxy_port

Expand Down Expand Up @@ -116,7 +114,8 @@ def request(self, req_method: RequestMethod, path: str, requery_dict=None, verif
headers = {"X-MBX-APIKEY": self.api_key}
for i in range(0, self.try_counts):
try:
response = requests.request(req_method.value, url=url, headers=headers, timeout=self.timeout, proxies=self.proxies)
response = requests.request(req_method.value, url=url, headers=headers, timeout=self.timeout,
proxies=self.proxies)
if response.status_code == 200:
return response.json()
else:
Expand Down Expand Up @@ -309,15 +308,23 @@ def place_order(self, symbol: str, order_side: OrderSide, order_type: OrderType,

return self.request(RequestMethod.POST, path=path, requery_dict=params, verify=True)

def get_order(self, symbol: str, client_order_id: str):
def get_order(self, symbol: str, client_order_id: str = ""):
"""
获取订单状态.
:param symbol:
:param client_order_id:
:return:
"""
path = "/api/v3/order"
prams = {"symbol": symbol, "timestamp": self.get_current_timestamp(), "origClientOrderId": client_order_id}
prams = {"symbol": symbol, "timestamp": self.get_current_timestamp()}
if client_order_id:
prams["origClientOrderId"] = client_order_id

return self.request(RequestMethod.GET, path, prams, verify=True)

def get_all_orders(self, symbol:str):
path = "/api/v3/allOrders"
prams = {"symbol": symbol, "timestamp": self.get_current_timestamp()}

return self.request(RequestMethod.GET, path, prams, verify=True)

Expand Down
29 changes: 27 additions & 2 deletions trader/binance_future_trader.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,19 @@ def start(self):
if check_order.get('status') == OrderStatus.CANCELED.value:
delete_buy_orders.append(buy_order)

print(f"{buy_order.get('symbol')}: buy order was canceled, time: {datetime.now()}")
symbol = buy_order.get('symbol')
print(f"{symbol}: buy order was canceled, time: {datetime.now()}")

price = float(check_order.get('price'))
qty = float(check_order.get('executedQty', 0))
min_qty = self.symbols_dict.get(symbol).get('min_qty', 0)

if qty > 0:
self.positions.update(symbol=symbol, trade_price=price, trade_amount=qty, min_qty=min_qty,
is_buy=True)

logging.info(
f"{symbol}: buy order was partially filled, price: {price}, qty: {qty}, time: {datetime.now()}")

elif check_order.get('status') == OrderStatus.FILLED.value:
delete_buy_orders.append(buy_order)
Expand Down Expand Up @@ -142,7 +154,20 @@ def start(self):
if check_order.get('status') == OrderStatus.CANCELED.value:
delete_sell_orders.append(sell_order)

print(f"{sell_order.get('symbol')}: sell order was canceled, time: {datetime.now()}")
symbol = sell_order.get('symbol')
print(f"{symbol}: sell order was canceled, time: {datetime.now()}")

price = float(check_order.get('price'))
qty = float(check_order.get('executedQty', 0))
min_qty = self.symbols_dict.get(symbol).get('min_qty', 0)

if qty > 0:
self.positions.update(symbol=symbol, trade_price=price, trade_amount=qty, min_qty=min_qty,
is_buy=False)

logging.info(
f"{symbol}: sell order was partially filled, price: {price}, qty: {qty}, total_profit: {self.positions.total_profit}, time: {datetime.now()}")

elif check_order.get('status') == OrderStatus.FILLED.value:
delete_sell_orders.append(sell_order)

Expand Down
40 changes: 35 additions & 5 deletions trader/binance_spot_trader.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,12 @@ def get_exchange_info(self):
items = data.get('symbols', [])
for item in items:

symbol = item['symbol']
if symbol.__contains__('UP') or symbol.__contains__('DOWN'):
continue

if item.get('quoteAsset') == 'USDT' and item.get('status') == "TRADING":

symbol = item['symbol']
symbol_data = {"symbol": symbol}
for filters in item['filters']:
if filters['filterType'] == 'PRICE_FILTER':
Expand Down Expand Up @@ -100,7 +103,20 @@ def start(self):
if check_order.get('status') == OrderStatus.CANCELED.value:
delete_buy_orders.append(buy_order)

print(f"{buy_order.get('symbol')}: buy order was canceled, time: {datetime.now()}")
symbol = buy_order.get('symbol')
print(f"{symbol}: buy order was canceled, time: {datetime.now()}")

min_qty = self.symbols_dict.get(symbol).get('min_qty', 0)
price = float(check_order.get('price'))
qty = float(check_order.get('executedQty', 0))

if qty > 0:
self.positions.update(symbol=symbol, trade_price=price, trade_amount=qty, min_qty=min_qty,
is_buy=True)

logging.info(
f"{symbol}: buy order was partially filled, price: {price}, qty: {qty}, time: {datetime.now()}")


elif check_order.get('status') == OrderStatus.FILLED.value:
delete_buy_orders.append(buy_order)
Expand Down Expand Up @@ -140,7 +156,21 @@ def start(self):
if check_order.get('status') == OrderStatus.CANCELED.value:
delete_sell_orders.append(sell_order)

print(f"{sell_order.get('symbol')}: sell order was canceled, time: {datetime.now()}")
symbol = sell_order.get('symbol')
print(f"{symbol}: sell order was canceled, time: {datetime.now()}")

min_qty = self.symbols_dict.get(symbol).get('min_qty', 0)
price = float(check_order.get('price'))
qty = float(check_order.get('executedQty', 0))

if qty > 0:
self.positions.update(symbol=symbol, trade_price=price, trade_amount=qty, min_qty=min_qty,
is_buy=False)

logging.info(
f"{symbol}: sell order was partially filled, price: {price}, qty: {qty}, total_profit: {self.positions.total_profit}, time: {datetime.now()}")


elif check_order.get('status') == OrderStatus.FILLED.value:
delete_sell_orders.append(sell_order)

Expand Down Expand Up @@ -259,7 +289,6 @@ def start(self):
else:
print(f"{s}: bid_price: {bid_price}, ask_price: {bid_price}")


pos_symbols = self.positions.positions.keys() # 有仓位的交易对信息.
pos_count = len(pos_symbols) # 仓位的个数.

Expand Down Expand Up @@ -295,7 +324,8 @@ def start(self):
order_type=OrderType.LIMIT, quantity=qty,
price=bid_price)

print(f"{s} hour change: {signal['pct']}, 4hour change: {signal['pct_4h']}, place buy order: {buy_order}")
print(
f"{s} hour change: {signal['pct']}, 4hour change: {signal['pct_4h']}, place buy order: {buy_order}")
if buy_order:
# resolve buy orders
orders = self.buy_orders_dict.get(s, [])
Expand Down

0 comments on commit ccfb06c

Please sign in to comment.