示例#1
0
文件: live.py 项目: richwu/fxcmminer
    def _fxc_login(self):
        """
        Logs into ForexConnectClient and returns a session. 
        """
        while 1:
            try:
                fxc = fx.ForexConnectClient(s.FX_USER, s.FX_PASS, s.FX_ENVR,
                                            s.URL)
                if fxc.is_connected() == True:
                    break
            except RuntimeError:
                sleep(0.1)

        return fxc
示例#2
0
    def _scouting(self):
        """
        Continuiosly poles FXCM for avaiable offers to trade.
        """
        url = "http://pricehistory.fxcorporate.com/pricearchive/catalog.xml"

        while True:
            try:
                fxc = fx.ForexConnectClient(s.FX_USER, s.FX_PASS, s.FX_ENVR,
                                            s.URL)
                if fxc.is_connected() == True:
                    break
            except RuntimeError:
                pass

        print("Scout started..")

        offers = []
        tracked = []
        fxo = []
        while True:
            fxo = [x for x in fxc.get_offers() if x not in fxo]
            if len(fxo) > len(offers):
                offers = []
                xml = urllib2.urlopen(url).read()
                with open(self.XML_FILE, 'wb') as f:
                    f.write(xml)
                with open(self.XML_FILE, 'r') as f:
                    soup = BeautifulSoup(f.read(), 'lxml-xml')
                    for symbol in soup.find_all('symbol'):
                        if symbol['price-stream'] == 'Default':
                            if symbol['name'] in fxo:
                                offers.append(symbol['name'])

                tracked = [x for x in offers if x not in tracked]

                self._reporting(tracked)

            # TODO : Remove offer from Live tracking

            sleep(0.1)
示例#3
0
"""
An example getting user infomation.
"""
import sys
import forexconnect
import lib.login_manager as lm

username, password, connection = lm.get_login_params()
try:
    client = forexconnect.ForexConnectClient(username, password, connection)
except:
    lm.clear_cache()
    sys.exit()
print "Balance:", client.get_balance()
print "UsedMargin:", client.get_used_margin()
trades = client.get_trades()
for t in trades:
    print t
client.logout()
示例#4
0
    def historical_prices(hist_queue, live_queue, event):
        """
        Contacts the database and retrives the latest date, then continues
        with the historical data mining to the present date
        """
        def collect_data(fxc, instrument, time_frame, dbdate):
            """
            Gets the data
            """      
            time_delta = TimeDelta().get_delta(time_frame)

            to_date = None
            fm_date, to_date = DateRange().get_date_block(
                                           time_delta, dbdate, to_date)
            log(instrument).debug("[>>] Starting Block   : %s %s %s %s" % \
                                (instrument, str(fm_date), str(to_date), time_frame))
            breakout = 0
            while True:
                breakdate = datetime.datetime.now() # - datetime.timedelta(minutes = 5)
                if to_date >= breakdate or fm_date >= breakdate:
                    breakout = 1
                    d = datetime.datetime.now()
                    to_date = d.replace(second=00, microsecond=00)

                try:
                    data = fxc.get_historical_prices(
                        str(instrument), fm_date,
                        to_date, str(time_frame)) 
                    data = [d.__getstate__()[0] for d in data]
                    data = [x for x in data if dbdate not in x.values()]

                except (KeyError, IndexError):
                    data = []

                if data != []:
                    hist_queue.put(HistDataEvent(
                        data, instrument, time_frame))

                    log(instrument).debug("[:)] Data Collected   : %s %s %s %s" % \
                        (instrument, str(fm_date), str(to_date), time_frame))
                    fm_date, to_date = DateRange().get_date_block(
                                       time_delta, fm_date, to_date)

                else:
                    log(instrument).debug("[??] Skipping Block   : %s %s %s %s" % \
                                (instrument, str(fm_date), str(to_date), time_frame))
                    fm_date, to_date = DateRange().get_date_block(
                                       time_delta, fm_date, to_date)

                del data
                
                if breakout == 1:
                    break

        fxoffer = event.fxoffer

        while True:
            try:
                fxc = fx.ForexConnectClient(s.FX_USER, s.FX_PASS,
                                            s.FX_ENVR, s.URL
                )
                if fxc.is_connected() == True:
                    break
            except RuntimeError:
                pass

        for offer, time_frames in fxoffer.iteritems():
            for time_frame in time_frames:
                dbdate = DatabaseManager().return_date(offer, time_frame)
                collect_data(fxc, offer, time_frame, dbdate)
                log(offer).debug("[^^] TFrame Complete  : %s |%s|" % (offer, time_frame))

            log(offer).debug("[<>] Offer Complete   : %s |%s|" % (offer, time_frame))
        print("[^^] Hist complete : %s" % offer)
        live_queue.put(LiveReadyEvent(offer))
示例#5
0
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import forexconnect as fc
import settings

# Clients
fxcm            = fc.ForexConnectClient(
                    settings.FXCM_USERNAME,
                    settings.FXCM_PASSWORD,
                    settings.FXCM_ACCOUNT
                    )

# conn        = psql.connect(database=pg_database, user=pg_username, password=pg_password, host=pg_host, port=pg_port)

def get_chart(currency_pair):
    # Get the last days worth of tick data, fit to pandas dataframe, resample to size
    now         = datetime.now()
    then        = now - datetime.timedelta(days = 1)
    data        = client.get_historical_prices(currency_pair, then, now)
    attributes  = ['date', 'open', 'high', 'low', 'close']
    dataframe   = pd.DataFrame([[getattr(i, j) for j in attributes] for i in data], columns = attributes)

    print(dataframe.to_string())

    dataframe.resample('10Min').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'})

    # Resample the chart to timeframe, the idea is last time period should be at the beginning and newest at the end
    # This way we can check MACD at beginning is different to end MACD
    # Augment the chart by adding a column for MACD position, and other indicators I guess
    # Figure out if the MACD at the beginning is different to the MACD at the end of the timetrame