def _session_status_changed(session, status):
        nonlocal offers_listener
        nonlocal first_call
        nonlocal orders_listener
        if not first_call:
            common_samples.session_status_changed(
                session.trading_session_descriptors, status)
        else:
            first_call = False
        if status == fxcorepy.AO2GSessionStatus.O2GSessionStatus.CONNECTED:
            orders_table = fx.get_table(ForexConnect.ORDERS)
            orders_listener = Common.subscribe_table_updates(
                orders_table, on_add_callback=on_order_added)

            offers = fx.get_table(ForexConnect.OFFERS)
            if live_history is not None:
                on_changed_callback = on_changed(live_history)
                offers_listener = Common.subscribe_table_updates(
                    offers, on_change_callback=on_changed_callback)
        elif status == fxcorepy.AO2GSessionStatus.O2GSessionStatus.DISCONNECTING or \
                status == fxcorepy.AO2GSessionStatus.O2GSessionStatus.RECONNECTING or \
                status == fxcorepy.AO2GSessionStatus.O2GSessionStatus.SESSION_LOST:
            if orders_listener is not None:
                orders_listener.unsubscribe()
                orders_listener = None
            if offers_listener is not None:
                offers_listener.unsubscribe()
                offers_listener = None
        elif status == fxcorepy.AO2GSessionStatus.O2GSessionStatus.DISCONNECTED and reconnect_on_disconnected:
            fx.session.login(str_user_id, str_password, str_url,
                             str_connection)
    def subscribe_events(self):
        orders_table = self._fx.get_table(ForexConnect.ORDERS)
        orders_table_listener = Common.subscribe_table_updates(
            orders_table,
            on_add_callback=self._on_added_orders,
            on_delete_callback=self._on_deleted_orders)
        self._listeners.append(orders_table_listener)

        trades_table = self._fx.get_table(ForexConnect.TRADES)
        trades_table_listener = Common.subscribe_table_updates(
            trades_table, on_add_callback=self._on_added_trades)
        self._listeners.append(trades_table_listener)

        messages_table = self._fx.get_table(ForexConnect.MESSAGES)
        messages_table_listener = Common.subscribe_table_updates(
            messages_table, on_add_callback=self._on_added_messages)
        self._listeners.append(messages_table_listener)

        closed_trades_table = self._fx.get_table(ForexConnect.CLOSED_TRADES)
        closed_trades_table_listener = Common.subscribe_table_updates(
            closed_trades_table, on_add_callback=self._on_added_closed_trades)
        self._listeners.append(closed_trades_table_listener)
