예제 #1
0
파일: TD.py 프로젝트: cruberg/guild
    def __init__(self):
        import os
        from config import CONSUMER_KEY, REDIRECT_URI, JSON_PATH
        from charlie import TD_ACCOUNT, my_Alpaca_key, my_Alpaca_secret, filepath, outpath
        from td.client import TDClient
        import alpaca_trade_api as tradeapi
        from datetime import datetime
        from datetime import timedelta
        import pandas as pd
        import numpy as np
        import time
        os.chdir(filepath)

        self.TDSession = TDClient(client_id = CONSUMER_KEY, redirect_uri = REDIRECT_URI, credentials_path = JSON_PATH)
        self.td_client = TDClient(CONSUMER_KEY, REDIRECT_URI, TD_ACCOUNT, JSON_PATH)
        self.td_client.login()

        self.alpaca_api_key = my_Alpaca_key
        self.alpaca_api_secret = my_Alpaca_secret

        self.api = tradeapi.REST(
            self.alpaca_api_key,
            self.alpaca_api_secret,
            'https://paper-api.alpaca.markets',
            api_version='v2'
        )
예제 #2
0
def connect_to_TDA():
    TDSession = TDClient(client_id=CONSUMER_KEY,
                         redirect_uri=REDIRECT_URI,
                         credentials_path='tda_key.json')

    TDSession.login()
    return TDSession
예제 #3
0
 def with_client(self, client_id, redirect_uri, credentials_path,
                 account_id):
     self.account_id = account_id
     self.client = TDClient(client_id=client_id,
                            redirect_uri=redirect_uri,
                            credentials_path=credentials_path)
     self.client.login()
예제 #4
0
파일: ALLTD.py 프로젝트: JChaiTea/Chia
class tdAction(object):
    def __init__(self):
        """Constructor"""
        self.conKey = CONSUMER_KEY
        self.redirect = REDIRECT_URL
        self.acct = ACCT_NUM
        self.tdClient = TDClient(client_id=self.conKey,
                                 redirect_uri=self.redirect)
        self.tdClient.login()

    def quote(self, tickerList):
        """Grab quotes"""
        retDict = {}
        quotes = self.tdClient.get_quotes(instruments=tickerList)
        for key in quotes:
            if type(quotes[key]['lastPrice']) is not None:
                retDict[key] = quotes[key]['lastPrice']
        return retDict

    def history(self, tickerList):
        """Create real time data for a given list of tickers"""
        retDict = {}
        for item in tickerList:
            tickerHistory = self.tdClient.get_price_history(symbol=item,
                                                            period_type='year')
            priceHistory = []
            for data in tickerHistory['candles']:
                priceHistory.append(data['close'])
            df = DataFrame({item: priceHistory})
            retDict[item] = df
        return retDict
예제 #5
0
파일: ALLTD.py 프로젝트: JChaiTea/Chia
 def __init__(self):
     """Constructor"""
     self.conKey = CONSUMER_KEY
     self.redirect = REDIRECT_URL
     self.acct = ACCT_NUM
     self.tdClient = TDClient(client_id=self.conKey,
                              redirect_uri=self.redirect)
     self.tdClient.login()
예제 #6
0
    def create_client(self) -> TDClient:
        creds_file = self.__fetch_credential_file()
        client = TDClient(client_id=self.td_client_id,
                          redirect_uri=self.td_redirect_uri,
                          credentials_path=creds_file)

        client.login()
        return client
예제 #7
0
def initialize(client_id, redirect_uri, credentials_path):
    global client
    if client:
        raise RuntimeError("client已经初始化了")
    client = TDClient(client_id=client_id,
                      redirect_uri=redirect_uri,
                      credentials_path=credentials_path)
    client.login()
    TSTypeRegistry.register(TDDailyBar())
예제 #8
0
    def _create_session(self) -> TDClient:
        td_client = TDClient(client_id=self.client_id,
                             redirect_uri=self.redirect_uri,
                             credentials_path=self.credentials_path)

        # login to the sessions.
        td_client.login()

        return td_client
