Ejemplo n.º 1
0
def main():
    args = parse_args()
    str_user_id = args.l
    str_password = args.p
    str_u_r_l = args.u
    str_connection = args.c
    str_session_id = args.session
    str_pin = args.pin

    with ForexConnect() as fx:
        try:
            session = fx.login(str_user_id, str_password, str_u_r_l,
                               str_connection, str_session_id, str_pin,
                               primary_session_status_changed)
            print("")
            print("Requesting a token...")
            token = session.token
            print("Token obtained: {0}".format(token))

            with ForexConnect() as fx_secondary:
                print("")
                print("Login using token...")
                fx_secondary.login_with_token(
                    str_user_id, token, str_u_r_l, str_connection,
                    str_session_id, str_pin, secondary_session_status_changed)
                print("")
                print("Logout...")
                fx_secondary.logout()
        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Ejemplo n.º 2
0
def main():
    global delimiter
    global datetime_separator
    global format_decimal_places
    global timezone

    args = parse_args()
    config_file = args.config

    str_password = args.p

    str_user_id, str_url, str_connection, str_session_id, str_pin, delimiter, output_dir, \
        datetime_separator, format_decimal_places, timezone, data = parse_xml(config_file)

    with ForexConnect() as fx:
        try:
            print("Connecting to: user id:"+str_user_id+", url:"+str_url+", Connection:"+str_connection)
            try:
                fx.login(str_user_id, str_password, str_url,
                         str_connection, str_session_id, str_pin,
                         common_samples.session_status_changed)
            except Exception as e:
                print("Exception: " + str(e))
                raise Exception(
                    "Login failed. Invalid parameters")

            lhc = []
            for param in data:
                offer = Common.get_offer(fx, param[0])

                check_params(param[0], param[1], offer)

                tf = ForexConnect.get_timeframe(fx, param[1])
                if not tf:
                    raise Exception(
                        "The timeframe '{0}' is not valid".format(param[1]))

                lhc, nd_array_history = set_init_history(fx, lhc, param[0], param[1], param[2], param[3], 
                                                         str_user_id, str_password, str_url, str_connection)

                time_difference = get_time_difference(timezone)

                save_old_history(param[0], param[2], param[4], nd_array_history, time_difference, datetime_separator)

                print("Old history saved to "+param[2])

            while True:
                time.sleep(60)

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.set_session_status_listener(session_status_changed(fx, None, None, str_user_id, str_password,
                                                                  str_url, str_connection, False))
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Ejemplo n.º 3
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_timeframe = args.timeframe
    quotes_count = args.quotescount
    date_from = args.datefrom
    date_to = args.dateto

    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)

        print("")
        print("Requesting a price history...")
        history = fx.get_history(str_instrument,
                                 str_timeframe,
                                 date_from,
                                 date_to,
                                 quotes_count)
        current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)

        df = pd.DataFrame(history).rename(columns={'BidOpen': 'Open',
                                                   'BidHigh': 'High',
                                                   'BidLow': 'Low',
                                                   'BidClose': 'Close'
                                                   }).drop(columns=['AskOpen',
                                                                    'AskHigh',
                                                                    'AskLow',
                                                                    'AskClose'
                                                                    ]).dropna()

        df = df.dropna()

        print(df)

        df = bbands('Close', df, 2, 3)

        df = adx(df, 5)

        df = macd('Close', df, 3, 4, 5)

        df = ma('Close', df, 3)

        df = rsi('Close', df, 10)

        print(df)

        fx.logout()
Ejemplo n.º 4
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

    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)

            print("")
            print("Accounts:")
            accounts_response_reader = fx.get_table_reader(fx.ACCOUNTS)
            for account in accounts_response_reader:
                print("{0:s}".format(account.account_id))

            print("")
        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
