Ejemplo n.º 1
0
def test_trade():
    quantity = 10
    price = 10
    aggressive_order = Order(1, ORDER_BUY_SIDE, 0, price, 1)
    resting_order = Order(2, ORDER_SELL_SIDE, 1, price, 2)
    trade = Trade(quantity, price, aggressive_order, resting_order)
    assert trade.price == price
    assert trade.quantity == quantity
    assert trade.aggressive_fill == FILL_TYPE_FULL
    assert trade.aggressive_quantity == 0
    assert trade.aggressive_id == 1
    assert trade.resting_fill == FILL_TYPE_PARTIAL
    assert trade.resting_quantity == 1
    assert trade.resting_id == 2
    aggressive_order = Order(1, ORDER_BUY_SIDE, 1, price, 1)
    resting_order = Order(2, ORDER_SELL_SIDE, 0, price, 2)
    trade = Trade(quantity, price, aggressive_order, resting_order)
    assert trade.price == price
    assert trade.quantity == quantity
    assert trade.aggressive_fill == FILL_TYPE_PARTIAL
    assert trade.aggressive_quantity == 1
    assert trade.aggressive_id == 1
    assert trade.resting_fill == FILL_TYPE_FULL
    assert trade.resting_quantity == 0
    assert trade.resting_id == 2
Ejemplo n.º 2
0
    def fetch_trades(self, init_period=False):
        '''
        Function to fetch a list of Trade objects

        Parameter
        ---------
        init_period : bool
                      If true, then the CandleList
                      used for the 'period' class attribute
                      will be initialized. Default: False

        Return
        ------
        list with trades
        '''
        trade_list = []
        args = {}
        for index, row in self.df.iterrows():
            pair = re.split(r'\.| ', row['id'])[0]
            args = {'pair': pair}
            for c in row.keys():
                args[c] = row[c]
            if init_period is True:
                t = Trade(**args, init=True)
            else:
                t = Trade(**args)
            trade_list.append(t)

        return trade_list
Ejemplo n.º 3
0
    def _process_matched_orders(self, new_order: Order,
                                matched_order_node: Tree):
        matched_order = matched_order_node.orders[0]

        # if new_order.qty matches matched_order.qty
        # 1. register expected: trade, new_order(X), matched_order(X)
        # 2. remove matched_order from the book
        # 3. remove the node from the tree if no more orders with same price
        # new_order fully filled nothing else to do
        if new_order.qty == matched_order.qty:
            self._expected_trades.append(
                Trade(matched_order.qty,
                      matched_order.price))  # add expected Trade
            self._expected_x_orders.add(
                new_order.order_id)  # add expected new_order(X)
            self._expected_x_orders.add(
                matched_order.order_id)  # add expected matched_order(X)
            self._orders_by_id.pop(matched_order_node.orders.popleft().order_id
                                   )  # del matched_order from dict and tree
            new_order.qty = 0
            if len(matched_order_node.orders) == 0:
                matched_order_node.remove_me()

        # new_order.qty < matched_order.qty
        # 1. decrease matched_order.qty
        # 2. register expected messages: trade, new_order(X)
        # new_order fully filled nothing else to do
        elif new_order.qty < matched_order.qty:
            matched_order.qty = matched_order.qty - new_order.qty
            self._expected_trades.append(
                Trade(new_order.qty,
                      matched_order.price))  # add expected Trade
            self._expected_x_orders.add(
                new_order.order_id)  # add expected new_order(X)
            new_order.qty = 0

        # new_order.qty > matched_order.qty
        # 1. decrease new_order.qty
        # 2. register expected messages: trade, matched_order(X)
        # 3. remove matched_order from the book
        # 4. remove the node from the tree if no more orders with the same price
        #    otherwise recursive call to try to fill the rest of qty
        else:
            new_order.qty = new_order.qty - matched_order.qty
            self._expected_trades.append(
                Trade(matched_order.qty, matched_order.price))
            self._expected_x_orders.add(
                matched_order.order_id)  # add expected matched_order(X)
            self._orders_by_id.pop(matched_order_node.orders.popleft().order_id
                                   )  # del matched_order from dict and tree
            if len(matched_order_node.orders) == 0:
                matched_order_node.remove_me()
            else:
                self._process_matched_orders(new_order, matched_order_node)
