Exemple #1
0
    def __init__(self, conf_file):
        ''' oanda.cfg:
        [oanda]
        account_id = ...
        access_token = ...
        account_type = practice (default) or live
      
        '''
        
        self.config = configparser.ConfigParser()
        self.config.read(conf_file)
        self.access_token = self.config['oanda']['access_token']
        self.account_id = self.config['oanda']['account_id']
        self.account_type = self.config['oanda']['account_type']

        if self.account_type == 'live':
            self.hostname = 'api-fxtrade.oanda.com'
            self.stream_hostname = 'stream-fxtrade.oanda.com'
        else:
            self.hostname = 'api-fxpractice.oanda.com'
            self.stream_hostname = 'stream-fxpractice.oanda.com'

        self.ctx = v20.Context(
            hostname=self.hostname,
            port=443,
            token=self.access_token,
        )
        self.ctx_stream = v20.Context(
            hostname=self.stream_hostname,
            port=443,
            token=self.access_token,
        )

        self.suffix = '.000000000Z'
        self.stop_stream = False
 def __init__(self, instrument, interval, SMA1, SMA2, units,
              *args, **kwargs):
     self.ticks = 0
     self.position = 0
     self.data = pd.DataFrame()
     self.instrument = instrument
     self.interval = interval
     self.SMA1 = SMA1
     self.SMA2 = SMA2
     self.units = units
     self.account_id = config['oanda']['account_id']
     self.ctx = v20.Context(
         'api-fxpractice.oanda.com',
         443,
         True,
         application='sample_code',
         token=config['oanda']['access_token'],
         datetime_format='RFC3339'
     )
     self.ctx_stream = v20.Context(
         'stream-fxpractice.oanda.com',
         443,
         True,
         application='sample_code',
         token=config['oanda']['access_token'],
         datetime_format='RFC3339'
     )
    def __init__(self, conf_file):
        ''' Init function expecting a configuration file with
        the following content:

        [oanda_v20]
        account_id = XYZ-ABC-...
        access_token = ZYXCAB...

        Parameters
        ==========
        conf_file: string
            path to and filename of the configuration file, e.g. '/home/me/oanda.cfg'
        '''
        self.config = configparser.ConfigParser()
        self.config.read(conf_file)
        self.access_token = self.config['oanda_v20']['access_token']
        self.account_id = self.config['oanda_v20']['account_id']
        self.ctx = v20.Context(hostname='api-fxpractice.oanda.com',
                               port=443,
                               ssl=True,
                               application='sample_code',
                               token=self.access_token,
                               datetime_format='RFC3339')
        self.ctx_stream = v20.Context(hostname='stream-fxpractice.oanda.com',
                                      port=443,
                                      ssl=True,
                                      application='sample_code',
                                      token=self.access_token,
                                      datetime_format='RFC3339')
        self.suffix = '.000000000Z'
    def __init__(self, accountid, token, is_live=False):
        if is_live:
            host = self.LIVE_API_HOST
            stream_host = self.LIVE_STREAM_HOST
        else:
            host = self.PRACTICE_API_HOST
            stream_host = self.PRACTICE_STREAM_HOST

        super(OandaBroker, self).__init__(host, self.PORT)

        self.accountid = accountid
        self.token = token

        self.api = v20.Context(host, self.port, token=token)
        self.stream_api = v20.Context(stream_host, self.port, token=token)
    def __init__(self, accountid, token, is_live=False):
        if is_live:
            host = self.live_api_host
            stream_host = self.live_stream_host
        else:
            host = self.practice_api_host
            stream_host = self.practice_stream_host

        super(OandaBroker, self).__init__(host, self.port)

        self.accountid = accountid
        self.token = token

        self.api = v20.Context(host, self.port, token=token)
        self.stream_api = v20.Context(stream_host, self.port, token=token)