예제 #9
0
def initialize(client_id, redirect_uri, credentials_path):
    global client
    if client:
        raise RuntimeError("client已经初始化了")
    client = TDClient(
        client_id=client_id,
        redirect_uri=redirect_uri,
        credentials_path=credentials_path
    )
    client.login()
 def auth(self, credentials_path='./td_state.json', client_path='./td_client_auth.json'):
     with open(client_path) as f:
         data = json.load(f)
     self.session = TDClient(
         client_id=data['client_id'],
         redirect_uri=data['callback_url'],
         credentials_path=credentials_path
     )
     self.session.login()
     
     # assuming only 1 account under management
     self.account = self.session.get_accounts(fields=['positions'])[0]
     self.account_id = self.account['securitiesAccount']['accountId']
     return self.session
예제 #11
0
def history(symbol):
    quotes = TDClient.get_price_history(TDSession, symbol=symbol, period_type='day',
                                        period=1, frequency_type='minute', frequency=1,
                                        extended_hours=False)
    # start_date = 1606086000000, end_date = 1606341600000,

    return quotes
예제 #12
0
 def get_TDClient(self):
     # Create a new session, credentials path is optional.
     TDSession = TDClient(
         client_id='LZGUB1XDODQPG9D95BZ0G7ZV8AMAUVM8',
         redirect_uri="http://localhost/green_chip",
         credentials_path="credentials.json"
     )
     return TDSession
예제 #13
0
  def create_client(force_refresh:bool=True, version:str='AWSCURRENT') -> TDClient:
    factory = ClientFactory()
    
    base_path = '/tmp/'
    if platform == 'win32':
      base_path = path.join(path.dirname(__file__),'..')

    #outfile = TemporaryDirectory(dir='FsiCollector')
    outpath = path.join(base_path,'creds.json')
    creds_file = factory.__fetch_credential_file(force_refresh=force_refresh, outpath=outpath, version=version)
    client = TDClient(
      client_id=factory.td_client_id,
      redirect_uri=factory.td_redirect_uri,
      credentials_path=creds_file)

    client.login()
    return client
    def setUp(self) -> None:
        """Set up the `TDClient`."""

        # Grab configuration values.
        config = ConfigParser()
        config.read('config/config.ini')

        # Load the values.
        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        JSON_PATH = config.get('main', 'JSON_PATH')
        ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        # Initalize the session.
        self.td_session = TDClient(client_id=CLIENT_ID,
                                   redirect_uri=REDIRECT_URI,
                                   credentials_path=JSON_PATH,
                                   account_number=ACCOUNT_NUMBER)
예제 #15
0
    def _create_session(self) -> TDClient:
        """Start a new session.
        Creates a new session with the TD Ameritrade API and logs the user into
        the new session.
        Returns:
        ----
        TDClient -- A TDClient object with an authenticated sessions.
        """

        # Create a new instance of the client
        td_client = TDClient(client_id=self.client_id,
                             redirect_uri=self.redirect_uri,
                             credentials_path=self.credentials_path)

        # log the client into the new session
        td_client.login()

        return td_client
예제 #16
0
def dt_signal_prices(candle_minutes, symbols):
    TDSession = TDClient(client_id=config.client_id,
                         redirect_uri='http://localhost/test',
                         credentials_path='td_state.json')

    TDSession.login()

    cur_day = datetime.datetime.now(tz=pytz.timezone('US/Eastern'))
    price_end_date = str(int(round(cur_day.timestamp() * 1000)))
    price_start_date = str(
        int(
            round(
                datetime.datetime(cur_day.year, cur_day.month,
                                  cur_day.day - 1).timestamp() * 1000)))

    candle_list = []

    for symbol in symbols:
        p_hist = TDSession.get_price_history(symbol,
                                             period_type='day',
                                             frequency_type='minute',
                                             frequency=str(candle_minutes),
                                             end_date=price_end_date,
                                             start_date=price_start_date)

        for candle in p_hist['candles']:
            candle_list.append([
                symbol,
                datetime.datetime.fromtimestamp(candle['datetime'] / 1000),
                candle['open'], candle['close'], candle['high'], candle['low']
            ])

    df_dt = pd.DataFrame(
        candle_list,
        columns=['Symbol', 'Date', 'Open', 'Close', 'High', 'Low'])

    # Calculate moving average
    df_dt['SMA_9'] = df_dt.groupby('Symbol')['Close'].rolling(
        9).mean().reset_index(0, drop=True)

    return df_dt
