def consumer_thread():

    try:
        # make sure we have an event loop, if not create a new one
        loop = asyncio.get_event_loop()
        loop.set_debug(True)
    except RuntimeError:
        asyncio.set_event_loop(asyncio.new_event_loop())

    global conn
    conn = StreamConn(
        ALPACA_API_KEY,
        ALPACA_SECRET_KEY,
        base_url=URL('https://paper-api.alpaca.markets'),
        data_url=URL('https://data.alpaca.markets'),
        # data_url=URL('http://127.0.0.1:8765'),
        data_stream='polygon' if USE_POLYGON else 'alpacadatav1')

    @conn.on(r'^AM\..+$')
    async def on_minute_bars(conn, channel, bar):
        print('bars', bar)

    @conn.on(r'Q\..+')
    async def on_quotes(conn, channel, quote):
        print('quote', quote)

    @conn.on(r'T\..+')
    async def on_trades(conn, channel, trade):
        print('trade', trade)

    conn.run(['alpacadatav1/Q.GOOG'])
Exemplo n.º 2
0
    def __init__(self, config, max_workers=20, chunk_size=100, **kwargs):
        # Alpaca authorize 200 requests per minute and per API key
        # Setting the max_workers for multithreading with a maximum
        # of 200
        self.name = "alpaca"
        self.max_workers = min(max_workers, 200)

        # When requesting data for assets for example,
        # if there is too many assets, the best thing to do would
        # be to split it into chunks and request data for each chunk
        self.chunk_size = min(chunk_size, 100)

        # Connection to alpaca REST API
        self.config = config
        self.api_key = config.API_KEY
        self.api_secret = config.API_SECRET
        if hasattr(config, "ENDPOINT"):
            self.endpoint = URL(config.ENDPOINT)
        else:
            self.endpoint = URL("https://paper-api.alpaca.markets")
        if hasattr(config, "VERSION"):
            self.version = config.VERSION
        else:
            self.version = "v2"
        self.api = tradeapi.REST(self.api_key, self.api_secret, self.endpoint,
                                 self.version)
Exemplo n.º 3
0
def consumer_thread(channels):
    try:
        # make sure we have an event loop, if not create a new one
        asyncio.get_event_loop()
    except RuntimeError:
        asyncio.set_event_loop(asyncio.new_event_loop())
    global conn
    if not conn:
        conn = tradeapi.StreamConn(
            key_id=_key_id,
            secret_key=_secret_key if not USE_POLYGON else 'DUMMY',
            base_url=URL(_base_url),
            data_url=URL(_data_url),
            data_stream='polygon' if USE_POLYGON else 'alpacadatav1',
            raw_data=True,
        )

        conn.on('authenticated')(on_auth)
        conn.on(r'Q.*')(on_message)
        conn.on(r'T.*')(on_message)

        conn.on(r'listening')(listen)

        if USE_POLYGON:
            conn.on(r'A.*')(on_message)
        conn.on(r'AM.*')(on_message)
        conn.on(r'account_updates')(on_account)
        conn.on(r'trade_updates')(on_trade)
        conn.run(channels)
Exemplo n.º 4
0
def initialize_client():
    global CLIENT
    conf = config.bundle.AlpacaConfig()
    key = conf.key
    secret = conf.secret
    base_url = conf.base_url
    CLIENT = tradeapi.REST(key_id=key,
                           secret_key=secret,
                           base_url=URL(base_url))
def consumer_thread():
    global conn
    conn = Stream(ALPACA_API_KEY,
                  ALPACA_SECRET_KEY,
                  base_url=URL('https://paper-api.alpaca.markets'),
                  data_feed='iex')

    conn.subscribe_quotes(print_quote, 'AAPL')
    conn.run()
Exemplo n.º 6
0
def initialize_client():
    global CLIENT
    with open("polygon.yaml", mode='r') as f:
        o = yaml.safe_load(f)
        key = o["key_id"]
        secret = o["secret"]
        base_url = o["base_url"]
    CLIENT = tradeapi.REST(key_id=key,
                           secret_key=secret,
                           base_url=URL(base_url))
Exemplo n.º 7
0
 def __init__(self,
              key_id: str = None,
              secret_key: str = None,
              data_url: URL = None,
              api_version: str = None,
              raw_data: bool = False
              ):
     """
     :param raw_data: should we return api response raw or wrap it with
                      Entity objects.
     """
     self._key_id, self._secret_key, _ = get_credentials(key_id, secret_key)
     self._data_url: URL = URL(data_url or get_data_url())