Exemple #6
0
    def run(self):

        # Create streaming api context
        api = v20.Context(hostname=self.v20config.streaming_hostname,
                          port=self.v20config.port,
                          token=self.v20config.token,
                          datetime_format=self.v20config.datetime_format)

        # Squash instrument list into a csv string
        instrument_str_list = ",".join(self.instrument_arrays.keys())

        # Prepare stream
        stream = api.pricing.stream(self.v20config.active_account,
                                    instruments=instrument_str_list).parts()

        # Keep looping until the kill event is set
        while not self.kill_event.is_set():

            # Pump the stream generator
            data = next(stream)[1]

            # Check if the data is a Price object
            if isinstance(data, Price):

                for field in self.instrument_arrays[data.instrument].keys():
                    self.instrument_arrays[data.instrument][field].push(
                        getattr(data, field), float(data.time))

            # Sleep so we don't overload the api (broker api has rate limiting)
            time.sleep(0.25)
 def __init__(self, confname):
     config = configparser.ConfigParser()
     config.read(confname)
     self.settings = {}
     self.settings['domain'] = config.get('demo', 'streaming_hostname')
     self.settings['access_token'] = config.get('demo', 'token')
     self.settings['account_id'] = config.get('demo', 'active_account')
     self.settings['v20_host'] = config.get('demo', 'hostname')
     self.settings['v20_port'] = config.get('demo', 'port')
     self.oanda = v20.Context(self.settings.get('v20_host'),
                              port=self.settings.get('v20_port'),
                              token=self.settings.get('access_token'))
     self.allowed_ins = \
         self.oanda.account.instruments(self.settings.get('account_id'
             )).get('instruments', '200')
     self.trades = \
         self.oanda.trade.list_open(self.settings.get('account_id'
             )).get('trades', '200')
     self.dataObj = {
         #'uk10y': { 'name': 'UK10YB_GBP' },
         #'us10y': { 'name':  'USB10Y_USD'},
         #'uk100': { 'name':  'UK100GBP'},
         #'us30': { 'name': 'US30_USD'},
         #'gu': { 'name': 'GBP_USD'}
         'wheat': {
             'name': 'WHEAT_USD'
         },
         'corn': {
             'name': 'CORN_USD'
         },
         'sugar': {
             'name': 'SUGAR_USD'
         }
     }
    def get_current_data(self, currency_pair, candle_types,
                         time_frame_granularity):
        # Create the Oanda API context
        api_context = v20.Context(Config.get_host_name(),
                                  Config.get_port(),
                                  Config.get_ssl(),
                                  application="sample_code",
                                  token=Config.get_api_token(),
                                  datetime_format=Config.get_date_format())

        # Create the key word arguments for the API
        kwargs = {}
        kwargs['granularity'] = time_frame_granularity
        kwargs['alignmentTimezone'] = Config.get_time_zone()
        kwargs['count'] = 1

        for candle_type in candle_types:
            if candle_type == 'bid':
                kwargs['price'] = 'B' + kwargs.get('price', '')

            elif candle_type == 'ask':
                kwargs['price'] = 'A' + kwargs.get('price', '')

            elif candle_type == 'mid':
                kwargs['price'] = 'M' + kwargs.get('price', '')

        # Use the Oanda API context as well as the key word arguments to get the historical currency data
        response = api_context.instrument.candles(currency_pair, **kwargs)

        # If the API call was unsucessful, return null for the candles data as well as the response error message
        if response.status != 200:
            return None, str(response) + '\n' + str(response.body)

        # Otherwise, return the candles data and null for the error message
        return response.get("candles", 200), None
def main():
    print("------ System online -------", datetime.now())
    latest_price_time = (datetime.utcnow() - timedelta(seconds=15)).isoformat('T')+'Z'

    api = v20.Context(
            'api-fxpractice.oanda.com',
            '443',
            token=OANDA_ACCESS_TOKEN)

    response = api.pricing.get(
                    OANDA_ACCOUNT_ID,
                    instruments='EUR_USD',
                    since=latest_price_time,
                    includeUnitsAvailable=False)

    print(response.reason + latest_price_time)

    prices = response.get("prices", 200)

    if len(prices):
        buy_price = prices[0].bids[0].price
        sell_price = prices[0].asks[0].price
        print('buy %s, sell %s, spread %s' % (buy_price,sell_price,sell_price-buy_price))
    else:
        print('no prices')
 def create_context(self):
     ctx = v20.Context(self.hostname,
                       self.port,
                       self.ssl,
                       token=self.token,
                       datetime_format=self.datetime_format)
     return ctx
