def _get_url(self): try: self.listenKey = self.rest.get_listenKey() return self.host + "/" + self.listenKey["listenKey"] except Exception as e: log.info("获取listenkey异常") return self.host
def check_force(self): # bar = np.array(self.bar) # volume = bar[:, 5] # volume=volume.astype(np.float) # log.info(volume) # volume = np.average(volume) # v=1/volume*200 # log.info(v) deltatime = get_cur_timestamp_ms() - self.force_time if (deltatime > self.dt * 1000) and self.force_time > 0: starttime = get_cur_timestamp_ms() - 60000 * 1440 * 30 volume = self.max_volume(starttime) side = BUY v = 0 if self.sell_force > 0: v = self.sell_force / volume * 300 side = BUY elif self.buy_force > 0: v = self.buy_force / volume * 300 side = SELL self.sig = ((1 / (1 + math.exp(-v))) - 0.5) * 2 # log.info(f"当前爆仓sig {self.sig},最近1小时成交量 {volume},强平卖单量 {self.sell_force},强平买单量 {self.buy_force}") price = float(self.data['c']) # log.info(f"当前价格 {price}") if self.sig > 0.85: log.info( f"当前爆仓sig {self.sig},最近1小时成交量 {volume},强平卖单量 {self.sell_force},强平买单量 {self.buy_force}" ) self.open_order(side, price) self.buy_force = 0 self.sell_force = 0 self.force_time = 0 self.force_time = 0
def teste_bar(): ev = EventEngine() ev.start() b = Binance(ev) bar = b.get_bar("BTCUSDT", "15m") log.info(bar.tail()) balance = b.get_balnce()
def _get_positions(self, symbol=None): uri = "/fapi/v1/positionRisk" data = {"timestamp": tools.get_cur_timestamp_ms()} data = self.request("get", uri, body=data, auth=True) position = {} if isinstance(data, list): log.info("is list") for d in data: if float(d['positionAmt']) != 0: p = Position() p.broker = self.name p.symbol = d['symbol'] p.qty = float(d['positionAmt']) if d['positionSide'] == "BOTH": p.direction = Direction.LONG if p.qty > 0 else Direction.SHORT else: p.direction = Direction.LONG if d[ 'positionSide'] == "LONG" else Direction.SHORT p.price = float(d['entryPrice']) p.liquidation_Price = float(d['liquidationPrice']) if p.symbol in position: position[p.symbol].append(p) else: position[p.symbol] = [] position[p.symbol].append(p) # log.info("新增加持仓记录") # log.info(p) self.positions = position else: log.info(f"无效持仓 {data}") if symbol: # log.info(self.positions) # log.info(symbol) return self.positions.get(symbol, [])
def connect(self): if self.ws: return else: self._connect() if self.ws: log.info("WS连接成功")
def __init__(self, engine, setting): super().__init__(engine, setting) self.ev = engine cfg = Config(setting) broker = cfg.broker self.tp = broker.tp self.sl = broker.sl self.qty = broker.qty self.symbol = broker.symbol self.timeframe = broker.timeframe self.data = deque(maxlen=1000) self.bar = deque(maxlen=100) self.broker = BinanceFutures(self.ev, broker.api_key, broker.api_secret) Market("Alert", "BINANCE", self.symbol, self.callback) self.broker.start(self.symbol, [TRADES]) self.register_event() self.price = 0 self.status = True self.lowprice = 0 self.highprice = 0 self.position = [] log.info("HT策略已启动。。。") log.info( f"symbol:{self.symbol},qty:{self.qty},timeframe:{self.timeframe},tp:{self.tp},sl:{self.sl}" ) self.loop()
def open_order(self, side): position = self.broker.get_positions(self.symbol) if len(position) > 0: pos = position[0] if (pos.direction == Direction.LONG and side == SELL) or (pos.direction == Direction.SHORT and side == BUY): o = self.broker.close_position(pos) log.info(f"止损平仓:{o}") time.sleep(0.5) self.position = self.broker.get_positions(self.symbol) if side == BUY: o = self.broker.buy(self.symbol, self.qty) log.info(f"买单:{o}") time.sleep(0.5) self.position = self.broker.get_positions(self.symbol) log.info(f"当前持仓{self.position}") else: o = self.broker.sell(self.symbol, self.qty) log.info(f"卖单:{o}") time.sleep(0.5) self.position = self.broker.get_positions(self.symbol) log.info(f"当前持仓{self.position}")
def publish(self, event): log.info( f"publish exchange:{event.exchange},key:{event.routing_key},data{event.data}" ) data = event.dumps() self._channel.basic_publish(exchange=event.exchange, routing_key=event.routing_key, body=data)
def _reconnect(self, ws): assert ws is not None, '_reconnect should only be called with an existing ws' if ws is self.ws: #todo 2020.05.01重新连接之后需要判断当前的订阅是不是要重新订阅,包括登录状态 log.info("Reconnect...") self.ws = None ws.close() self.connect()
def on_bar(self, event): data = event.data data = data['k'] self.price = float(data['c']) log.info(data) if data['x']: self.bar.append(data) self.check_position()
def _init_depth(self): log.info("初始化深度") res = self.get_order_book(self.symbol) for bid in res['bids']: self.depth.add_bid(bid) for ask in res['asks']: self.depth.add_ask(ask) self.update_orderbook()
def connect(self,proxies=None): self.proxies=proxies if self.ws: return with self.connect_lock: while not self.ws: self._connect() if self.ws: log.info("WS连接成功!") return
def subscribe(self, market_type, platform, symbol, callback): try: self.ev = EventServer() symbol = symbol.replace("-", ".") key = f"{platform}.{symbol}" self.ev.subscribe(market_type, callback, key) log.info(f"{market_type},{key},订阅成功!") except Exception as e: log.error(e) traceback.format_exc()
def _get_url(self): try: if self.rest.API_KEY != None: self.listenKey = self.rest.get_listenKey() return self.host + "/" + self.listenKey["listenKey"] else: return self.host except Exception as e: log.info("获取listenkey异常") return self.host
def _subscribe(self,ch,symbols): if not self.ws: self.connect() if self.ws: for k in ch.keys(): chanels=self.param.get("chanels",None) c = chanels.get(k, "") for symbol in symbols: req=self.get_sub(channel=c,symbol=symbol) log.info(req) self.ws.send_json(req) self.subscribes[k] = ch[k]
def subscribe(self, channels): for k in channels.keys(): c = self.chanels.get(k, "") for symbol in self.symbols: req = { "method": "SUBSCRIBE", "params": [f'{symbol}@{c}'], "id": 1 } log.info(req) self.send_json(req) self.subscribes[k] = channels[k]
def get_account(self): url = self.param['api'].get("account", None) params = None response = self.request("get", url, "info", params=params, auth=True) try: self.groupid = str(response["data"]["accountGroup"]) self.cashAccount = response["data"]["cashAccount"][0] self.marginAccount = response["data"]["marginAccount"][0] log.info("账户验证成功") except Exception as e: log.error(f"账户验证失败 {response}") log.error(e) return response
def callback(self, ch, method, properties, data): e = Event() e.loads(data) data = e.data if data["alert"] == self.alert and data["timeframe"] == self.timeframe: log.info(data) if len(self.data) > 1: ht = self.data[-1]["ht"] newht = data["ht"] if ht > 0 and newht < 0: self.open_order("SELL") if ht < 0 and newht > 0: self.open_order("BUY") self.data.append(data)
def trend_rsi(data,smoothK=3,smoothD=3,lengthRSI=7,lengthStoch=5): """" :return 0:盘整,1:向上,-1:向下 """ k,d=StochRSI(data, smoothK=smoothK, smoothD=smoothD, lengthRSI=lengthRSI, lengthStoch=lengthStoch) l = f"{k[-1]},{d[-1]}" trend=0#趋势盘整 if k[-1] > d[-1] and k[-1] > k[-2] and d[-1] > d[-2]: log.info(f"趋势向上,{l}") trend = 1 # elif k[-1] < d[-1] and k[-1] < k[-2] and d[-1] < d[-2]: log.info(f"趋势向下,{l}") trend = -1 return trend
def move_tp(self, side, close, price): if self.highprice < close: self.highprice = close if self.lowprice > close or self.lowprice == 0: self.lowprice = close if side == Direction.LONG: #高点超过止盈价,收盘价低于止盈价时止盈 if self.highprice > price * (1 + self.tp_per) and close < price * ( 1 + self.tp_per): log.info(f"高点{self.highprice},回调到{close}") return True #高点超过止盈价,回调幅度大于回撤百分比 elif self.highprice > price * (1 + self.tp_per) and ( self.highprice - close) / close > self.move_ratio: log.info( f"高点 {self.highprice},回调 {(self.highprice-close)/close}") return True else: return False else: if self.lowprice < price * (1 - self.sl_per) and close > price * ( 1 - self.tp_per): log.info(f"低点{self.lowprice},回调到{close}") return True elif (close - self.lowprice ) / close > self.move_ratio and self.lowprice < price * ( 1 - self.sl_per): log.info( f"低点 {self.lowprice},回调 {(close-self.lowprice)/close}") return True else: return False
def sell(): ev = EventEngine() ev.start() key = "YdDyZz1sql53yOZF9EDI2oe7H3hLgc8Y" # dongjing secret = "UxPDjJHpUa9oCLCQbwwpZKU7rSfoSL7ngQFcBfmF87nvPQhh3yLvByG8puKzi3io" b = Bitmax(ev, key, secret) sw = b.get_balnce() print(sw) symbol = "SRM/USDT" sw = sw["SRM"] print(sw) aty = float(sw.balance) data = b.sell(symbol, aty, 1.2) log.info(data)
def test_order(): ev = EventEngine() ev.start() # key = "YdDyZz1sql53yOZF9EDI2oe7H3hLgc8Y" # dongjing # secret = "UxPDjJHpUa9oCLCQbwwpZKU7rSfoSL7ngQFcBfmF87nvPQhh3yLvByG8puKzi3io" # key = "kFzuMzo2EmHYseOMXPQxiNXUEt9VBkFQ" # shanghai secret = "gAf9eePa3A5a5BLMoS4Yv3ShPdYgobBpF3LxBrLJY966CINeUQMvYmEoMkLcybUF" b = Bitmax(ev, key, secret) # symbol = "BTMX/USDT" symbol = "FIS/USDT" while get_cur_timestamp_ms() < 1599832721000: time.sleep(1) # data=b.buy("SWINGBY/USDT",20000,0.06) max_price = 1 qty = 2000 status = 0 while status == 0: orderlist = b.get_order_book(symbol) data = orderlist.get("data", None) if data: data = data.get("data", None) data = data.get("asks", []) if len(data) > 0: log.info(data) ask = data[0] price = float(ask[0]) if price < max_price: data = b.buy_ioc(symbol, qty, max_price) print(data) if data.get("code") == 0: log.info("下单成功") sw = b.get_balnce() sw = sw["FIS"] aty = round(float(sw.balance)) data = b.sell(symbol, aty, 1.8) log.info(data) status = 1 else: # pass log.info(data) else: log.info(f"{symbol}-no data") time.sleep(0.5)
def create_order(self, action, symbol, quantity, price=None, order_type=OrderType.LIMIT, reduceOnly=False, tif=None, position_side="BOTH", client_id=None): """Create an order. LIMIT_MAKER are LIMIT orders that will be rejected if they would immediately match and trade as a taker. STOP_LOSS and TAKE_PROFIT will execute a MARKET order when the stopPrice is reached. Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty. Any order with an icebergQty MUST have timeInForce set to GTC. MARKET orders using quantity specifies how much a user wants to buy or sell based on the market price. MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) of the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty. MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty. """ url = self.param['api'].get("order", None) # url = "/fapi/v1/order" data = { "symbol": symbol, "side": action, "type": order_type.name.upper(), "positionSide": position_side, "quantity": quantity, "timestamp": tools.get_cur_timestamp_ms() } if tif != None: data["timeInForce"] = tif.name if reduceOnly: data["reduceOnly"] = reduceOnly if price: data["price"] = price if client_id: data["newClientOrderId"] = client_id # log.info(f"{symbol},{action},{quantity},{price}") log.info(data) return self.request("post", url, body=data, auth=True)
def dsr(data,smoothK=3,smoothD=3,lengthRSI=7,lengthStoch=5): """" :return 1:买入/开多,-1:卖出/开空 """ k,d=StochRSI(data, smoothK=smoothK, smoothD=smoothD, lengthRSI=lengthRSI, lengthStoch=lengthStoch) # log.info(f"4小时k:{k[-1]},d:{d[-1]},15分钟k:{k[-1]},d:{fastd[-1]}") s=f"{k[-1]},{d[-1]}" log.info(s) sign=0 if crossover(k, d) and k[-1] > 20: # msg = f"当前时间:{get_datetime()}\n趋势:向上\n当前价格{list(short)[-1]}\n策略:买入" sign=1 # self.msg.send("日内震荡策略", msg) # self.open_order("Buy") if crossunder(k, d) and k[-1] < 80: sign=-1 # msg = f"当前时间:{get_datetime()}\n趋势:向下\n当前价格{list(short)[-1]}\n策略:卖出" # self.msg.send("日内震荡策略", msg) # self.open_order("Sell") return sign
def check_position(self): while self.status: try: position = self.broker.get_positions(self.symbol) if len(position) > 0: p = position[0] # log.info(p) data = self.data if len(data) > 0: price = float(data["c"]) #止损 if p.direction == Direction.LONG: if price < (p.price * (1 - self.sl_per)): o = self.broker.close_position(p) log.info(f"止损平仓:{o}") self.lowprice = 0 self.highprice = 0 else: if price > (p.price * (1 + self.sl_per)): o = self.broker.close_position(p) log.info(f"止损平仓:{o}") self.lowprice = 0 self.highprice = 0 #止盈 if self.move_tp(p.direction, price, p.price): o = self.broker.close_position(p) self.lowprice = 0 self.highprice = 0 log.info(f"移动止盈:{o}") time.sleep(1) except Exception as e: print(e) time.sleep(1)
def test_order(): ev = EventEngine() key = "qer4Udt2tkbfOihvE5zlINiPgfmuC5hbx1SEQmmow8XXiJqZhyGwtF83VRjuIqXN" secret = "X7UOt9wgYNCgjuLwIKX6Taij6afQTj89mKqG4fsYqufnxqrLI2GsV5kTZ7H7u1TL" b = BinanceFutures(ev, key, secret) # b.start(["BTCUSDT"]) # success,text=b.get_user_account() log.info("开始下单") O = b.buy("BTCUSDT", 0.001) log.info("开始结束。") log.info("获取持仓") pos = b.get_positions("BTCUSDT") log.info("当前持仓") print(pos)
def _get_positions(self, symbol=None): """" [ { "entryPrice": "0.00000", // 开仓均价 "marginType": "isolated", // 逐仓模式或全仓模式 "isAutoAddMargin": "false", "isolatedMargin": "0.00000000", // 逐仓保证金 "leverage": "10", // 当前杠杆倍数 "liquidationPrice": "0", // 参考强平价格 "markPrice": "6679.50671178", // 当前标记价格 "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 "positionAmt": "0.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 "symbol": "BTCUSDT", // 交易对 "unRealizedProfit": "0.00000000", // 持仓未实现盈亏 "positionSide": "BOTH", // 持仓方向 }, { "entryPrice": "6563.66500", // 开仓均价 "marginType": "isolated", // 逐仓模式或全仓模式 "isAutoAddMargin": "false", "isolatedMargin": "15517.54150468", // 逐仓保证金 "leverage": "10", // 当前杠杆倍数 "liquidationPrice": "5930.78", // 参考强平价格 "markPrice": "6679.50671178", // 当前标记价格 "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 "positionAmt": "20.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 "symbol": "BTCUSDT", // 交易对 "unRealizedProfit": "2316.83423560" // 持仓未实现盈亏 "positionSide": "LONG", // 持仓方向 }, { "entryPrice": "0.00000", // 开仓均价 "marginType": "isolated", // 逐仓模式或全仓模式 "isAutoAddMargin": "false", "isolatedMargin": "5413.95799991", // 逐仓保证金 "leverage": "10", // 当前杠杆倍数 "liquidationPrice": "7189.95", // 参考强平价格 "markPrice": "6679.50671178", // 当前标记价格 "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 "positionAmt": "-10.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 "symbol": "BTCUSDT", // 交易对 "unRealizedProfit": "-1156.46711780" // 持仓未实现盈亏 "positionSide": "SHORT", // 持仓方向 } ] """ uri = "/fapi/v1/positionRisk" data = {"timestamp": tools.get_cur_timestamp_ms()} data = self.request("get", uri, body=data, auth=True) position = {} if isinstance(data, list): log.info("is list") for d in data: if float(d['positionAmt']) != 0: p = Position() p.broker = self.name p.symbol = d['symbol'] p.qty = float(d['positionAmt']) if d['positionSide'] == "BOTH": p.direction = Direction.LONG if p.qty > 0 else Direction.SHORT else: p.direction = Direction.LONG if d[ 'positionSide'] == "LONG" else Direction.SHORT p.price = float(d['entryPrice']) p.liquidation_Price = float(d['liquidationPrice']) if p.symbol in position: position[p.symbol].append(p) else: position[p.symbol] = [] position[p.symbol].append(p) # log.info("新增加持仓记录") # log.info(p) self.positions = position else: log.info(f"无效持仓 {data}") if symbol: # log.info(self.positions) # log.info(symbol) return self.positions.get(symbol, [])
def open_order(self, side, price): position = self.broker.get_positions(self.symbol) bar_4h = self.broker.get_bar(self.symbol, "4h") close_4h = bar_4h["close"] t = trend_frsi(close_4h) # log.info(f"当前持仓{position}") if len(position) > 0: pos = position[0] if (pos.direction == Direction.LONG and side == SELL) or (pos.direction == Direction.SHORT and side == BUY): o = self.broker.close_position(pos) log.info(f"止损平仓:{o}") self.lowprice = 0 self.highprice = 0 time.sleep(0.5) else: position = self.broker.get_positions(self.symbol) if len(position) == 0: value = self.broker.get_balnce("USDT") #根据开仓百分比下单 qty = round( float(value.balance) * self.percent / price * 50, self.miniqty) log.info(f"当前账户USDT余额:{value}") if side == BUY: o = self.broker.buy(self.symbol, qty) log.info(f"买单:{o}") time.sleep(0.5) self.position = self.broker.get_positions(self.symbol) log.info(f"当前持仓{self.position }") self.lowprice = 0 self.highprice = 0 msg = f"*******一阳指策略*******\n交易对:BTC合约(币安)\n当前价格:{price}\n操作建议:平空做多" self.msg.send(msg) else: o = self.broker.sell(self.symbol, qty) log.info(f"卖单:{o}") time.sleep(0.5) self.position = self.broker.get_positions(self.symbol) log.info(f"当前持仓{self.position}") self.lowprice = 0 self.highprice = 0 msg = f"*******一阳指策略*******\n交易对:BTC合约(币安)\n当前价格:{price}\n操作建议:平多做空" self.msg.send(msg)
def on_order(self, event): data = event.data log.info(f"订单更新 {data}") self.position = self.broker.get_positions(self.symbol)
from aq.common.logger import log import time if __name__ == "__main__": i = 1 while True: log.info(f"demo {i}") time.sleep(5) i += 1