Exemplo n.º 8
0
 def __init__(self, key_id: str = None):
     self._key_id = get_polygon_credentials(key_id)
     self._endpoint: URL = URL(
         os.environ.get('POLYGON_WS_URL',
                        'wss://socket.polygon.io/stocks').rstrip('/'))
     self._handlers = {}
     self._handler_symbols = {}
     self._streams = set([])
     self._ws = None
     self._retry = int(os.environ.get('APCA_RETRY_MAX', 3))
     self._retry_wait = int(os.environ.get('APCA_RETRY_WAIT', 3))
     self._retries = 0
     self.loop = asyncio.get_event_loop()
     self._consume_task = None
Exemplo n.º 9
0
def consumer_thread():
    try:
        # make sure we have an event loop, if not create a new one
        loop = asyncio.get_event_loop()
        loop.set_debug(True)
    except RuntimeError:
        asyncio.set_event_loop(asyncio.new_event_loop())

    global conn
    conn = Stream(ALPACA_API_KEY,
                  ALPACA_SECRET_KEY,
                  base_url=URL('https://paper-api.alpaca.markets'),
                  data_feed='iex')

    conn.subscribe_quotes(print_quote, 'AAPL')
    conn.run()
Exemplo n.º 10
0
def main(args):
    stream = Stream(ALPACA_API_KEY,
                    ALPACA_SECRET_KEY,
                    base_url=URL('https://paper-api.alpaca.markets'),
                    data_feed='iex')  # <- replace to sip for PRO subscription
    api = alpaca.REST(key_id=ALPACA_API_KEY,
                    secret_key=ALPACA_SECRET_KEY,
                    base_url="https://paper-api.alpaca.markets")

    fleet = {}
    symbols = args.symbols
    for symbol in symbols:
        algo = ScalpAlgo(api, symbol, lot=args.lot)
        fleet[symbol] = algo

    async def on_bars(data):
        if data.symbol in fleet:
            fleet[data.symbol].on_bar(data)

    for symbol in symbols:
        stream.subscribe_bars(on_bars, symbol)

    async def on_trade_updates(data):
        logger.info(f'trade_updates {data}')
        symbol = data.order['symbol']
        if symbol in fleet:
            fleet[symbol].on_order_update(data.event, data.order)

    stream.subscribe_trade_updates(on_trade_updates)

    async def periodic():
        while True:
            if not api.get_clock().is_open:
                logger.info('exit as market is not open')
                sys.exit(0)
            await asyncio.sleep(30)
            positions = api.list_positions()
            for symbol, algo in fleet.items():
                pos = [p for p in positions if p.symbol == symbol]
                algo.checkup(pos[0] if len(pos) > 0 else None)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(
        stream._run_forever(),
        periodic(),
    ))
    loop.close()
Exemplo n.º 11
0
def consumer_thread(channels):
    try:
        # make sure we have an event loop, if not create a new one
        loop = asyncio.get_event_loop()
        # loop.set_debug(True)
    except RuntimeError:
        asyncio.set_event_loop(asyncio.new_event_loop())

    global conn
    if not conn:
        conn = tradeapi.Stream(_key_id,
                               _secret_key,
                               base_url=URL(_base_url),
                               data_feed=_pro_subscription,
                               raw_data=True)
        subscribe(channels)
        conn.run()
Exemplo n.º 12
0
 def _request(self, method: str, path: str, params: dict = None,
              version: str = 'v1'):
     """
     :param method: GET, POST, ...
     :param path: url part path (without the domain name)
     :param params: dictionary with params of the request
     :param version: v1 or v2
     :return: response
     """
     url: URL = URL('https://api.polygon.io/' + version + path)
     params = params or {}
     params['apiKey'] = self._api_key
     if self._staging:
         params['apiKey'] += '-staging'
     resp = self._session.request(method, url, params=params)
     resp.raise_for_status()
     return resp.json()
 def __init__(self, key_id: str = None, raw_data: bool = False):
     """
     :param raw_data: should we return stream data raw or wrap it with
                      Entity objects.
     """
     self._key_id = get_polygon_credentials(key_id)
     self._endpoint: URL = URL(
         os.environ.get('POLYGON_WS_URL',
                        'wss://socket.polygon.io/stocks').rstrip('/'))
     self._handlers = {}
     self._handler_symbols = {}
     self._streams = set([])
     self._ws = None
     self._retry = int(os.environ.get('APCA_RETRY_MAX', 3))
     self._retry_wait = int(os.environ.get('APCA_RETRY_WAIT', 3))
     self._retries = 0
     self.loop = asyncio.get_event_loop()
     self._consume_task = None
     self._use_raw_data = raw_data
        conn.run(channels)
    except Exception as e:
        print(f'Exception from websocket connection: {e}')
    finally:
        print("Trying to re-establish connection")
        time.sleep(3)
        run_connection(conn, channels)