Ejemplo n.º 4
0
def check_stop_loss(trades_list, account):
    """
    Checks if active trades need stop-losses
    """
    for element in trades_list:
        trade = Trade(element['instrument'],
                      element['initialUnits'],
                      i_d=element['id'],
                      price=element['price'],
                      take_profit=element['takeProfitOrder']['price'],
                      account=os.environ['trading_url_' +
                                         account].split('/')[-2],
                      openTime=element['openTime'])
        duration = trade.get_trade_duration()

        if duration >= 3 and 'stopLossOrder' not in element:
            logging.info(f'Trade to set SL:{trade.i_d} [{duration}h]')
            try:
                trade.get_stop_loss()
                stop_loss = trade.stop_loss
                order = Order(trade, account)
                order.set_stop_loss(stop_loss)
                logging.info(f'SL [{stop_loss}] set for trade ({trade.i_d})')
            except Exception as e:
                logging.error(
                    f'No se pudo obtener trade [{trade.i_d}] de la BD ({e})')
Ejemplo n.º 5
0
def run_game():

    # Create deck, hand, tableau.
    deck = Deck()
    hand = Hand(deck)
    tableau = Tableau(tableau_limit)
    trade = Trade()

    game_end = False

    # Main game loop.
    while game_end is False:

        # Choose action.
        # phase = gf.choose_action()

        # Play phases.
        for phase in range(0, 5):
            gf.play_phase(phase, deck, hand, tableau, trade)

        # Check hand limit
        hand.hand_limit(deck)

        # Check for game end.
        game_end = gf.end_check(tableau, scoreboard)

    return scoreboard.get_vp_total(tableau)
Ejemplo n.º 6
0
    def propose_trade(self, player_id, partner, args):
        if args[0] in self.trades:
            return False

        offer_list = args[2:args.index('want')]
        want_list = args[args.index('want') + 1:]

        offer_dict = {}
        want_dict = {}

        for x in range(0, len(offer_list), 2):
            offer_dict[offer_list[x]] = int(offer_list[x + 1])

        for x in range(0, len(want_list), 2):
            want_dict[want_list[x]] = int(want_list[x + 1])

        self.trades[args[0]] = Trade(player_id.id, partner, offer_dict,
                                     want_dict)

        msg = '{0} wants to trade with '.format(
            player_id.mention) + '<@' + str(
                self.trades[args[0]].partner) + '>\n'
        msg = msg + 'Contract: ' + args[0] + '\n'
        msg = msg + 'Offers: ' + str(self.trades[args[0]].offers) + '\n'
        msg = msg + 'Wants: ' + str(self.trades[args[0]].wants)
        return msg
Ejemplo n.º 7
0
 def __init__(self, config, queue, markets, api):
     self.config = config
     self.markets = markets
     self.api = api
     self.best_ask_bid = BestAskBidAdapter(queue, 'spot_trading','weekly','biweekly','3month')
     self.trade_pairs = TradePairs()
     self.trade = Trade(self.api, config, markets)
     self.scheduler = Scheduler(self.config, self.markets)
     self.messages = Messages(self.config.config_data['message_language'])
Ejemplo n.º 8
0
def main():
    """Main function

    Returns:
        0 -- exit status
    """
    trade = Trade()
    trade.run()
    return SUCCESS
Ejemplo n.º 9
0
 def create_trade(self, p1: Player, p2_name: str, card_ids: List[str], wants: List[str]):
     tcs: List[TradingCard] = self.ids_to_tcs(p1, card_ids)
     new_trades: List[Trade] = []
     p2: Player = util.shrink([player for player in self.players if player.name == p2_name])
     if not p2:
         return util.error("Player chosen is not in game")
     new_trades += [Trade(p1, p2, tcs, wants)]
     self.trades += new_trades
     return util.success('Successfully created trade')