Exemple #3
0
def main():
    args = parse_args()
    str_user_i_d = args.l
    str_password = args.p
    str_url = args.u
    str_connection = args.c
    str_session_id = args.session
    str_pin = args.pin
    str_instrument = args.i

    with ForexConnect() as fx:
        try:
            fx.login(str_user_i_d, str_password, str_url, str_connection,
                     str_session_id, str_pin,
                     common_samples.session_status_changed)

            offers = fx.get_table(ForexConnect.OFFERS)
            offers_listener = OffersTableListener(str_instrument)

            table_listener = Common.subscribe_table_updates(
                offers,
                on_change_callback=offers_listener.on_changed,
                on_add_callback=offers_listener.on_added,
                on_delete_callback=offers_listener.on_deleted,
                on_status_change_callback=offers_listener.on_changed)

            offers_listener.print_offers(offers)

            time.sleep(60)

            table_listener.unsubscribe()

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Exemple #4
0
def main():
    args = parse_args()
    user_id = args.l
    password = args.p
    str_url = args.u
    connection = args.c
    session_id = args.session
    pin = args.pin
    instrument = args.i
    str_account = args.account

    with ForexConnect() as fx:
        fx.login(user_id, password, str_url, connection, session_id,
                 pin, common_samples.session_status_changed)

        account = Common.get_account(fx, str_account)

        if not account:
            raise Exception(
                "The account '{0}' is not valid".format(account))
        else:
            str_account = account.account_id
            print("AccountID='{0}'".format(str_account))

        offer = Common.get_offer(fx, instrument)

        if not offer:
            raise Exception(
                "The instrument '{0}' is not valid".format(instrument))

        trade = Common.get_trade(fx, str_account, offer.offer_id)

        if not trade:
            raise Exception("There are no opened positions for instrument '{0}'".format(instrument))

        amount = trade.amount

        buy = fxcorepy.Constants.BUY
        sell = fxcorepy.Constants.SELL

        buy_sell = sell if trade.buy_sell == buy else buy

        request = fx.create_order_request(
            order_type=fxcorepy.Constants.Orders.TRUE_MARKET_CLOSE,
            OFFER_ID=offer.offer_id,
            ACCOUNT_ID=str_account,
            BUY_SELL=buy_sell,
            AMOUNT=amount,
            TRADE_ID=trade.trade_id
        )

        if request is None:
            raise Exception("Cannot create request")

        orders_monitor = OrdersMonitor()
        closed_trades_monitor = ClosedTradesMonitor()

        closed_trades_table = fx.get_table(ForexConnect.CLOSED_TRADES)
        orders_table = fx.get_table(ForexConnect.ORDERS)

        trades_listener = Common.subscribe_table_updates(closed_trades_table,
                                                         on_add_callback=closed_trades_monitor.on_added_closed_trade)
        orders_listener = Common.subscribe_table_updates(orders_table, on_add_callback=orders_monitor.on_added_order,
                                                         on_delete_callback=orders_monitor.on_deleted_order)

        try:
            resp = fx.send_request(request)
            order_id = resp.order_id

        except Exception as e:
            common_samples.print_exception(e)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()

        else:
            # Waiting for an order to appear/delete or timeout (default 30)
            is_success = orders_monitor.wait(30, order_id)

            closed_trade_row = None
            if is_success:
                # Waiting for a closed trade to appear or timeout (default 30)
                closed_trade_row = closed_trades_monitor.wait(30, order_id)

            if closed_trade_row is None:
                print("Response waiting timeout expired.\n")
            else:
                print("For the order: OrderID = {0} the following positions have been closed: ".format(order_id))
                print("Closed Trade ID: {0:s}; Amount: {1:d}; Closed Rate: {2:.5f}".format(closed_trade_row.trade_id,
                                                                                           closed_trade_row.amount,
                                                                                           closed_trade_row.close_rate))
                sleep(1)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