예제 #17
0
def history(symbol, period, p_type, freq, f_type):
    quotes = TDClient.get_price_history(TDSession,
                                        symbol=symbol,
                                        period=period,
                                        period_type=p_type,
                                        frequency=freq,
                                        frequency_type=f_type,
                                        extended_hours=False,
                                        start_date=1606086000000)
    # start_date=1606086000000, end_date = 1606341600000,

    return quotes
예제 #18
0
    def grab_refresh_token(self, tda_creds: dict) -> TDClient:

        # Write the creds int a known location...
        output = path.join(gettempdir(), 'creds.json')
        with open(output, 'w') as f:
            f.write(dumps(tda_creds))

        # Fetch the offline token...
        client = TDClient(credentials_path=output,
                          client_id=self.client_id,
                          redirect_uri=self.redirect_uri)

        if not client.login():
            raise ValueError('Unable to login')
        if not client.grab_refresh_token():
            raise ValueError('Unable to grab_refresh_token')

        # Read the cached offline token...
        with open(output, 'r') as f:
            token = f.read()
            return loads(token)
예제 #19
0
def get_symbols(watchlist):
    TDSession = TDClient(client_id=config.client_id,
                         redirect_uri='http://localhost/test',
                         credentials_path='td_state.json')

    TDSession.login()

    response = TDSession.get_watchlist_accounts()

    i = 0

    for r in response:
        if r['name'] == str(watchlist):
            watch = response[i]
            symbols = [
                watch['watchlistItems'][x]['instrument']['symbol']
                for x in range(len(watch['watchlistItems']))
            ]
        else:
            i += 1

    return symbols
예제 #20
0
    def setUp(self) -> None:
        """Set up the Portfolio."""

        self.portfolio = Portfolio()
        self.maxDiff = None

                # Grab configuration values.
        config = ConfigParser()
        config.read('configs/config.ini')       

        CLIENT_ID = config.get('main', 'CLIENT_ID')
        REDIRECT_URI = config.get('main', 'REDIRECT_URI')
        CREDENTIALS_PATH = config.get('main', 'JSON_PATH')
        self.ACCOUNT_NUMBER = config.get('main', 'ACCOUNT_NUMBER')

        self.td_client = TDClient(
            client_id=CLIENT_ID,
            redirect_uri=REDIRECT_URI,
            credentials_path=CREDENTIALS_PATH
        )

        self.td_client.login()
import pprint
from datetime import datetime
from datetime import timedelta
from td.client import TDClient

# Create a new session
TDSession = TDClient(client_id='<CLIENT_ID>',
                     redirect_uri='<REDIRECT_URI>',
                     credentials_path='<CREDENTIALS_PATH>')

# Login to the session
TDSession.login()