Ejemplo n.º 10
0
    def start(self, mode):
        if mode == 'SIM':
            self.trade = TradeSim(self.bitflyer, self.coincheck, self.gmo)
        else:
            self.trade = Trade(self.bitflyer, self.coincheck, self.gmo)

        while True:
            self.tick()
            time.sleep(1)
Ejemplo n.º 11
0
def prepare_trade(tb_obj, type, SL, ic, harea_sel, delta, add_pips):
    '''
    Prepare a Trade object
    and check if it is taken

    Parameters
    ----------
    tb_obj : TradeBot object
    type : str,
            Type of trade. 'short' or 'long'
    SL : float,
        Adjusted (by '__get_trade_type') SL price
    ic : Candle object
        Indecision candle for this trade
    harea_sel : HArea of this trade
        delta : Timedelta object corresponding to
        the time that needs to be increased
    add_pips : Number of pips above/below SL and entry
        price to consider for recalculating
        the SL and entry. Default : None

    Returns
    -------
    Trade object
    '''
    startO = ic.time + delta
    if type == 'short':
        # entry price will be the low of IC
        entry_p = getattr(ic, "low{0}".format(CONFIG.get('general', 'bit')))
        if add_pips is not None:
            SL = round(add_pips2price(tb_obj.pair,
                                      SL, add_pips), 4)
            entry_p = round(substract_pips2price(tb_obj.pair,
                                                 entry_p, add_pips), 4)
    elif type == 'long':
        # entry price will be the high of IC
        entry_p = getattr(ic, "high{0}".format(CONFIG.get('general', 'bit')))
        if add_pips is not None:
            entry_p = add_pips2price(tb_obj.pair,
                                     entry_p, add_pips)
            SL = substract_pips2price(tb_obj.pair,
                                      SL, add_pips)

    startO = ic.time+delta
    t = Trade(
        id='{0}.bot'.format(tb_obj.pair),
        start=startO.strftime('%Y-%m-%d %H:%M:%S'),
        pair=tb_obj.pair,
        timeframe=tb_obj.timeframe,
        type=type,
        entry=entry_p,
        SR=harea_sel.price,
        SL=SL,
        RR=CONFIG.getfloat('trade_bot', 'RR'),
        strat='counter')

    return t
Ejemplo n.º 12
0
 def sell_stock(self, stock, quantity, price, timestamp=None):
     """
     records a sell event for a given stock if no Timestamp is provided it uses the current timestamp
     returns the Trade
     """
     return self._record_trade(
         stock,
         Trade(quantity,
               TRADE_TYPE.SELL,
               price,
               timestamp=(timestamp or dt.now())))
Ejemplo n.º 13
0
 def _create_open_trade(self, fill):
     trade = Trade(symbol=fill.symbol,
                   trade_id=fill.trade_id,
                   entry_time=fill.datetime,
                   entry_price=fill.price,
                   exit_time=None,
                   exit_price=None,
                   quantity=fill.quantity,
                   direction=fill.direction,
                   paper_pnl=None,
                   profit=None)
     return trade