def main():
    print("------ System online -------", datetime.now())
    latest_price_time = (datetime.utcnow() -
                         timedelta(seconds=15)).isoformat('T') + 'Z'

    api = v20.Context('api-fxtrade.oanda.com', '443', token=OANDA_ACCESS_TOKEN)

    response = api.pricing.get(OANDA_ACCOUNT_ID,
                               instruments='EUR_USD',
                               since=latest_price_time,
                               includeUnitsAvailable=False)

    print(response.reason, latest_price_time)

    prices = response.get("prices", 200)
    if len(prices):
        buy_price = prices[0].bids[0].price

        print("Buy at", buy_price)

        response = api.order.market(OANDA_ACCOUNT_ID,
                                    instrument='EUR_USD',
                                    units=5000)

        print("Trading id", response.get('orderFillTransaction').id)
        print("Account Balance",
              response.get('orderFillTransaction').accountBalance)
        print("Price", response.get('orderFillTransaction').price)

    else:
        print(response.reason)
    def __init__(self, oanda_key=None, url=None):
        if oanda_key is None:
            self.key = os.environ['OANDA_KEY']
        else:
            self.key = oanda_key
        if url is None:
            self.url = "api-fxpractice.oanda.com"
        else:
            self.url = url
        self.api = v20.Context(self.url, 443, token=self.key)

        self.accounts = {}

        try:
            accountlist = self.api.account.list().get('accounts')
        except:
            msg = 'One of the parameters key ({}) or url ({}) seems to be wrong'
            raise ValueError(msg.format(self.key, self.url))

        for a in accountlist:
            self.accounts[a.id] = OandaAccount(self.api, a.id)
            acc = self.api.account.get(a.id)
            acc = acc.get('account')
            if acc.alias == 'Primary':
                self.primary = self.accounts[a.id]
Exemple #13
0
def main():
    account_id = os.getenv('V20_ACCOUNT_ID')
    application_name = os.getenv('V20_APPLICATION_NAME')
    token = os.getenv('V20_TOKEN')
    instruments = os.getenv('V20_INSTRUMENTS')
    snapshot = to_bool(os.getenv('V20_SNAPSHOT', True))
    host = os.getenv('V20_HOST', 'stream-fxpractice.oanda.com')

    api = v20.Context(hostname=host,
                      port=443,
                      ssl=True,
                      application=application_name,
                      token=token,
                      datetime_format="UNIX")

    response = api.pricing.stream(
        account_id,
        snapshot=snapshot,
        instruments=instruments,
    )

    print(f'Listening for stock price data from {host}')
    print(f'Account: {account_id}')
    print(f'Instruments: {instruments}')

    for _, msg in response.parts():
        if isinstance(msg, PricingHeartbeat):
            # ? Log this?
            pass
        elif isinstance(msg, ClientPrice):
            # ? Logs?
            save_to_db(msg)
        else:
            raise Exception('unexpected value')
Exemple #14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--hostname",
                        default="api-fxpractice.oanda.com",
                        help="v20 REST server hostname")
    parser.add_argument("--port",
                        type=int,
                        default=443,
                        help="v20 REST server port")
    parser.add_argument("--accountid",
                        default="101-001-8202252-001",
                        help="v20 account ID")
    parser.add_argument(
        "--token",
        default=
        "e8fee72913e5e218b36ae4e033799030-379435510d3d570855776d7ac80cd223",
        help="v20 auth token")
    parser.add_argument("--instrument",
                        default="EUR_USD",
                        type=common.args.instrument,
                        help="The instrument to place a market order for")
    parser.add_argument("--units",
                        default="1",
                        help="Number of units for the market order")
    args = parser.parse_args()

    api = v20.Context(args.hostname, args.port, token=args.token)

    response = api.order.market(args.accountid,
                                instrument=args.instrument,
                                units=args.units)

    print("Response: {} ({})".format(response.status, response.reason))
    print("")
    print_order_create_response_transactions(response)
