Exemple #1
0
    def market_sell_decide_algorithm(self, chart, open_rate, created_time,
                                     current_time):
        created_timestamp = TimeUtil.timestamp_utc(created_time)
        current_timestamp = TimeUtil.timestamp_utc(current_time)
        created_index = chart.convert_unixtime_to_bar_indexlike_value(
            created_timestamp)
        current_index = chart.convert_unixtime_to_bar_indexlike_value(
            current_timestamp)

        if current_index - created_index >= self.close_bar_count_to_hold:
            return True

        return False
Exemple #2
0
    def show_bar():
        chart = updater_and_runner.get_chart()
        last_bar_set = chart.bars_w_starttime[-1]
        last_time = last_bar_set[0]
        last_bar = last_bar_set[1]

        print("%s: (b,e,h,l) = (%f,%f,%f,%f)" % (
            TimeUtil.fromutctimestamp(float(last_time)),
            last_bar.begin, last_bar.end, last_bar.high, last_bar.low))
    def on_message_callback(self):
        now = TimeUtil.now_utc()

        to_save = self.last_saved_time is None or (
            now - self.last_saved_time).total_seconds() >= self.save_span_sec

        if not to_save:
            return

        print("save", now)

        save_oldest_time = now - timedelta(seconds=self.max_save_minutes * 60)
        with self.chart.bars_lock_obj:
            while len(self.chart.bars_w_starttime) > 0:
                starttime = TimeUtil.fromutctimestamp(
                    self.chart.bars_w_starttime[0][0])
                if starttime < save_oldest_time:
                    del self.chart.bars_w_starttime[0]
                else:
                    break

            with open(self.save_file_path, "w") as fw:
                for timestamp, bar in self.chart.bars_w_starttime:
                    date = TimeUtil.fromutctimestamp(timestamp)

                    begin = bar.begin
                    end = bar.end
                    high = bar.high
                    low = bar.low

                    fw.write("%s,%f,%f,%f,%f\n" % (
                        str(date),
                        begin,
                        end,
                        low,
                        high,
                    ))

        self.last_saved_time = now
def preload_chart(chart, file_path, allow_time_gap_in_sec=90):
    loaded_bar = {}
    for line in open(file_path):
        line = line.strip()
        if len(line) == 0: continue

        # DATE,BEGIN,END,LOW,HIGH
        data = line.split(",")

        start_date = dateutil.parser.parse(data[0])
        begin = float(data[1])
        end = float(data[2])
        low = float(data[3])
        high = float(data[4])

        timestamp = TimeUtil.timestamp_utc(start_date)

        loaded_bar[timestamp] = (begin, end, low, high)

    keys = sorted(loaded_bar.keys())

    latest_date = keys[-1]
    if (TimeUtil.now_timestamp_utc() - latest_date) > allow_time_gap_in_sec:
        print("Cannot load preloaded chart due to timegap: ",
              (TimeUtil.now_timestamp_utc() - latest_date))
        return

    one_sec = 1
    for timestamp in keys:
        begin, end, low, high = loaded_bar[timestamp]
        chart.add_new_data(timestamp + one_sec, begin)
        chart.add_new_data(timestamp + one_sec, low)
        chart.add_new_data(timestamp + one_sec, high)
        chart.add_new_data(timestamp + one_sec, end)

    print("Load preloaded chart!!")
    def on_message(self, ws, msg):
        now = TimeUtil.now_timestamp_utc()

        received_data = json.loads(msg)
        #print("msg:"+str(msg))

        if not isinstance(received_data, list):
            print("error: recieved data is not array: " + str(msg))
            return

        if len(received_data) < 5:
            print("error: recieved array length is less than 5: " +
                  str(received_data))
            return

        msg_id = received_data[0]
        pair = received_data[1]
        price = float(received_data[2])
        amount = float(received_data[3])
        trade_type = received_data[4]

        update_only_high_or_low = False
        if self.last_received_id is not None and msg_id < self.last_received_id:
            # this is not clever solution!!!
            #  because old message possibly update (high&low)
            #  but I ignore it. my algorithm cannot handle high & low value
            #print("old message recieved (latest:%d, received:%d)" % (self.last_received_id, msg_id,))
            update_only_high_or_low = True
            return

        if pair != "btc_jpy":
            print("received data is not btc_jpy data: " + str(pair))
            return

        self.last_received_id = max(msg_id, self.last_received_id)

        # update chart
        self.chart.add_new_data(now, price, update_only_high_or_low)

        # callback after update
        if self.callback_on_update is not None:
            self.callback_on_update(0)
 def __init__(self):
     self.outputPath = Constant.GetOutputFolder() + "\\" + TimeUtil.GetCurrentTime()
     self.tempPdf = Constant.GetXlsFolder() + "\\temp.pdf"
     self.jpStr = "JP"
     self.description = "傳道與生活聚會委派通知單-"
     self.jpDescription = "日語-"