def main():

    with ForexConnect() as fx:
        try:
            fx.login("D261153925",
                     "384",
                     "fxcorporate.com/Hosts.jsp",
                     "Demo",
                     session_status_callback=session_status_changed)

            history = fx.get_history(
                "EUR/USD", "H1",
                datetime.datetime.strptime(
                    "07.01.2019 21:21:21",
                    '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc),
                datetime.datetime.strptime(
                    "07.31.2019 21:21:21",
                    '%m.%d.%Y %H:%M:%S').replace(tzinfo=datetime.timezone.utc))

            print("Date, BidOpen, BidHigh, BidLow, BidClose, Volume")
            for row in history:
                print("{0:s}, {1:,.5f}, {2:,.5f}, {3:,.5f}, {4:,.5f}, {5:d}".
                      format(
                          pd.to_datetime(str(
                              row['Date'])).strftime('%m.%d.%Y %H:%M:%S'),
                          row['BidOpen'], row['BidHigh'], row['BidLow'],
                          row['BidClose'], row['Volume']))

        except Exception as e:
            print("Exception: " + str(e))

        try:
            fx.logout()
        except Exception as e:
            print("Exception: " + str(e))
Ejemplo n.º 6
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_i_d = args.session
    str_pin = args.pin
    date_from = args.datefrom
    date_to = args.dateto

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

            get_reports(fx, date_from, date_to)

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Ejemplo n.º 7
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_i_d = args.session
    str_pin = args.pin
    str_table = args.table

    if str_table != 'orders' and str_table != 'trades':
        str_table = 'trades'

    with ForexConnect() as fx:

        fx.login(str_user_id, str_password, str_url, str_connection,
                 str_session_i_d, str_pin,
                 common_samples.session_status_changed)

        table_manager = fx.table_manager
        account = get_account(table_manager)

        if not account:
            raise Exception("No valid accounts")

        if str_table == "orders":
            print_orders(table_manager, account.account_id)
        else:
            print_trades(table_manager, account.account_id)

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
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_timeframe = args.timeframe
    quotes_count = args.quotescount
    date_from = args.datefrom
    date_to = args.dateto

    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)

            print("")
            print("Requesting a price history...")
            history = fx.get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)
            current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)
           
            date_format = '%m.%d.%Y %H:%M:%S'
            if current_unit == fxcorepy.O2GTimeFrameUnit.TICK:
                print("Date, Bid, Ask")
                print(history.dtype.names)
                for row in history:
                    print("{0:s}, {1:,.5f}, {2:,.5f}".format(
                        pd.to_datetime(str(row['Date'])).strftime(date_format), row['Bid'], row['Ask']))
            else:
                print("Date, BidOpen, BidHigh, BidLow, BidClose, Volume")
                for row in history:
                    print("{0:s}, {1:,.5f}, {2:,.5f}, {3:,.5f}, {4:,.5f}, {5:d}".format(
                        pd.to_datetime(str(row['Date'])).strftime(date_format), row['BidOpen'], row['BidHigh'],
                        row['BidLow'], row['BidClose'], row['Volume']))
        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
def main():
    global str_instrument
    global old_status
    args = parse_args()
    str_user_id = args.l
    str_password = args.p
    str_url = args.u
    str_connection = args.c
    str_session_i_d = args.session
    str_pin = args.pin
    str_instrument = args.i
    status = args.status

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

            offer = get_offer(fx, str_instrument)

            string = 'instrument='+offer.instrument+'; subscription_status='+offer.subscription_status
            old_status = offer.subscription_status
            print(string)

            if status == old_status:
                raise Exception('New status = current status')

            offers_table = fx.get_table(ForexConnect.OFFERS)

            request = fx.create_request({
                fxcorepy.O2GRequestParamsEnum.COMMAND: fxcorepy.Constants.Commands.SET_SUBSCRIPTION_STATUS,
                fxcorepy.O2GRequestParamsEnum.OFFER_ID: offer.offer_id,
                fxcorepy.O2GRequestParamsEnum.SUBSCRIPTION_STATUS: status
            })

            offers_listener = Common.subscribe_table_updates(offers_table, on_change_callback=on_changed())

            try:
                fx.send_request(request)

            except Exception as e:
                common_samples.print_exception(e)
                offers_listener.unsubscribe()
            else:
                sleep(1)
                offers_listener.unsubscribe()

        except Exception as e:
            common_samples.print_exception(e)

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
def main():
    global profit_level
    global loss_level
    global str_account
    global instrument

    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
    profit_level = args.Profit_Level
    loss_level = args.Loss_Level

    if not profit_level and not loss_level:
        print("Profit and/or loss level must be specified")
        return

    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)

        table_manager = fx.table_manager

        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))

        check_trades(fx, table_manager)

        try:
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Ejemplo n.º 11
0
def main():
    with ForexConnect() as fx:
        try:
            #fxcorporate.com/Hosts.jsp
            #http://www.fxcorporate.com/Hosts.jsp
            fx.login(user_id,
                     password,
                     "fxcorporate.com/Hosts.jsp",
                     "demo",
                     session_status_callback=session_status_changed)
            print("Exception: " + str(e))

        # TBD: your ForexConnect API logic here.

        except Exception as e:
            print("Exception: " + str(e))

        try:
            fx.logout()
        except Exception as e:
            print("Exception: " + str(e))
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
Archivo: matplot.py Proyecto: cjj208/tt
        addplot=ap0,
        panel_ratios=(1, 0.3, 0.3, 0.3, 0.3),
        num_panels=5,
        style='binance',
    )

    #mpf.show()