if __name__ == '__main__':
    channels = ['alpacadatav1/Q.GOOG']

    conn = StreamConn(
        ALPACA_API_KEY,
        ALPACA_SECRET_KEY,
        base_url=URL('https://paper-api.alpaca.markets'),
        data_url=URL('https://data.alpaca.markets'),
        # data_url=URL('http://127.0.0.1:8765'),
        data_stream='polygon' if USE_POLYGON else 'alpacadatav1')

    @conn.on(r'^AM\..+$')
    async def on_minute_bars(conn, channel, bar):
        print('bars', bar)

    @conn.on(r'Q\..+')
    async def on_quotes(conn, channel, quote):
        print('quote', quote)

    @conn.on(r'T\..+')
    async def on_trades(conn, channel, trade):
        print('trade', trade)
from datetime import timedelta

import alpaca_trade_api
import faust
from alpaca_trade_api.common import URL
from faust import Worker

app = faust.App(
    'stock-app',
    broker='kafka://localhost:9092',
    value_serializer='json',
    store='rocksdb://',
    version=1,
)

ALPACA_BASE_URL = URL('https://paper-api.alpaca.markets')
alpaca_ws_url = URL('wss://data.alpaca.markets')
ALPACA_API_KEY = os.getenv('alpaca_key_id')
ALPACA_SECRET_KEY = os.getenv('alpaca_secret_key')

alpaca = alpaca_trade_api.REST(ALPACA_API_KEY,
                               ALPACA_SECRET_KEY,
                               ALPACA_BASE_URL,
                               api_version='v2')


class OHLCRecord(faust.Record, serializer='json'):
    Name: str
    datetime: str

    Open: float
Exemplo n.º 16
0
 def __init__(self, account: Account, base_url: str):
     super().__init__()
     self.client = REST(key_id=account.get_access_key(),
                        secret_key=account.get_secret_key(),
                        base_url=URL(base_url))
Exemplo n.º 17
0
import alpaca_trade_api as tradeapi
from alpaca_trade_api.common import URL

api = tradeapi.REST('PKCQ9FP8ICADEN6GXVMV',
                    'FcDJHcD5lgvYUySh7tSC4TZkwdl9NpLPMhfp6E15',
                    base_url=URL("https://paper-api.alpaca.markets"))

counter = 0
while True:
    try:
        api.submit_order('NVDA', 1, 'buy', 'market', 'day')
        counter = counter + 1
        print(counter, 'purchases processed')
    except Exception as e:
        pass
Exemplo n.º 18
0
 def __init__(self, api_key, api_secret):
     super().__init__(api_key, api_secret)
     self.base_url = URL('https://paper-api.alpaca.markets')
     self.alpaca_rest = alpaca_trade_api.REST(self.api_key,
                                              self.api_secret,
                                              base_url=self.base_url)
Exemplo n.º 19
0
 def __init__(self, api_key, api_secret):
     self.api_key = api_key
     self.api_secret = api_secret
     self.base_url = URL('https://api.alpaca.markets')
Exemplo n.º 20
0
import traceback

import Util

import alpaca_trade_api as tradeapi
from alpaca_trade_api.stream import Stream
from alpaca_trade_api.common import URL

ACCOUNT_STATUS_ACTIVE = "ACTIVE"
NANOSEC = 10**9

#core_domain = "https://api.alpaca.markets"
core_domain = "https://paper-api.alpaca.markets"
data_domain = "https://data.alpaca.markets"

conn = Stream(base_url=URL(core_domain), data_feed='iex')

async def on_minute_bars(bar):
    symbol = bar.symbol
    mins = 1

    # BIG TODO - TIME (mins) SHOULD NOT BE HARDCODED
    
    epsilon = 30
    bar_time = bar.timestamp / NANOSEC
    time_range_floor = (60 * mins - epsilon) + Core.prev_time[symbol]
    time_range_ceil  = (60 * mins + epsilon) + Core.prev_time[symbol]
    if time_range_floor < bar_time and bar_time < time_range_ceil:
        curr = bar.close
        change = curr - Core.prev_close[symbol]
        if change > 0: