Beispiel #1
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()
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)
Beispiel #3
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():
    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():
    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)
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)