if __name__ == "__main__":

    USER = "******"
    PASS = "******"
    URL = "http://www.fxcorporate.com/Hosts.jsp"
    ENV = "demo"  # or "real"
    fx = ForexConnect()
    fx.login(user_id=USER,
             password=PASS,
             url=URL,
             connection=ENV,
             session_status_callback=status_callback)
    symlist = symbolList = [
        'HKG33',
        'USOil',
        "NAS100",
        'US30',
        'SPX500',
        'UK100',
        'JPN225',
        'XAG/USD',
        'XAU/USD',
Ejemplo n.º 14
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_timeframe = args.timeframe
    quotes_count = args.quotescount
    date_from = args.datefrom
    date_to = args.dateto

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

        timeframe, _ = ForexConnect.parse_timeframe(str_timeframe)
        if not timeframe:
            raise Exception("ResponseListener: time frame is incorrect")
        nd_array = fx.get_history(instrument, str_timeframe, date_from,
                                  date_to, quotes_count)
        df = pd.DataFrame(nd_array).rename(
            columns={
                'BidOpen': 'Open',
                'BidHigh': 'High',
                'BidLow': 'Low',
                'BidClose': 'Close'
            }).drop(columns=['AskOpen', 'AskHigh', 'AskLow', 'AskClose'
                             ]).set_index('Date').dropna()

        y = np.where(df['Close'].shift(-1) > df['Close'], 1, -1)

        df['Open-Close'] = df.Open - df.Close

        df['High-Low'] = df.High - df.Low

        x = df[['Open-Close', 'High-Low']]

        split_percentage = 0.8

        split = int(split_percentage * len(df))

        x_train = x[:split]

        y_train = y[:split]

        x_test = x[split:]

        y_test = y[split:]

        cls = SVC().fit(x_train, y_train)

        accuracy_train = accuracy_score(y_train, cls.predict(x_train))

        accuracy_test = accuracy_score(y_test, cls.predict(x_test))

        print('Train Accuracy:{: .2f}%'.format(accuracy_train * 100))

        print('Test Accuracy:{: .2f}%'.format(accuracy_test * 100))

        fx.logout()
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)
def main():
    args = parse_args()
    user_id = args.l
    password = args.p
    url = args.u
    connection = args.c
    session_id = args.session
    pin = args.pin
    instrument = args.i
    timeframe = args.timeframe
    quotes_count = args.quotescount
    date_from = args.datefrom
    date_to = args.dateto
    prev_bars = args.prevbars
    next_bars = args.nextbars

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

        nd_array = fx.get_history(instrument, timeframe, date_from, date_to,
                                  quotes_count)
        df = pd.DataFrame(nd_array).rename(
            columns={
                'BidOpen': 'Open',
                'BidHigh': 'High',
                'BidLow': 'Low',
                'BidClose': 'Close'
            }).drop(columns=['AskOpen', 'AskHigh', 'AskLow', 'AskClose'
                             ]).set_index('Date').dropna()

        for i in range(1, prev_bars + 1, 1):
            df[str(i)] = df['Close'].shift(i)

        df = df.dropna()

        x = df.drop(['Open', 'Close', 'Volume', 'High', 'Low'], axis=1)

        y = df['Close']

        length = int(len(df))
        t1 = length - next_bars
        t2 = t1 - prev_bars

        # Train dataset

        x_train = x[t2:t1]

        y_train = y[t2:t1]

        # Test dataset

        x_test = x[t1:]

        y_test = y[t1:]

        linear = LinearRegression().fit(x_train, y_train)

        predicted_price = linear.predict(x_test)

        predicted_price = pd.DataFrame(predicted_price,
                                       index=y_test.index,
                                       columns=['price'])

        r2_score = linear.score(x[t1:], y[t1:]) * 100

        res = predicted_price['price']

        print()
        print("Predicted prices:")
        print(list(res))

        print()
        print("Real prices:")
        print(list(y_test))

        print()
        print("Mean squared error: ",
              mean_squared_error(y_test, predicted_price))
        print("Variance score: {0:.2f}".format(r2_score))

        print()

        fx.logout()