Exemple #15
0
    def __init__(self, conf_file):
        ''' Init function is expecting a configuration file with
        the following content:

        [oanda]
        account_id = XYZ-ABC-...
        access_token = ZYXCAB...
        account_type = practice (default) or live

        Parameters
        ==========
        conf_file: string
            path to and filename of the configuration file,
            e.g. '/home/me/oanda.cfg'
        '''
        self.config = configparser.ConfigParser()
        self.config.read(conf_file)
        self.access_token = self.config['oanda']['access_token']
        self.account_id = self.config['oanda']['account_id']
        self.account_type = self.config['oanda']['account_type']

        if self.account_type == 'live':
            self.hostname = 'api-fxtrade.oanda.com'
            self.stream_hostname = 'stream-fxtrade.oanda.com'
        else:
            self.hostname = 'api-fxpractice.oanda.com'
            self.stream_hostname = 'stream-fxpractice.oanda.com'

        self.ctx = v20.Context(
            hostname=self.hostname,
            port=443,
            # ssl=True,
            # application='sample_code',
            token=self.access_token,
            # datetime_format='RFC3339'
        )
        self.ctx_stream = v20.Context(
            hostname=self.stream_hostname,
            port=443,
            # ssl=True,
            # application='sample_code',
            token=self.access_token,
            # datetime_format='RFC3339'
        )

        self.suffix = '.000000000Z'
        self.stop_stream = False
def main():
    """
    Create a Market Order in an Account based on the provided command-line
    arguments.
    """

    parser = argparse.ArgumentParser()

    #
    # Add arguments for API connection
    #
    parser.add_argument("--hostname",
                        default="api-fxpractice.oanda.com",
                        help="v20 REST Server hostname")

    parser.add_argument("--port",
                        type=int,
                        default=443,
                        help="v20 REST Server port")

    #
    # Add Account arguments
    #
    parser.add_argument("accountid", help="v20 Account ID")

    parser.add_argument("token", help="v20 Auth Token")

    #
    # Add arguments for minimal Market Order
    #
    parser.add_argument("instrument",
                        type=common.args.instrument,
                        help="The instrument to place the Market Order for")

    parser.add_argument("units",
                        help="The number of units for the Market Order")

    args = parser.parse_args()

    #
    # Create the API context based on the provided arguments
    #
    api = v20.Context(args.hostname, args.port, token=args.token)

    #
    # Submit the request to create the Market Order
    #
    response = api.order.market(args.accountid,
                                instrument=args.instrument,
                                units=args.units)

    #
    # Process the response
    #
    print("Response: {} ({})".format(response.status, response.reason))

    print("")

    print_order_create_response_transactions(response)
Exemple #17
0
    def __init__(self,
                 config_name,
                 _type,
                 verbose=2,
                 write_trades=False,
                 multiplier=1):
        # class init
        # config_name: Path to config file
        # _type: which section of the config file to use for broker connection
        # verbose: verbositiy. 0: Display FATAL only, 1: Display progress bars also, >=2: Display a lot of misc info
        self.multiplier = multiplier
        self.write_trades = write_trades
        if write_trades:
            trades_path = '/home/tubuntu/data/trades.csv'
            self.trades_file = open(trades_path, 'w')
            #self.trades_file.write('INS,UNITS,TP,SL,ENTRY,EXPIRY;')

        config = configparser.ConfigParser()
        config.read(config_name)
        self.verbose = verbose

        self.settings = {
            'estim_path': config.get('data', 'estim_path'),
            'prices_path': config.get('data', 'prices_path')
        }
        if _type and v20present:
            self.settings['domain'] = config.get(_type, 'streaming_hostname')
            self.settings['access_token'] = config.get(_type, 'token')
            self.settings['account_id'] = config.get(_type, 'active_account')
            self.settings['v20_host'] = config.get(_type, 'hostname')
            self.settings['v20_port'] = config.get(_type, 'port')
            self.settings['account_risk'] = int(
                config.get('triangle', 'account_risk'))
            self.oanda = v20.Context(self.settings.get('v20_host'),
                                     port=self.settings.get('v20_port'),
                                     token=self.settings.get('access_token'))
            self.allowed_ins = \
                self.oanda.account.instruments(self.settings.get('account_id'
                                                                 )).get('instruments', '200')
            self.trades = self.oanda.trade.list_open(
                self.settings.get('account_id')).get('trades', '200')
            self.orders = self.oanda.order.list(
                self.settings.get('account_id')).get('orders', '200')
        self.db = dataset.connect(config.get('data', 'candle_path'))
        self.calendar_db = dataset.connect(config.get('data', 'calendar_path'))
        self.optimization_db = dataset.connect(
            config.get('data', 'optimization_path'))
        self.calendar = self.calendar_db['calendar']
        self.table = self.db['dailycandles']
        self.estimtable = self.db['estimators']
        self.importances = self.db['feature_importances']
        self.opt_table = self.optimization_db['function_values']
        # the following arrays are used to collect aggregate information in estimator improvement
        self.accuracy_array = []
        self.n_components_array = []
        self.spreads = {}
        self.prices = {}
