def check_position(candle: OHLCV, trade): # Check position status global max_margin_used global pos global pl global plot_sell_index global plot_sell_value global plot_buy_index global plot_buy_value global plot_pl_index global plot_pl_value if pos.status == 'ACTIVE': pos.calc(trade) if not pos.trailing and pos.pl_pct <= -add_percent and abs(pos.amount * pos.base) < margin: pos.add(trade['price'], pos.amount) pos.calc(trade) logging.info('Add ' + str(pos.amount) + '@' + str(trade['price']) + '- base: ' + str(pos.base)) if not pos.trailing and pos.pl_pct <= -stop_pct: pos.close() if not pos.trailing and pos.pl_pct >= trailing_profit_pct: pos.trailing_stop(trailing_stop_pct) if pos.status != "CLOSED" and pos.trailing: pos.trailing_stop(trailing_stop_pct) if pos.status == "CLOSED": if pos.trailing: logging.info('Close position by trailing @ ' + str(trade['price']) + ' @ ' + str(pos.pl_pct)) else: logging.info('Close position by stop-loss @ ' + str(trade['price']) + ' @ ' + str(pos.pl_pct)) if pos.amount > 0: plot_sell_index.append(datetime.fromtimestamp(float(candle.start / 1000))) plot_sell_value.append(candle.close) else: plot_buy_index.append(datetime.fromtimestamp(float(candle.start / 1000))) plot_buy_value.append(candle.close) pl += pos.pl - (pos.fee * 2) plot_pl_index.append(datetime.fromtimestamp(float(candle.start / 1000))) plot_pl_value.append(pl) logging.info('PL: ' + str(pl)) positions.append(pos) if pos.amount * pos.base > max_margin_used: max_margin_used = pos.amount * pos.base pos = Position()
trailing_profit_pct = 2 trailing_stop_pct = 0.2 # Stop loss percent stop_pct = 10 # print(start, end) # Get trades data from db trade_cursor = trades.find({"selector": selector, "time": {"$lte": end, "$gte": start}}).sort([("time", 1)]) # Back testing candle = OHLCV() macd = MACD(macd_short, macd_long) strategy = Extend(min_len=min_length, max_len=max_length, diff=diff) order = None pos = Position() positions = [] last_signal = None pl = 0 max_margin_used = 0 plot_price_index = [] plot_price_value = [] plot_buy_index = [] plot_buy_value = [] plot_sell_index = [] plot_sell_value = [] plot_pl_index = [] plot_pl_value = [] plot_macd_short = [] plot_macd_long = []
def setupPosition(self, pair): return Position(pair)