Ejemplo n.º 17
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)
Ejemplo n.º 18
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 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_timeframe = args.timeframe
    date_from = args.datefrom
    str_account = args.account
    str_lots = args.lots
    orders_count = args.orderscount
    short_periods = args.shortperiods
    long_periods = args.longperiods
    print("")

    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)

            current_unit, _ = 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")

            live_history = LiveHistory.LiveHistoryCreator(str_timeframe)
            on_bar_added_callback = on_bar_added(fx, str_account,
                                                 str_instrument, str_lots,
                                                 short_periods, long_periods)
            live_history.subscribe(on_bar_added_callback)

            session_status_changed_callback = session_status_changed(
                fx, live_history, str_user_id, str_password, str_url,
                str_connection, True)
            session_status_changed_callback(fx.session,
                                            fx.session.session_status)
            fx.set_session_status_listener(session_status_changed_callback)

            print("Getting history...")
            history = fx.get_history(str_instrument, str_timeframe, date_from)

            print("Updating history...")
            live_history.history = history
            # apply for current history
            on_bar_added_callback(live_history.history)

            print("")
            while order_created_count < orders_count:
                print("")
                print("Waiting 1 minute...")
                time.sleep(60)

            print("")
            print("Orders created: {0}".format(str(order_created_count)))
            print("")

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.set_session_status_listener(
                session_status_changed(fx, None, str_user_id, str_password,
                                       str_url, str_connection, False))
            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)
Ejemplo n.º 21
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)
def main():
    global next_bars
    global difft
    global last_bar

    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
    date_from = args.datefrom
    str_account = args.account
    next_bars = args.nextbars
    print("")

    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)

            current_unit, current_size = ForexConnect.parse_timeframe(
                str_timeframe)
            difft = common_samples.convert_timeframe_to_seconds(
                current_unit, current_size)

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

            live_history = LiveHistory.LiveHistoryCreator(str_timeframe)
            on_bar_added_callback = on_bar_added(fx, str_account,
                                                 str_instrument)
            live_history.subscribe(on_bar_added_callback)

            session_status_changed_callback = session_status_changed(
                fx, live_history, str_user_id, str_password, str_url,
                str_connection, True)
            session_status_changed_callback(fx.session,
                                            fx.session.session_status)
            fx.set_session_status_listener(session_status_changed_callback)

            print("Getting history...")
            history = fx.get_history(str_instrument, str_timeframe, date_from)

            df = pd.DataFrame(history).rename(
                columns={
                    'BidOpen': 'Open',
                    'BidHigh': 'High',
                    'BidLow': 'Low',
                    'BidClose': 'Close'
                }).drop(columns=['AskOpen', 'AskHigh', 'AskLow', 'AskClose'
                                 ]).set_index('Date').dropna()

            y = np.where(df['Close'].shift(-1) > df['Close'], 1, -1)

            for i in range(0, next_bars + 1, 1):
                df['OC' + str(i)] = (df['Close'].shift(i) -
                                     df['Close'].shift(i + 1)) * 100000

            df = df[next_bars + 1:]
            y = y[next_bars + 1:]

            y_train = y

            x_test = df[['OC0']]
            x_test = x_test[len(x_test) - 1:]

            live_history.history = history

            on_bar_added_callback(live_history.history)

            print()
            print('Next ' + str(next_bars) + ' bar prediction: ')

            last_complete_data_frame = live_history.history.tail(1)
            dt = str(last_complete_data_frame.index.values[0])
            dt = parser.parse(dt)
            dt0 = dt

            for i in range(1, next_bars + 1, 1):
                x_train = df[['OC' + str(i)]]

                cls = SVC(gamma='auto').fit(x_train, y_train)

                if cls.predict(x_test)[0] > 0:
                    res = 'Up'
                else:
                    res = 'Dn'
                dt = dt + timedelta(0, difft)
                print(str(dt) + ': ' + res)