Ejemplo n.º 14
0
def process_trade(message):
    message_id = message.id
    message_channel_id = message.channel_id
    message_sender_id = message.sender_id
    message_date = message.message_date
    message_channel_name = message.channel_name
    message_status = message.status
    message_raw_text = message.raw_text
    logging.info("%s:%s:%s:%s:%s:%s" %
                 (message_id, message_channel_id, message_date,
                  message_channel_name, message_status, message_raw_text))

    raw_text_results = parse_raw_text(message_raw_text)
    #    test = check_if_trade_exists(session, raw_text_results,
    #                                 timeframe=datetime.datetime.now() - datetime.timedelta(hours=1))
    trade = Trade()

    kwargs = {'forex_account_number': forex_account_number, \
              'tp_adjust': spreadmod, \
              'pip_digits': pipdigits, \
              'origin': "TG%s" % message_channel_name, \
              'tg_sender_id': message_sender_id, \
              'tg_message_id': message_id, \
              'tg_date': message_date, \
              'state': "received", \
              'action': raw_text_results['action'], \
              'entry': raw_text_results['entry'], \
              'take_profit_count': raw_text_results['take_profit_count'], \
              'forex_pair': raw_text_results['forex_pair'], \
              'forex_pair_digits': raw_text_results['forex_pair_digits'], \
              'stop_loss1': raw_text_results['stop_loss1'], \
              'take_profit': raw_text_results['take_profit']
              }

    #    trade_wrapper = TradeWrapper(trade, session, lotsize, message_raw_text, **kwargs)
    trade_wrapper = TradeWrapper(trade, lotsize, message_raw_text, **kwargs)
    last_trade_id = trade_wrapper.get_id()

    if trade_wrapper.get_strategy(
    ) == "20_pip_partial_close_rolling_stop_loss":
        group_magic_number = random.randint(10000, 2000000000)
        trade_wrapper.set_mt4_magic_number(group_magic_number)
    if trade_wrapper.get_strategy(
    ) == "take_profit_move_other_trade_stop_loss":
        group_magic_number = random.randint(10000, 2000000000)
        trade_wrapper.set_mt4_magic_number(group_magic_number)

    session = Session()
    session.add(trade)
    session.commit()
    session.close()
    return last_trade_id
Ejemplo n.º 15
0
 def __init__(self, code_list, init_cash, starttime, endtime):
     self.starttime = starttime
     self.endtime = endtime
     self.data_repository = DataRepository.get_instance(code_list, starttime, endtime)
     self.code_list = code_list
     self.init_cash = init_cash
     self.cash = init_cash
     self.limited_cash = init_cash/len(code_list)
     self.position_list = {}
     for code in self.code_list:
         self.position_list[code] = 0
     #存储trade对象
     self.trade = Trade()
Ejemplo n.º 16
0
    def get_trades(self, ticker="BTC-EUR", start_date=None, end_date=None):
        url = "https://api.gdax.com/products/{}/ticker".format(ticker)

        response = requests.get(url)
        json_response = json.loads(response.content)

        ts = time.time()
        timestamp = dt.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

        return Trade(str(json_response['trade_id']), ticker,
                     float(json_response['price']),
                     float(json_response['size']), timestamp,
                     float(json_response['bid']), float(json_response['ask']))
Ejemplo n.º 17
0
    def _build_trading_platform(self):

        """
        + Description: build trading platform.
        + Input:
        -
        + Output:
        -
        """

        self.trading = Trade(self.world, self.portfolio)
        print("\nTrading platform")
        pprint(self.trading)
def test_max_min_rsi(pair, timeframe, id, start, type, SR, SL, TP, entry,
                     avalue):
    t = Trade(id=id,
              start=start,
              pair=pair,
              timeframe=timeframe,
              type=type,
              SR=SR,
              SL=SL,
              TP=TP,
              entry=entry,
              strat='counter_b1')

    assert avalue == get_max_min_rsi(t)
Ejemplo n.º 19
0
    def _build_trading_platform(self):
        """
        + Description: build trading platform.
        + Input:
        -
        + Output:
        -
        """

        self.trading = Trade(self.world, self.oracle, self.assets,
                             self.portfolio, self.request_pile,
                             self.request_flag, Lock())
        print("\nTrading platform")
        pprint(self.trading)
Ejemplo n.º 20
0
    def _enter(self, index, price, long_short, entry_time):
        try:
            dt = self.stock.dates()[index]
        except:
            dt = None

        params = {
            'stock_code': self.stock.code,
            'trade_type': long_short,
            'entry_date': dt,
            'entry_price': price,
            'entry_time': entry_time
        }
        return Trade(params)
Ejemplo n.º 21
0
    def get_all_trades(self):
        conn = self.__connect__()
        c = conn.cursor()
        self.__create_table__(c)
        trades = []

        for data in c.execute('SELECT * FROM trades ORDER BY create_date'):
            trades.append(
                Trade(data[0], data[1], data[2], data[3], data[4], data[5],
                      data[6], data[7], data[8], data[9], data[10], data[11],
                      data[12], data[13], data[14], data[15], data[16]))

        conn.close()
        return trades