def main():
    args = parse_args()
    user_id = args.l
    password = args.p
    str_url = args.u
    connection = args.c
    session_id = args.session
    pin = args.pin
    instrument = args.i
    buy_sell = args.d
    lots = args.lots
    openhour = args.openhour
    openminute = args.openminute
    str_account = args.account
    event = threading.Event()

    if not openhour:
        print("Open hour must be specified")
        return

    openhm = 60 * openhour + openminute

    with ForexConnect() as fx:
        fx.login(user_id, password, str_url, connection, session_id, pin,
                 common_samples.session_status_changed)

        account = Common.get_account(fx, str_account)

        if not account:
            raise Exception("The account '{0}' is not valid".format(account))
        else:
            str_account = account.account_id
            print("AccountID='{0}'".format(str_account))

        offer = Common.get_offer(fx, instrument)

        if not offer:
            raise Exception(
                "The instrument '{0}' is not valid".format(instrument))

        login_rules = fx.login_rules
        trading_settings_provider = login_rules.trading_settings_provider
        base_unit_size = trading_settings_provider.get_base_unit_size(
            instrument, account)
        amount = base_unit_size * lots
        market_open = fxcorepy.Constants.Orders.TRUE_MARKET_OPEN
        order_id = None

        curtime = datetime.now()
        hm = curtime.hour * 60 + curtime.minute

        print("Waiting...")

        while hm != openhm:
            curtime = datetime.now()
            hm = curtime.hour * 60 + curtime.minute
            time.sleep(1)

        request = fx.create_order_request(order_type=market_open,
                                          ACCOUNT_ID=str_account,
                                          BUY_SELL=buy_sell,
                                          AMOUNT=amount,
                                          SYMBOL=offer.instrument)

        if request is None:
            raise Exception("Cannot create request")

        def on_added_trade(_, __, trade_row):
            if trade_row.open_order_id == order_id:
                print("For the order: OrderID = {0} the following positions\
                        have been opened:".format(order_id))
                print("Trade ID: {0:s}; Amount: {1:d}; Rate: {2:.5f}".format(
                    trade_row.trade_id, trade_row.amount, trade_row.open_rate))
                event.set()

        def on_added_order(_, __, order_row):
            nonlocal order_id
            if order_row.order_id == order_id:
                print("The order has been added. Order ID: {0:s},\
                     Rate: {1:.5f}, Time In Force: {2:s}".format(
                    order_row.order_id, order_row.rate,
                    order_row.time_in_force))

        def on_deleted_order(_, __, row_data):
            nonlocal order_id
            if row_data.order_id == order_id:
                print("The order has been deleted. Order ID: {0}".format(
                    row_data.order_id))

        trades_table = fx.get_table(ForexConnect.TRADES)
        orders_table = fx.get_table(ForexConnect.ORDERS)

        trades_listener = Common.subscribe_table_updates(
            trades_table, on_add_callback=on_added_trade)
        orders_listener = Common.subscribe_table_updates(
            orders_table,
            on_add_callback=on_added_order,
            on_delete_callback=on_deleted_order)

        try:
            resp = fx.send_request(request)
            order_id = resp.order_id

        except Exception as e:
            common_samples.print_exception(e)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()
        else:
            # Waiting for an order to appear or timeout (default 30)
            if not event.wait(30):
                print("Response waiting timeout expired.\n")
            else:
                time.sleep(1)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Exemple #6