Exemple #18
0
def create_streaming_context():
    """
    Initialize a streaming API context based on the Config instance
    """
    ctx = v20.Context(hostname=OANDA_STREAM_DOMAIN,
                      application=settings.APPLICATION_NAME,
                      token=settings.OANDA_ACCESS_TOKEN,
                      datetime_format='RFC3339')

    return ctx
Exemple #19
0
 def __init__(self, domain, access_token, account_id):
     self.domain = domain
     self.access_token = access_token
     self.account_id = account_id
     self.ctx = v20.Context(self.domain,
                            443,
                            True,
                            application="sample_code",
                            token=self.access_token,
                            datetime_format="RFC3339")
Exemple #20
0
 def __init__(self,
              oanda_access_token,
              hostname='api-fxpractice.oanda.com',
              datetime_format='UNIX'):
     self.oanda_access_token = oanda_access_token
     self.hostname = hostname
     self.datetime_format = datetime_format
     self.api = v20.Context(hostname=self.hostname,
                            token=self.oanda_access_token,
                            datetime_format=datetime_format)
 def connectToServer(self):
     while True:  #Loops indefinitely because connecting to the server is critical to the code working
         try:
             self.api = v20.Context(self.hostname,
                                    self.portname,
                                    token=self.apiToken)
             return
         except V20Timeout:
             self.timeoutError('Forex could not connect to the server')
         except V20ConnectionError:
             self.connectionError('Forex could not connect to the server')
Exemple #22
0
def create_api_context():
    """
    Initialize an API context based on the Config instance
    """
    ctx = v20.Context(
        hostname=OANDA_API_DOMAIN,
        application=settings.APPLICATION_NAME,
        token=settings.OANDA_ACCESS_TOKEN,
    )

    return ctx
Exemple #23
0
    def create_streaming_context(self):
        """
        Initialize a streaming API context based on the Config instance
        """
        ctx = v20.Context(self.streaming_hostname,
                          self.port,
                          self.ssl,
                          application="sample_code",
                          token=self.token,
                          datetime_format=self.datetime_format)

        return ctx
    def __init__(self,dir, pair, zslice, since, till, ctx=v20.Context("","",token="")):
        import csv
        self.dir = dir
        self.slice = zslice
        self.pair = pair
        self.since = since
        self.till  = makeTILL(till)

        self.fileIterator = FileCacheIterator(dir, pair, zslice,since, till)
        self.ctx = ctx

        self.rowIterator = None
Exemple #25
0
    def __init__(self, momentum, instrument, units, *args, **kwargs):

        self.ticks = 0
        self.position = 0
        self.data = pd.DataFrame()
        self.momentum = momentum
        self.account_id = account_id
        self.instrument = instrument
        self.units = units
        self.ctx = v20.Context('api-fxpractice.oanda.com',
                               443,
                               True,
                               application='sample_code',
                               token=access_token,
                               datetime_format='RFC3339')
        self.ctx_stream = v20.Context('stream-fxpractice.oanda.com',
                                      443,
                                      True,
                                      application='sample_code',
                                      token=access_token,
                                      datetime_format='RFC3339')
