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
def send_email(currency_pair, signal): message = Mail(from_email=Config.get_sendgrid_email(), to_emails=Config.get_sendgrid_email(), subject=currency_pair + ' ' + str(signal), plain_text_content=str(signal) + ' signal on ' + str(currency_pair)) try: sg = SendGridAPIClient(Config.get_sendgrid_api_token()) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print('Error sending email:') print(e.message)
def __init__(self): # Database connection object self.connection = None # A list of available subscription types self.available_subscription_types = ['basic', 'advanced'] # File path to the database self.db_file_path = Config.get_db_file_path()
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 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
def clear_database(): # Connect to the database connection = sqlite3.connect(Config.get_db_file_path()) cursor = connection.cursor() # Drop all the tables (except the currency pair table since it never changes) cursor.execute("""DROP TABLE IF EXISTS followed_pairs_left""") cursor.execute("""DROP TABLE IF EXISTS pairs_followed""") cursor.execute("""DROP TABLE IF EXISTS subscriptions""") cursor.execute("""DROP TABLE IF EXISTS users""") # Recreate the dropped tables cursor.execute("""CREATE TABLE IF NOT EXISTS followed_pairs_left ( followed_pairs_left_id text, user_id text, num_pairs_available integer )""") # Create the table cursor.execute("""CREATE TABLE IF NOT EXISTS pairs_followed ( pair_followed_id text, user_id text, currency_name text )""") cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions ( subscription_id text, user_id text, subscription_type text, monthly_cost real )""") cursor.execute("""CREATE TABLE IF NOT EXISTS users ( user_id text, username text, first_name text, last_name text, password text )""") # Execute connection.commit() connection.close()
def update_trade_take_profit(trade_id, new_take_profit_price): kwargs = {} kwargs['takeProfit'] = {'price': str(new_take_profit_price)} 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.set_dependent_orders( Config.get_account(), trade_id, **kwargs) if response.status != 200: return str(response) + '\n' + str(response.body) return None
def close_trade(trade_id, n_units): kwargs = {} kwargs['units'] = str(abs(n_units)) 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.close(Config.get_account(), trade_id, **kwargs) if response.status != 200: return str(response) + '\n' + str(response.body) return None
def place_market_order(currency_pair, order_type, n_units, profit_price, stop_loss, pips_to_risk, use_trailing_stop): # Add all of the needed arguments kwargs = {} kwargs['type'] = 'MARKET' kwargs['instrument'] = currency_pair kwargs['units'] = str(n_units) if order_type == 'buy' else str( -n_units) kwargs['timeInForce'] = 'FOK' kwargs['positionFill'] = 'DEFAULT' kwargs['takeProfitOnFill'] = { 'price': str(profit_price), 'timeInForce': 'GTC' } if use_trailing_stop: kwargs['trailingStopLossOnFill'] = { 'distance': str(pips_to_risk), 'timeInForce': 'GTC' } else: kwargs['stopLossOnFill'] = { 'price': str(stop_loss), 'timeInForce': 'GTC' } # 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()) # Use the Oanda API context as well as the key word arguments to place the order response = api_context.order.market(Config.get_account(), **kwargs) print("Response: {} ({})\n{}".format(response.status, response.reason, response.body))
def get_current_tick_data(self, currency_pair): # 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['instruments'] = currency_pair # Use the Oanda API context as well as the key word arguments to get the historical currency data response = api_context.pricing.get(Config.get_account(), **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('prices', 200), None
def __init__(self): self.connection = None self.db_file_path = Config.get_db_file_path()