0
def main():
    args = parse_args()
    user_id = args.l
    password = args.p
    str_url = args.u
    connection = args.c
    session_id = args.session
    pin = args.pin
    instrument = args.i
    buy_sell = args.d
    lots = args.lots
    str_account = args.account

    with ForexConnect() as fx:
        fx.login(user_id, password, str_url, connection, session_id, pin,
                 common_samples.session_status_changed)

        account = Common.get_account(fx, str_account)

        if not account:
            raise Exception("The account '{0}' is not valid".format(account))
        else:
            str_account = account.account_id
            print("AccountID='{0}'".format(str_account))

        offer = Common.get_offer(fx, instrument)

        if not offer:
            raise Exception(
                "The instrument '{0}' is not valid".format(instrument))

        login_rules = fx.login_rules
        trading_settings_provider = login_rules.trading_settings_provider
        base_unit_size = trading_settings_provider.get_base_unit_size(
            instrument, account)
        amount = base_unit_size * lots
        market_open = fxcorepy.Constants.Orders.TRUE_MARKET_OPEN

        request = fx.create_order_request(order_type=market_open,
                                          ACCOUNT_ID=str_account,
                                          BUY_SELL=buy_sell,
                                          AMOUNT=amount,
                                          SYMBOL=offer.instrument)

        if request is None:
            raise Exception("Cannot create request")

        orders_monitor = OrdersMonitor()
        trades_monitor = TradesMonitor()

        trades_table = fx.get_table(ForexConnect.TRADES)
        orders_table = fx.get_table(ForexConnect.ORDERS)

        trades_listener = Common.subscribe_table_updates(
            trades_table, on_add_callback=trades_monitor.on_added_trade)
        orders_listener = Common.subscribe_table_updates(
            orders_table,
            on_add_callback=orders_monitor.on_added_order,
            on_delete_callback=orders_monitor.on_deleted_order,
            on_change_callback=orders_monitor.on_changed_order)

        try:
            resp = fx.send_request(request)
            order_id = resp.order_id

        except Exception as e:
            common_samples.print_exception(e)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()
        else:
            # Waiting for an order to appear/delete or timeout (default 30)
            is_success = orders_monitor.wait(30, order_id)

            trade_row = None
            if is_success:
                # Waiting for an trade to appear or timeout (default 30)
                trade_row = trades_monitor.wait(30, order_id)

            if trade_row is None:
                print("Response waiting timeout expired.\n")
            else:
                print(
                    "For the order: OrderID = {0} the following positions have been opened:"
                    .format(order_id))
                print("Trade ID: {0:s}; Amount: {1:d}; Rate: {2:.5f}".format(
                    trade_row.trade_id, trade_row.amount, trade_row.open_rate))
                sleep(1)
            trades_listener.unsubscribe()
            orders_listener.unsubscribe()

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Exemple #7
0
def change_trade(fx, trade):
    global str_account
    global instrument
    global stop
    amount = trade.amount
    event = threading.Event()

    offer = Common.get_offer(fx, trade.instrument)

    if not offer:
        raise Exception("The instrument '{0}' is not valid".format(instrument))

    buy = fxcorepy.Constants.BUY
    sell = fxcorepy.Constants.SELL

    buy_sell = sell if trade.buy_sell == buy else buy

    order_id = trade.stop_order_id

    open_price = trade.open_rate
    amount = trade.amount
    pip_size = offer.PointSize
    if trade.buy_sell == buy:
        stopv = open_price - stop * pip_size
    else:
        stopv = open_price + stop * pip_size

    if order_id:
        request = fx.create_order_request(
            order_type=fxcorepy.Constants.Orders.STOP,
            command=fxcorepy.Constants.Commands.EDIT_ORDER,
            OFFER_ID=offer.offer_id,
            ACCOUNT_ID=str_account,
            RATE=stopv,
            TRADE_ID=trade.trade_id,
            ORDER_ID=trade.stop_order_id)
    else:
        request = fx.create_order_request(
            order_type=fxcorepy.Constants.Orders.STOP,
            command=fxcorepy.Constants.Commands.CREATE_ORDER,
            OFFER_ID=offer.offer_id,
            ACCOUNT_ID=str_account,
            BUY_SELL=buy_sell,
            RATE=stopv,
            AMOUNT=amount,
            TRADE_ID=trade.trade_id,
            ORDER_ID=trade.stop_order_id)

    if request is None:
        raise Exception("Cannot create request")

    def on_changed_order(_, __, order_row):
        nonlocal order_id
        if order_row.stop_order_id == order_id:
            print("The order has been changed. Order ID: {0:s}".format(
                order_row.trade_id))

    trades_table = fx.get_table(ForexConnect.TRADES)

    trades_listener = Common.subscribe_table_updates(
        trades_table, on_change_callback=on_changed_order)

    try:
        resp = fx.send_request(request)

    except Exception as e:
        common_samples.print_exception(e)
        trades_listener.unsubscribe()
    else:
        # Waiting for an order to appear or timeout (default 30)
        trades_listener.unsubscribe()