Exemple #26
0
    def __init__(self, instrument='XAU_USD', units=1, *args, **kwargs):

        self.ticks = 0
        self.position = 0  #记录策略开仓方向
        self.account_id = account_id
        self.instrument = instrument
        self.units = units
        self.ctx = v20.Context('api-fxpractice.oanda.com',
                               443,
                               True,
                               application='sample_code',
                               token=access_token,
                               datetime_format='RFC3339')
        self.ctx_stream = v20.Context('stream-fxpractice.oanda.com',
                                      443,
                                      True,
                                      application='sample_code',
                                      token=access_token,
                                      datetime_format='RFC3339')
        self.data = self._init_data(self.ctx)
        print(self.data.head(15))
    def __init__(self):
        '''Initialization'''
        super(OandaV20Store, self).__init__()

        self.notifs = collections.deque()  # store notifications for cerebro

        self._cash = 0.0  # margin available, currently available cash
        self._value = 0.0  # account balance
        self._currency = None  # account currency
        self._leverage = 1  # leverage
        self._client_id_prefix = str(datetime.now().timestamp())

        self.broker = None  # broker instance
        self.datas = list()  # datas that have registered over start

        self._env = None  # reference to cerebro for general notifications
        self._evt_acct = SerializableEvent()
        self._orders = collections.OrderedDict()  # map order.ref to order id
        self._trades = collections.OrderedDict()  # map order.ref to trade id

        # init oanda v20 api context
        self.oapi = v20.Context(
            self._OAPI_URL[int(self.p.practice)],
            poll_timeout=self.p.poll_timeout,
            port=443,
            ssl=True,
            token=self.p.token,
            datetime_format="UNIX",
        )

        # init oanda v20 api stream context
        self.oapi_stream = v20.Context(
            self._OAPI_STREAM_URL[int(self.p.practice)],
            stream_timeout=self.p.stream_timeout,
            port=443,
            ssl=True,
            token=self.p.token,
            datetime_format="UNIX",
        )
Exemple #28
0
 def __init__(self, config_name):
     self.config = configparser.ConfigParser()
     self.prices = dict()
     self.config.read(config_name)
     self.fxmath = self.get_fxmath()
     self.oanda = v20.Context(self.config.get('live', 'hostname'),
                              port=self.config.get('live', 'port'),
                              token=self.config.get('live', 'token'))
     self.allowed_ins = \
         self.oanda.account.instruments(self.config.get('live', 'active_account'
                                                        )).get('instruments', '200')
     self.trades = self.oanda.trade.list_open(
         self.config.get('live', 'active_account')).get('trades', '200')
    def get_historical_data(self, currency_pair, time_frame_granularity,
                            from_time, to_time):
        # Initialize the candle types - we'll just restrict them to the bid and ask prices since no one really cares
        # about the mid prices
        candle_types = ['bid', 'ask']

        # Check the parameters
        valid_params, error_message = self._check_historical_data_parameters(
            currency_pair, candle_types, time_frame_granularity, from_time,
            to_time)

        # If the parameters aren't valid, return null for the candles data as well as the error message
        if not valid_params:
            return None, error_message

        # Create the Oanda API context
        api_context = v20.Context(Config.get_host_name(),
                                  Config.get_port(),
                                  Config.get_ssl(),
                                  application="sample_code",
                                  token=Config.get_api_token(),
                                  datetime_format=Config.get_date_format())

        # Create the key word arguments for the API
        kwargs = {}
        kwargs['granularity'] = time_frame_granularity
        kwargs['fromTime'] = api_context.datetime_to_str(
            datetime.strptime(from_time, '%Y-%m-%d %H:%M:%S'))
        kwargs['toTime'] = api_context.datetime_to_str(
            datetime.strptime(to_time, '%Y-%m-%d %H:%M:%S'))

        for candle_type in candle_types:
            if candle_type == 'bid':
                kwargs['price'] = 'B' + kwargs.get('price', '')

            elif candle_type == 'ask':
                kwargs['price'] = 'A' + kwargs.get('price', '')

            elif candle_type == 'mid':
                kwargs['price'] = 'M' + kwargs.get('price', '')

        # Use the Oanda API context as well as the key word arguments to get the historical currency data
        response = api_context.instrument.candles(currency_pair, **kwargs)

        # If the API call was unsucessful, return null for the candles data as well as the response error message
        if response.status != 200:
            return None, str(response) + '\n' + str(response.body)

        # Otherwise, return the candles data and null for the error message
        return response.get("candles", 200), None
Exemple #30
0
    def get_open_trades(self):
        api_context = v20.Context(Config.get_host_name(),
                                  Config.get_port(),
                                  Config.get_ssl(),
                                  application="sample_code",
                                  token=Config.get_api_token(),
                                  datetime_format=Config.get_date_format())

        response = api_context.trade.list_open(Config.get_account())

        if response.status != 200:
            return None, str(response) + '\n' + str(response.body)

        return response.body['trades'], None