Ejemplo n.º 22
0
 def get(self, create_date):
     conn = self.__connect__()
     c = conn.cursor()
     self.__create_table__(c)
     c.execute(f'SELECT * FROM trades WHERE create_date={create_date}')
     data = c.fetchone()
     conn.close()
     if (data == None):
         return None
     else:
         return Trade(data[0], data[1], data[2], data[3], data[4], data[5],
                      data[6], data[7], data[8], data[9], data[10],
                      data[11], data[12], data[13], data[14], data[15],
                      data[16])
Ejemplo n.º 23
0
def refreshTradeSession(balance):
    log = "   ------  NEW TRADE SESSION   ------"
    writeToFile(log, "main")

    #construct a new pool
    pool = Pool.construct(binancecClient)
    log = logPool(pool)
    writeToFile(log, "main")

    #train the missing models in the new pool
    newModels = Train.start(pool, models)
    log = "Added New Models for Symbols: "
    log += logPool(newModels.keys())
    writeToFile(log, "main")

    #stop trading the models that is not in the new pool
    writeToFile("Terminating OUT-DATED symbols...", "main")
    for symbol in models.keys():
        if not (symbol in pool):
            writeToFile("terminating {0}...".format(symbol), "main")
            #terminate the process for this symbol
            processes[symbol].terminate()
            #liquadate any assest for this symbol if we have some
            balance += tradeIntances[symbol].liquidateAssets()
            #remove the symbol from session
            del processes[symbol]
            del tradeIntances[symbol]
            del models[symbol]
            writeToFile("SUCCESS", "main")

    #refresh the instances for newModels
    writeToFile("Creating New Trade Instances...", "main")
    for symbol in newModels.keys():
        writeToFile("creating a Trade instance for {0}...".format(symbol),
                    "main")
        #add symbol to the models
        models[symbol] = newModels[symbol]
        #create a new trade instance
        newTradeInstance = Trade(models[symbol], binancecClient, symbol,
                                 int(balance / len(pool)))
        tradeIntances[symbol] = newTradeInstance
        #create and new process for trade
        processes[symbol] = multiprocessing.Process(
            target=newTradeInstance.start)
        processes[symbol].start()
        writeToFile("SUCCESS for {0}...".format(symbol), "main")

    writeToFile(" -------  NEW SESSION STARTED!! -------", "main")

    return balance
Ejemplo n.º 24
0
def test_get_trend_i(pair, id, timeframe, start, type, SR, SL, TP, entry, trend_i):
    t = Trade(
        id=id,
        start=start,
        pair=pair,
        timeframe=timeframe,
        type=type,
        SR=SR,
        SL=SL,
        TP=TP,
        entry=entry,
        strat='counter_b1')

    assert trend_i == t.trend_i
Ejemplo n.º 25
0
 def get_by_ticker(self, ticker):
     conn = self.__connect__()
     c = conn.cursor()
     self.__create_table__(c)
     c.execute(f"SELECT * FROM trades WHERE ticker='{ticker}'")
     data = c.fetchone()
     conn.close()
     if (data == None):
         return None
     else:
         return Trade(data[0], data[1], data[2], data[3], data[4], data[5],
                      data[6], data[7], data[8], data[9], data[10],
                      data[11], data[12], data[13], data[14], data[15],
                      data[16])
def test_calc_pips_c_trend(pair, id, timeframe, start, type, SR, SL, TP, entry,
                           pips_c_trend, clean_tmp):
    t = Trade(id=id,
              start=start,
              pair=pair,
              timeframe=timeframe,
              type=type,
              SR=SR,
              SL=SL,
              TP=TP,
              entry=entry,
              strat='counter_b1')

    assert pips_c_trend == calc_pips_c_trend(t)