Exemple #8
0
def main():
    args = parse_args()
    str_user_id = args.l
    str_password = args.p
    str_url = args.u
    str_connection = args.c
    str_session_id = args.session
    str_pin = args.pin
    str_old = args.orderid

    with ForexConnect() as fx:
        try:
            fx.login(str_user_id, str_password, str_url, str_connection, str_session_id,
                     str_pin, common_samples.session_status_changed)

            order_id = str_old
            orders_table = fx.get_table(ForexConnect.ORDERS)
            orders = orders_table.get_rows_by_column_value("order_id", order_id)
            order = None
            
            for order_row in orders:
                order = order_row
                break

            if order is None:
                raise Exception("Order {0} not found".format(order_id))

            request = fx.create_request({

                fxcorepy.O2GRequestParamsEnum.COMMAND: fxcorepy.Constants.Commands.DELETE_ORDER,
                fxcorepy.O2GRequestParamsEnum.ACCOUNT_ID: order.account_id,
                fxcorepy.O2GRequestParamsEnum.ORDER_ID: str_old
            })

            orders_monitor = OrdersMonitor()

            orders_table = fx.get_table(ForexConnect.ORDERS)
            orders_listener = Common.subscribe_table_updates(orders_table, on_delete_callback=orders_monitor.on_delete_order)

            try:
                fx.send_request(request)

            except Exception as e:
                common_samples.print_exception(e)
                orders_listener.unsubscribe()
            else:
                # Waiting for an order to delete or timeout (default 30)
                is_deleted = orders_monitor.wait(30, order_id)
                if not is_deleted:
                    print("Response waiting timeout expired.\n")
                else:
                    print("The order has been deleted. Order ID: {0:s}".format(order_row.order_id))
                    sleep(1)
                orders_listener.unsubscribe()

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Exemple #9
0
def main():
    args = parse_args()
    str_user_id = args.l
    str_password = args.p
    str_url = args.u
    str_connection = args.c
    str_session_id = args.session
    str_pin = args.pin
    str_instrument = args.i
    str_buy_sell = args.d
    str_rate = args.r
    str_lots = args.lots
    str_account = args.account

    with ForexConnect() as fx:
        fx.login(str_user_id, str_password, str_url, str_connection,
                 str_session_id, str_pin,
                 common_samples.session_status_changed)

        try:
            account = Common.get_account(fx, str_account)
            if not account:
                raise Exception(
                    "The account '{0}' is not valid".format(str_account))

            else:
                str_account = account.account_id
                print("AccountID='{0}'".format(str_account))

            offer = Common.get_offer(fx, str_instrument)

            if offer is None:
                raise Exception(
                    "The instrument '{0}' is not valid".format(str_instrument))

            login_rules = fx.login_rules

            trading_settings_provider = login_rules.trading_settings_provider

            base_unit_size = trading_settings_provider.get_base_unit_size(
                str_instrument, account)

            amount = base_unit_size * str_lots

            entry = fxcorepy.Constants.Orders.ENTRY

            request = fx.create_order_request(
                order_type=entry,
                OFFER_ID=offer.offer_id,
                ACCOUNT_ID=str_account,
                BUY_SELL=str_buy_sell,
                AMOUNT=amount,
                RATE=str_rate,
            )

            orders_monitor = OrdersMonitor()

            orders_table = fx.get_table(ForexConnect.ORDERS)
            orders_listener = Common.subscribe_table_updates(
                orders_table, on_add_callback=orders_monitor.on_added_order)

            try:
                resp = fx.send_request(request)
                order_id = resp.order_id

            except Exception as e:
                common_samples.print_exception(e)
                orders_listener.unsubscribe()

            else:
                # Waiting for an order to appear or timeout (default 30)
                order_row = orders_monitor.wait(30, order_id)
                if order_row is None:
                    print("Response waiting timeout expired.\n")
                else:
                    print(
                        "The order has been added. OrderID={0:s}, "
                        "Type={1:s}, BuySell={2:s}, Rate={3:.5f}, TimeInForce={4:s}"
                        .format(order_row.order_id, order_row.type,
                                order_row.buy_sell, order_row.rate,
                                order_row.time_in_force))
                    sleep(1)
                orders_listener.unsubscribe()

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
def close_trade(fx, trade):
    global str_account
    global instrument
    amount = trade.amount
    event = threading.Event()

    offer = Common.get_offer(fx, trade.instrument)

    if not offer:
        raise Exception("The instrument '{0}' is not valid".format(instrument))

    buy = fxcorepy.Constants.BUY
    sell = fxcorepy.Constants.SELL

    buy_sell = sell if trade.buy_sell == buy else buy
    order_id = None

    request = fx.create_order_request(
        order_type=fxcorepy.Constants.Orders.TRUE_MARKET_CLOSE,
        OFFER_ID=offer.offer_id,
        ACCOUNT_ID=str_account,
        BUY_SELL=buy_sell,
        AMOUNT=amount,
        TRADE_ID=trade.trade_id)

    if request is None:
        raise Exception("Cannot create request")

    def on_added_closed_trade(_, __, trade_row):
        nonlocal order_id
        if trade_row.close_order_id == order_id:
            print("For the order: OrderID = {0} \
                the following positions have been closed: ".format(order_id))
            print("Closed Trade ID: {0:s}; Amount: {1:d}; \
                Closed Rate: {2:.5f}".format(trade_row.trade_id,
                                             trade_row.amount,
                                             trade_row.close_rate))
            event.set()

    def on_added_order(_, __, order_row):
        nonlocal order_id
        if order_row.order_id == order_id:
            print("The order has been added. Order ID: {0:s}, \
            Rate: {1:.5f}, Time In Force: {2:s}".format(
                order_row.order_id, order_row.rate, order_row.time_in_force))

    def on_deleted_order(_, __, row_data):
        nonlocal order_id
        if row_data.order_id == order_id:
            print("The order has been deleted. Order ID: \
            {0}".format(row_data.order_id))

    closed_trades_table = fx.get_table(ForexConnect.CLOSED_TRADES)
    orders_table = fx.get_table(ForexConnect.ORDERS)

    trades_listener = Common.subscribe_table_updates(
        closed_trades_table, on_add_callback=on_added_closed_trade)
    orders_listener = Common.subscribe_table_updates(
        orders_table,
        on_add_callback=on_added_order,
        on_delete_callback=on_deleted_order)

    try:
        resp = fx.send_request(request)
        order_id = resp.order_id

    except Exception as e:
        common_samples.print_exception(e)
        trades_listener.unsubscribe()
        orders_listener.unsubscribe()
    else:
        # Waiting for an order to appear or timeout (default 30)
        if not event.wait(30):
            print("Response waiting timeout expired.\n")
        else:
            sleep(1)
        trades_listener.unsubscribe()
        orders_listener.unsubscribe()
