コード例 #1
0
ファイル: sms.py プロジェクト: florentchandelier/qtpylib
def _send_trade(trade, numbers, timezone="UTC"):
    global SMS_SERVICE, SMS_CREDENTIALS

    numbers = _ready_to_send(numbers)
    if numbers == False:
        return

    # message template
    arrow      = "▲" if trade['direction'] == "BUY" else "▼"
    order_type = trade['order_type'].replace("MARKET", "MKT").replace("LIMIT", "LMT")

    msg = ""

    trade['direction'] = trade['direction'].replace("BUY", "BOT").replace("SELL", "SLD")

    qty = ""
    if abs(trade['quantity']) > 1:
        qty = str(abs(trade['quantity'])) + "x "

    if trade['action'] == "ENTRY":
        target = round(trade['target'], 2) if trade['target'] > 0 else '-'
        stop   = round(trade['stop'], 2) if trade['stop'] > 0 else '-'

        try:
            trade['entry_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['entry_time'].strftime('%H:%M:%S%z') +"\n"
        except:
            pass
        msg += trade['direction'] +" "+ arrow  +" "+ qty +" "+ trade['symbol']
        msg += " @ "+ str(round(trade['entry_price'], 2)) +" "+ order_type +"\n"
        msg += "TP "+ str(target) +" / SL "+ str(stop) +"\n"

    elif trade['action'] == "EXIT":
        exit_type = trade['exit_reason'].replace("TARGET", "TGT"
            ).replace("STOP", "STP").replace("SIGNAL", order_type)
        pnl_char = "+" if trade['realized_pnl'] > 0 else ""

        try:
            trade['exit_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['exit_time'].strftime('%H:%M:%S%z') +"\n"
        except:
            pass
        msg += trade['direction'] +" "+ arrow  +" "+ qty +" "+ trade['symbol']
        msg += " @ "+ str(round(trade['exit_price'], 2)) +" "+ exit_type +"\n"
        msg += "PL "+ pnl_char + str(trade['realized_pnl']) +" ("+ trade['duration'] +")\n"


    # if UTC remove timezone info
    msg = msg.replace("+0000", " UTC")

    # send sms
    send_text(msg, numbers)
コード例 #2
0
ファイル: broker.py プロジェクト: Sahanduiuc/qtpylib
    def _register_trade(self, order):
        """ constructs trade info from order data """
        if order['id'] in self.orders.recent:
            orderId = order['id']
        else:
            orderId = order['parentId']
        # entry / exit?
        symbol = order["symbol"]
        order_data = self.orders.recent[orderId]
        position = self.get_positions(symbol)['position']

        if position != 0:
            # entry
            order_data['action'] = "ENTRY"
            order_data['position'] = position
            order_data['entry_time'] = tools.datetime_to_timezone(
                order['time'])
            order_data['exit_time'] = None
            order_data['entry_order'] = order_data['order_type']
            order_data['entry_price'] = order['avgFillPrice']
            order_data['exit_price'] = 0
            order_data['exit_reason'] = None

        else:
            order_data['action'] = "EXIT"
            order_data['position'] = 0
            order_data['exit_time'] = tools.datetime_to_timezone(order['time'])
            order_data['exit_price'] = order['avgFillPrice']

            # target / stop?
            if order['id'] == order_data['targetOrderId']:
                order_data['exit_reason'] = "TARGET"
            elif order['id'] == order_data['stopOrderId']:
                order_data['exit_reason'] = "STOP"
            else:
                order_data['exit_reason'] = "SIGNAL"

            # remove from collection
            del self.orders.recent[orderId]

        if order_data is None:
            return None

        # trade identifier
        tradeId = self.strategy.upper() + '_' + symbol.upper()
        tradeId = hashlib.sha1(tradeId.encode()).hexdigest()

        # existing trade?
        if tradeId not in self.active_trades:
            self.active_trades[tradeId] = {
                "strategy": self.strategy,
                "action": order_data['action'],
                "quantity": abs(order_data['position']),
                "position": order_data['position'],
                "symbol": order_data["symbol"].split('_')[0],
                "direction": order_data['direction'],
                "entry_time": None,
                "exit_time": None,
                "duration": "0s",
                "exit_reason": order_data['exit_reason'],
                "order_type": order_data['order_type'],
                "market_price": order_data['price'],
                "target": order_data['target'],
                "stop": order_data['initial_stop'],
                "entry_price": 0,
                "exit_price": order_data['exit_price'],
                "realized_pnl": 0
            }
            if "entry_time" in order_data:
                self.active_trades[tradeId]["entry_time"] = order_data['entry_time']
            if "entry_price" in order_data:
                self.active_trades[tradeId]["entry_price"] = order_data['entry_price']
        else:
            # self.active_trades[tradeId]['direction']   = order_data['direction']
            self.active_trades[tradeId]['action'] = order_data['action']
            self.active_trades[tradeId]['position'] = order_data['position']
            self.active_trades[tradeId]['exit_price'] = order_data['exit_price']
            self.active_trades[tradeId]['exit_reason'] = order_data['exit_reason']
            self.active_trades[tradeId]['exit_time'] = order_data['exit_time']

            # calculate trade duration
            try:
                delta = int((self.active_trades[tradeId]['exit_time'] -
                             self.active_trades[tradeId]['entry_time']).total_seconds())
                days, remainder = divmod(delta, 86400)
                hours, remainder = divmod(remainder, 3600)
                minutes, seconds = divmod(remainder, 60)
                duration = ('%sd %sh %sm %ss' %
                            (days, hours, minutes, seconds))
                self.active_trades[tradeId]['duration'] = duration.replace(
                    "0d ", "").replace("0h ", "").replace("0m ", "")
            except Exception as e:
                pass

            trade = self.active_trades[tradeId]
            if trade['entry_price'] > 0 and trade['position'] == 0:
                if trade['direction'] == "SELL":
                    pnl = trade['entry_price'] - trade['exit_price']
                else:
                    pnl = trade['exit_price'] - trade['entry_price']

                pnl = tools.to_decimal(pnl)
                # print("1)", pnl)
                self.active_trades[tradeId]['realized_pnl'] = pnl

        # print("\n\n-----------------")
        # print(self.active_trades[tradeId])
        # print("-----------------\n\n")

        # get trade
        trade = self.active_trades[tradeId].copy()

        # sms trades
        sms._send_trade(trade, self.sms_numbers, self.timezone)

        # rename trade direction
        trade['direction'] = trade['direction'].replace(
            "BUY", "LONG").replace("SELL", "SHORT")

        # log
        self.log_trade(trade)

        # remove from active trades and add to trade
        if trade['action'] == "EXIT":
            del self.active_trades[tradeId]
            self.trades.append(trade)

        # return trade
        return trade
コード例 #3
0
def _send_trade(trade, numbers, timezone="UTC"):

    numbers = _ready_to_send(numbers)
    if not numbers:
        return

    # decimals to round:
    decimals = max([2, len(str(trade['entry_price']).split('.')[1])])

    # reverse direction for exits
    if trade['action'] == "EXIT":
        trade['direction'] = "BUY" if trade['direction'] == "SELL" else "BUY"

    # message template
    arrow = "▲" if trade['direction'] == "BUY" else "▼"
    order_type = trade['order_type'].replace("MARKET",
                                             "MKT").replace("LIMIT", "LMT")

    msg = ""

    trade['direction'] = trade['direction'].replace("BUY", "BOT").replace(
        "SELL", "SLD")

    qty = ""
    if abs(trade['quantity']) > 1:
        qty = str(abs(trade['quantity'])) + "x "

    if trade['action'] == "ENTRY":
        target = round(trade['target'],
                       decimals) if trade['target'] > 0 else '-'
        stop = round(trade['stop'], decimals) if trade['stop'] > 0 else '-'

        try:
            trade['entry_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['entry_time'].strftime('%H:%M:%S%z') + "\n"
        except Exception as e:
            pass

        msg += trade['direction'] + " " + arrow + \
            " " + qty + " " + trade['symbol']
        msg += " @ " + str(round(trade['entry_price'], decimals))
        msg += " " + order_type + "\n"
        msg += "TP " + str(target) + " / SL " + str(stop) + "\n"

    elif trade['action'] == "EXIT":
        exit_type = trade['exit_reason'].replace("TARGET", "TGT").replace(
            "STOP", "STP").replace("SIGNAL", order_type)
        pnl_char = "+" if trade['realized_pnl'] > 0 else ""

        try:
            trade['exit_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['exit_time'].strftime('%H:%M:%S%z') + "\n"
        except Exception as e:
            pass

        msg += trade['direction'] + " " + arrow + \
            " " + qty + " " + trade['symbol']
        msg += " @ " + str(round(trade['exit_price'], decimals))
        msg += " " + exit_type + "\n"
        msg += "PL " + pnl_char + str(round(trade['realized_pnl'], decimals))
        msg += " (" + trade['duration'] + ")\n"

    # if UTC remove timezone info
    msg = msg.replace("+0000", " UTC")

    # send sms
    send_text(msg, numbers)
コード例 #4
0
ファイル: sms.py プロジェクト: Greenwicher/qtpylib
def _send_trade(trade, numbers, timezone="UTC"):

    numbers = _ready_to_send(numbers)
    if numbers == False:
        return

    # decimals to round:
    decimals = max([2, len(str(trade['entry_price']).split('.')[1])])

    # reverse direction for exits
    if trade['action'] == "EXIT":
        trade['direction'] = "BUY" if trade['direction'] == "SELL" else "BUY"

    # message template
    arrow = "▲" if trade['direction'] == "BUY" else "▼"
    order_type = trade['order_type'].replace(
        "MARKET", "MKT").replace("LIMIT", "LMT")

    msg = ""

    trade['direction'] = trade['direction'].replace(
        "BUY", "BOT").replace("SELL", "SLD")

    qty = ""
    if abs(trade['quantity']) > 1:
        qty = str(abs(trade['quantity'])) + "x "

    if trade['action'] == "ENTRY":
        target = round(trade['target'], decimals) if trade['target'] > 0 else '-'
        stop   = round(trade['stop'], decimals) if trade['stop'] > 0 else '-'

        try:
            trade['entry_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['entry_time'].strftime('%H:%M:%S%z') + "\n"
        except:
            pass

        msg += trade['direction'] + " " + arrow + " " + qty + " " + trade['symbol']
        msg += " @ " + str(round(trade['entry_price'], decimals))
        msg += " " + order_type + "\n"
        msg += "TP " + str(target) + " / SL " + str(stop) + "\n"

    elif trade['action'] == "EXIT":
        exit_type = trade['exit_reason'].replace("TARGET", "TGT"
                                                 ).replace("STOP", "STP").replace("SIGNAL", order_type)
        pnl_char = "+" if trade['realized_pnl'] > 0 else ""

        try:
            trade['exit_time'] = tools.datetime_to_timezone(
                trade['entry_time'], timezone)
            msg += trade['exit_time'].strftime('%H:%M:%S%z') + "\n"
        except:
            pass

        msg += trade['direction'] + " " + arrow + " " + qty + " " + trade['symbol']
        msg += " @ " + str(round(trade['exit_price'], decimals))
        msg += " " + exit_type + "\n"
        msg += "PL " + pnl_char + str(round(trade['realized_pnl'], decimals))
        msg += " (" + trade['duration'] + ")\n"

    # if UTC remove timezone info
    msg = msg.replace("+0000", " UTC")

    # send sms
    send_text(msg, numbers)