#                print(cls.predict(x_test)[0])

            last_bar = dt0

            while True:
                time.sleep(60)

        except Exception as e:
            common_samples.print_exception(e)
        try:
            fx.set_session_status_listener(
                session_status_changed(fx, None, str_user_id, str_password,
                                       str_url, str_connection, False))
            fx.logout()
        except Exception as e:
            common_samples.print_exception(e)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
        'XAU/USD',
        'CHN50',
        'BTC/USD',
        'USDOLLAR',
        'USD/JPY',
    ]
    symbol = "US30"

    USER = "******"
    PASS = "******"
    # PASS = input("password:"******"http://www.fxcorporate.com/Hosts.jsp"
    ENV = "demo"  # or "real"
    dinghook = 'https://oapi.dingtalk.com/robot/send?access_token=0bc405cea1acf99a4de3a084bb9e99f5a19923a8fa5b6dd6eb185f511db67e91'
    fx = ForexConnect()
    fx.login(user_id=USER,
             password=PASS,
             url=URL,
             connection=ENV,
             session_status_callback=status_callback)

    while True:
        call = []
        # if datetime.now().second==59:
        now = ("%s" %
               time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time())))
        for sym in symbolList:
            history = fx.get_history(instrument=sym,
                                     timeframe="m1",
                                     quotes_count=300)
def main():
    args = parse_args()
    user_id = args.l
    password = args.p
    url = args.u
    connection = args.c
    session_id = args.session
    pin = args.pin
    instrument = args.i
    timeframe = args.timeframe
    quotes_count = args.quotescount
    date_from = args.datefrom
    date_to = args.dateto
    period_ma1 = args.PeriodMA1
    period_ma2 = args.PeriodMA2
    period_ma3 = args.PeriodMA3
    train_percent = args.TrainPercent

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

        nd_array = fx.get_history(instrument, timeframe,
                                  date_from, date_to, quotes_count)
        df = pd.DataFrame(nd_array).rename(columns={'BidOpen': 'Open',
                                                    'BidHigh': 'High',
                                                    'BidLow': 'Low',
                                                    'BidClose': 'Close'
                                                    }).drop(columns=['AskOpen',
                                                                     'AskHigh',
                                                                     'AskLow',
                                                                     'AskClose']).set_index('Date').dropna()
        df['S_1'] = df['Close'].rolling(window=period_ma1).mean()

        df['S_2'] = df['Close'].rolling(window=period_ma2).mean()

        df['S_3'] = df['Close'].rolling(window=period_ma3).mean()

        df = df.dropna()

        x = df[['S_1', 'S_2', 'S_3']]

        y = df['Close']

        t = train_percent/100.

        t = int(t * len(df))

        # Train dataset

        x_train = x[:t]

        y_train = y[:t]

        # Test dataset

        x_test = x[t:]

        y_test = y[t:]

        linear = LinearRegression().fit(x_train, y_train)

        predicted_price = linear.predict(x_test)

        print('Coefficients: \n', linear.coef_)

        print("Mean squared error: ", mean_squared_error(y_test, predicted_price))

        r2_score = linear.score(x[t:], y[t:]) * 100

        print("Variance score: {0:.2f}".format(r2_score))

        fx.logout()