def main():
    pd.options.display.float_format = '{:,.5f}'.format
    pd.options.display.max_columns = 9
    args = parse_args()
    str_user_id = args.l
    str_password = args.p
    str_url = args.u
    str_connection = args.c
    str_session_id = args.session
    str_pin = args.pin
    str_instrument = args.i
    str_timeframe = args.timeframe
    quotes_count = args.bars
    candle_open_price_mode = parse_candle_open_price_mode(args.o)

    with ForexConnect() as fx:
        if candle_open_price_mode is None:
            raise Exception("Invalid value of the candle open price mode. Possible values are "
                            "'first_tick' or 'prev_close'.")

        fx.login(str_user_id, str_password, str_url,
                 str_connection, str_session_id, str_pin,
                 common_samples.session_status_changed)
        try:
            current_unit, current_size = ForexConnect.parse_timeframe(str_timeframe)

            if current_unit == fxcorepy.O2GTimeFrameUnit.TICK:
                # we can't from candles from the t1 time frame
                raise Exception("Do NOT use t* time frame")

            print("Begins collecting live history before uploading a story")

            live_history_creator = LiveHistoryCreator(str_timeframe, candle_open_price_mode=candle_open_price_mode)
            offers = fx.get_table(ForexConnect.OFFERS)

            table_listener = Common.subscribe_table_updates(offers, on_change_callback=on_changed(live_history_creator))
            print("")
            print("Loading old history...")
            nd_array_history = fx.get_history(str_instrument, str_timeframe, None, None, 1, candle_open_price_mode)
            print("Done")

            print("Apply collected history")
            live_history_creator.history = nd_array_history

            print("Accumulating live history...")
            sleep_times = int(quotes_count *
                              common_samples.convert_timeframe_to_seconds(current_unit, current_size) / 60)
            if sleep_times < quotes_count:
                sleep_times = quotes_count
            for i in range(sleep_times):
                time.sleep(60)
                print("Patience...")
            table_listener.unsubscribe()
            print("Done")
            print("")

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)