# Define a list of all valid periods
valid_values = {
    'minute': {
        'day': [1, 2, 3, 4, 5, 10]
    },
    'daily': {
        'month': [1, 2, 3, 6],
        'year': [1, 2, 3, 5, 10, 15, 20],
        'ytd': [1]
    },
    'weekly': {
        'month': [1, 2, 3, 6],
        'year': [1, 2, 3, 5, 10, 15, 20],
        'ytd': [1]
    },
    'monthly': {
        'year': [1, 2, 3, 5, 10, 15, 20]
    }
예제 #22
0
    for key, value in dict_obj.items():
        if isinstance(value, dict):
            print_nested(value)
        else:
            if isinstance(value, list):
                print("")
                for inner in value:
                    print_nested(inner)
            else:
                print(key, ':', value)
                

# Create a new session, credentials path is required.
TDSession = TDClient(
    client_id = os.environ['TDAMERITRADE_CLIENT_ID'],
    redirect_uri = 'http://localhost',
    credentials_path='[put your path here]/credentials.json'
)

# Login to the session
TDSession.login()
        
# Option Chain Example
opt_chain = {
    'symbol': 'MSFT',
    'contractType': 'PUT',
    'optionType': 'S',
    'fromDate': '2020-04-01',
    'afterDate': '2020-05-21',
    'strikeCount': 20,
    'includeQuotes': False,
예제 #23
0
from sqlalchemy import create_engine
from td.client import TDClient
from datetime import datetime
from td import exceptions
import datetime
import pandas as pd
import sqlite3
import time
import credentials

TDSession = TDClient(
    client_id=credentials.client_id,
    redirect_uri='https://127.0.0.1',
    credentials_path=
    '/Users/Sato/Documents/PycharmProjects/open_interest/td_state.json')

TDSession.login()


def history(symbol):
    quotes = TDClient.get_price_history(TDSession,
                                        symbol=symbol,
                                        period_type='day',
                                        period=1,
                                        frequency_type='minute',
                                        frequency=1,
                                        extended_hours=False)
    # start_date = 1606086000000, end_date = 1606341600000,

    return quotes
예제 #24
0
class MakeRequest:
    def get_front_date(date_delta):
        dates_list = []
        for i in range(0, date_delta):
            d = datetime.date.today()
            d += datetime.timedelta(i)
            if d.weekday() == 4:
                dates_list.append(str(d))
        #print(dates_list[-2])
        return dates_list[0]

    def get_back_date(date_delta):
        dates_list = []
        for i in range(0, date_delta):
            d = datetime.date.today()
            d += datetime.timedelta(i)
            if d.weekday() == 4:
                dates_list.append(str(d))
        #print(dates_list[-1])
        return dates_list[-1]

    # Create a new session, credentials path is optional.
    TDSession = TDClient(client_id=client_id,
                         redirect_uri=redirect_uri,
                         credentials_path='')

    TDSession.login()

    front_date = get_front_date(date_delta)
    back_date = get_back_date(date_delta)

    # ========= check earnings calendar ==========
    date_from = datetime.datetime.strptime(
        date.today().strftime('%Y-%m-%d') + " 05:00:00", '%Y-%m-%d %X')
    date_to = datetime.datetime.strptime(front_date + " " + "18:00:00",
                                         '%Y-%m-%d %X')

    symbols = []
    watchlist_filename = "./callie_scripts/2020-11-04-watchlist.csv"
    with open(watchlist_filename, newline="") as watchlist_file:
        fr = csv.reader(watchlist_file, delimiter=',', quotechar='|')
        for row in fr:
            if len(row) > 1 and row[0] != "Symbol":
                symbols.append(row[0])

    # Login to the session

    option_chains_list = []

    for symbol in symbols:
        #print(symbol)
        opt_chain = {
            'symbol': symbol,
            'contractType': 'CALL',
            'optionType': 'S',
            'fromDate': front_date,
            'toDate': back_date,
            #'strikeCount': 15,
            'includeQuotes': True,
            'range': 'OTM',
            'strategy': 'SINGLE',
        }
        try:
            option_chains = TDSession.get_options_chain(option_chain=opt_chain)
            time.sleep(.5)
        except:
            # might be querying the API too quickly. wait and try again
            print("error getting data from TD retrying ...")
            time.sleep(7)  # compeletely reset per second rule from TDA
            option_chains = TDSession.get_options_chain(option_chain=opt_chain)
        try:
            quote = option_chains['underlying']['mark']
        except:
            print('error getting stock quote for', symbol)

        print(option_chains)
        option_chains_list.append(option_chains)

    with open('callie_scripts/options_chains_list.json', 'w') as f:
        json.dump(option_chains_list, f)

    with open('callie_scripts/scan_time.json', 'w') as f:
        tz = timezone('EST')
        d = str(datetime.datetime.now(tz))
        json.dump(d, f)
    --------------------
    10. NEWS_HEADLINE
    11. ACCT_ACTIVITY


    EXPERIMENTAL - WORKING
    ----------------------
    1. LEVEL TWO QUOTES
    2. LEVEL TWO OPTIONS
    3. LEVEL TWO NASDAQ

'''

# Create a new session
TDSession = TDClient(account_number=ACCOUNT_NUMBER,
                     account_password=ACCOUNT_PASSWORD,
                     consumer_id=CONSUMER_ID,
                     redirect_uri=REDIRECT_URI)

# Login to the session
TDSession.login()

# Create a streaming sesion
TDStreamingClient = TDSession.create_streaming_session()

'''
    REGULAR - WORKING
'''

# # Actives
# TDStreamingClient.actives(service='ACTIVES_NASDAQ',
#                           venue='NASDAQ', duration='ALL')
예제 #26
0
from datetime import datetime
from datetime import timedelta
from td.client import TDClient

# Create a new session
TDSession = TDClient(
    client_id='<CLIENT_ID>',
    redirect_uri='<REDIRECT_URI>',
    credentials_path='<CREDENTIALS_PATH>'
)


# Login to the session
TDSession.login()

# `get_quotes` endpoint with single value. Should not return an error.
quotes_single = TDSession.get_quotes(instruments=['SQ'])

# `get_quotes` with a Options Contract
quotes_option_contract = TDSession.get_quotes(instruments=['MSFT_041720C75'])

# `get_quotes` with a Futures Contract
quotes_futures = TDSession.get_quotes(instruments=['/ES'])

# `get_quotes` with Forex
quotes_forex = TDSession.get_quotes(instruments=['AUD/USD'])

# `get_quotes` endpoint with multiple values
quotes_multi = TDSession.get_quotes(instruments=['SQ', 'MSFT'])

# `search_instruments` Endpoint
예제 #27
0
from td.client import TDClient
"""
Follow the tutorial below:
https://www.youtube.com/watch?v=8N1IxYXs4e8&ab_channel=SigmaCoding
"""

# Create a new session, credentials path is required.
TDSession = TDClient(
    client_id='WPT2HCPQWAPY3TPSXDQTNTNXPGSW8ZOH',
    redirect_uri='http://localhost/StrategicOptions',
    credentials_path=
    'C:/Users/chena/Desktop/Trading/TD Ameritrade/API/td_state.json')

TDSession.login()
예제 #28
0
from td.client import TDClient
import requests
import json

import oca_config
import option_chain

settingsLocation = "Settings/oca_config.ini"
oca_config_ini = oca_config.OcaConfig(settingsLocation)

# Create a new session, credentials path is optional.
TDSession = TDClient(
    client_id=oca_config_ini.consumerKey,
    redirect_uri=oca_config_ini.callbackUrl,
)

# Login to the session
TDSession.login()

full_url = 'https://api.tdameritrade.com/v1/marketdata/chains?'

page = requests.get(
    url=full_url,
    params=
    {
        'apikey' : oca_config_ini.consumerKey,
        'symbol' : oca_config_ini.ticker,
        'fromDate' : oca_config_ini.fromDate,
        'toDate' : oca_config_ini.toDate,
        'contractType' : oca_config_ini.contractType,
    })
예제 #29
0
파일: app.py 프로젝트: zachariah25/gamma
        open('/run/secrets/client_secret')
        return '/run/secrets/client_secret'
    except FileNotFoundError:
        return '../client_secret.json'


def getClientId():
    try:
        return open('/run/secrets/client_id').readline().strip()
    except FileNotFoundError as e:
        return open('../client_id.txt').readline().strip()


# Create a new session, credentials path is optional.
TDSession = TDClient(client_id=getClientId(),
                     redirect_uri='https://127.0.0.1',
                     credentials_path=getClientSecretPath(),
                     auth_flow='flask')

# Login to the session
TDSession.login()


def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
예제 #30
0
]
timesale_fields = [
    'symbol', 'last-price', 'last-size', 'trade-time', 'last-sequence'
]
chart_fields = [
    'key', 'open-price', 'high-price', 'low-price', 'close-price', 'volume',
    'sequence', 'chart-time', 'chart-day'
]

import pprint
from td.client import TDClient
import config.credentials as config

# Create a new session
TDSession = TDClient(client_id=config.CLIENT_ID,
                     redirect_uri=config.REDIRECT_URI,
                     credentials_path=config.JSON_PATH)

# Login to the session
TDSession.login()

# Create a streaming sesion
TDStreamingClient = TDSession.create_streaming_session()

# Set the data dump location
TDStreamingClient.write_behavior(file_path="raw_data.csv", append_mode=True)

# Charts, this looks like it only streams every one minute. Hence if you want the last bar you should use this.
TDStreamingClient.chart(service='CHART_FUTURES',
                        symbols=['/CL'],
                        fields=[0, 1, 2, 3, 4, 5, 6, 7])