Ejemplo n.º 27
0
def run():
    LOGGER.info('INITIALIZING...')
    bot = Trade(asset_main='BNB', asset_pair='BTC', minimum_order_len_asset_pair=0.0001, minimum_order_len_asset_main=0.1,
                isTest=False, api_key=API_KEY, secret_key=SECRET_KEY, interval_to_work=5, limit_data=202)
    while True:
        LOGGER.info('GETTING CANDLE DATA')
        bot.get_candle_asset_data()
        LOGGER.info('CALCULATING INDICATORS')
        bot.calculate_indicators()
        LOGGER.info('CHECKING TENDENCY')
        bot.check_asset_tendency_lvl_medium()
        LOGGER.info('SAVING INDICATORS')
        bot.save_indicators_data()
        if bot.tendency in ['UP', 'DOWN']:
            if ((bot.tendency == 'DOWN' and bot.asset_main_balance > 0) or
                    (bot.tendency == 'UP' and bot.asset_pair_balance > 0)):
                LOGGER.info('MAKING AN ORDER')
                bot.make_market_order_entry_position()
                # LOGGER.info('CHECKING ORDER STATUS')
                # bot.check_order_made_status()
                if bot.order_made_status in ['FILLED', 'PARTIALLY_FILLED']:
                    LOGGER.info('ORGANIZING ORDER INFO')
                    bot.organize_order_made()
                    LOGGER.info('GETTING OUT OF CURRENT POSITION')
                    bot.get_out_current_position()
                else:
                    LOGGER.info(f'ORDER {bot.order_made_status.upper()}')
                    LOGGER.info(
                        f'TRYING AGAIN IN {bot.interval_to_work} MINUTE(S)')
                    bot.wait_to_run_again()
            else:
                LOGGER.info(f'THE TENDENCY IDENTIFIED IS: {bot.tendency}')
                if bot.tendency == 'DOWN':
                    LOGGER.info(
                        f'BUT YOUR QUANTITY OF {bot.asset_main} IS: {bot.asset_main_balance}')
                else:
                    LOGGER.info(
                        f'BUT YOUR QUANTITY OF {bot.asset_pair} IS: {bot.asset_pair_balance}')

                LOGGER.info(
                    f'BECAUSE OF THAT IT WAS NOT POSSIBLE TO MAKE AN ORDER')
                LOGGER.info(
                    f'TRYING AGAIN IN {bot.interval_to_work} MINUTE(S)')
                bot.wait_to_run_again()
        else:
            bot.bot_status = 'STAND_BY'
            LOGGER.info('NO TENDENCY IDENTIFIED!')
            LOGGER.info(f'TRYING AGAIN IN {bot.interval_to_work} MINUTE(S)')
            bot.wait_to_run_again()
Ejemplo n.º 28
0
def t_object_list(scope="session"):
    '''Returns a list of Trade objects'''

    td = Trade(start="2017-04-10 14:00:00",
               end="2017-04-26 14:00:00",
               entry=0.74960,
               TP=0.75592,
               SL=0.74718,
               SR=0.74784,
               pair="AUD/USD",
               type="long",
               timeframe="H8",
               strat="counter_b1",
               id="AUD_USD 10APR2017H8")
    return [td]
Ejemplo n.º 29
0
	def __init__(self, table_name, candle_table_name):
		self.table_name = table_name
		self.candle_table_name = candle_table_name

		if dbm.exists_table(table_name):
			DBManager.drop_table(table_name)
		self.table = TradeTable(table_name)
		self.table.save()

		candles = CandleTable.get_candle_array(candle_table_name)
		for c in candles:
			p = Trade(dbm, table_name, c.date, 0, 0, Trade.NONE_TYPE)
			p.save()
		dbm = DBManager.get_instance()
		dbm.save_and_close()
def test_get_lasttime(start, type, SR, SL, TP, entry, lasttime):
    """
    Check function get_lasttime
    """
    t = Trade(id='test',
              start=start,
              pair='EUR_AUD',
              timeframe='D',
              type=type,
              SR=SR,
              SL=SL,
              TP=TP,
              entry=entry,
              strat='counter_b1')

    assert get_lasttime(t) == lasttime