def process_status_and_orders(api,
                              chart_updater,
                              target_symbol,
                              position_traders,
                              lots,
                              recursive_called=False):
    global GLOBAL_LOCK_PROCESS_ONE_FRAME
    global GLOBAL_IS_TEST_BOT
    global GLOBAL_STOP_MAKE_POSITION_FILE

    do_not_create_new_order = False
    if GLOBAL_STOP_MAKE_POSITION_FILE is not None:
        do_not_create_new_order = os.path.exists(
            GLOBAL_STOP_MAKE_POSITION_FILE)
        if do_not_create_new_order:
            print("-----creating new order is stopped!!-----")

    immediate_re_update_required = False
    with GLOBAL_LOCK_PROCESS_ONE_FRAME:
        # query current states by api
        print("----------------------")
        print(
            str(datetime.now()) + ", update" +
            (": immediate recursive call" if recursive_called else ""))

        # base currencies (to get margin)
        #WIPWIPWIP: use_target_symbol
        base_currencies = list(
            set(map(lambda x: x.get_base_currency(), position_traders)))
        pairs = list(set(map(lambda x: x.pair, position_traders)))

        try:
            margin, leverage_margin, positions_ret, transactions, orders = update_all_status_by_api(
                api, base_currencies, pairs)

            if margin is None or leverage_margin is None or positions_ret is None or transactions is None or orders is None:
                print("Failed to request")
                return

            print("leverage margin:", leverage_margin)
            print("wallet total margin:", margin)

            if len(positions_ret) > 0:
                print("positions")
                show_info = []
                for x in positions_ret:
                    pos_id = x["id"]
                    new_order_id = None
                    if "new_order" in x and "id" in x["new_order"]:
                        new_order_id = x["new_order"]["id"]
                    show_info.append((pos_id, new_order_id))
                print(show_info)
            if len(orders) > 0:
                print("orders")
                print(orders)

            if GLOBAL_IS_TEST_BOT:
                max_margin_to_test = {}
                max_margin_to_test['jpy'] = 18000
                max_margin_to_test['btc'] = 0.01
                print(
                    "!!!!!!!!!!!!!!!!!!!BOT IS TEST MODE: max_margin_jpy = %f!!!!!!!!!!!!!!!!!!!!!!"
                    % max_margin_to_test['jpy'])
                print(
                    "!!!!!!!!!!!!!!!!!!!BOT IS TEST MODE: max_margin_btc = %f!!!!!!!!!!!!!!!!!!!!!!"
                    % max_margin_to_test['btc'])
                leverage_margin['jpy'] = min(max_margin_to_test['jpy'],
                                             float(leverage_margin['jpy']))
                if 'btc' in leverage_margin:
                    leverage_margin['btc'] = min(max_margin_to_test['btc'],
                                                 float(leverage_margin['btc']))
                if 'jpy' in margin:
                    margin['jpy'] = min(max_margin_to_test['jpy'],
                                        margin['jpy'])
                if 'btc' in margin:
                    margin['btc'] = min(max_margin_to_test['btc'],
                                        margin['btc'])

            # get all trader position values
            all_positioned = {}
            for pos_i, position in enumerate(position_traders):
                currency = position.get_base_currency()
                if currency not in all_positioned:
                    all_positioned[currency] = 0
                all_positioned[currency] += position.get_positioned_price_base(
                )

            # update for each traders
            for pos_i, position in enumerate(position_traders):
                currency = position.get_base_currency()
                # set usable money
                if position.use_leverage:
                    leverage_margin[currency] = float(
                        leverage_margin[currency])
                    position.set_max_total_position_price_base(
                        lots[pos_i] * leverage_margin[currency])
                    position.set_max_free_margin_of_base_currency(
                        lots[pos_i] * leverage_margin[currency])
                else:
                    # margin = all - positioned
                    # => all should be set to set_max_total_position_price_jpy
                    this_margin = margin[currency]
                    possible_total = this_margin + all_positioned[currency]
                    if GLOBAL_IS_TEST_BOT:
                        possible_total = min(possible_total,
                                             max_margin_to_test[currency])
                        #possible_total = 0.1 # dummy
                    total = possible_total * lots[pos_i]
                    position.set_max_total_position_price_base(total)
                    position.set_max_free_margin_of_base_currency(
                        margin[currency + "_free"])

                # update position & order status
                position.update_status(positions_ret, transactions, orders)

            # update close orders
            now_time = TimeUtil.now_utc()
            for position in position_traders:
                chart = chart_updater.get_chart(position.pair)
                print("pair:", position.pair, " chart:", chart)
                position.update_close_orders(chart, now_time)

            # update orders (when recursive calling, status updating and place sell order is objective. not update new orders
            if not recursive_called:
                for position in position_traders:
                    # udpate orders
                    chart = chart_updater.get_chart(position.pair)
                    update_ret = position.update_new_orders(
                        chart, do_not_create_new_order=do_not_create_new_order)
                    if update_ret is True:
                        immediate_re_update_required = True

        except Exception as exp:
            print(
                "Error has occurred!!! Program continues to work but should be fixed!!"
            )
            print(traceback.format_exc())
            print(exp)
            print(exp.args)

    # if immediate update is required, call this method recursively
    if immediate_re_update_required is True and recursive_called is False:
        process_status_and_orders(api,
                                  chart_updater,
                                  target_symbol,
                                  position_traders,
                                  lots,
                                  recursive_called=True)