diff --git a/testy/archive/alpacaGetHistoryBars.py b/testy/archive/alpacaGetHistoryBars.py index 6de3710..32700b0 100644 --- a/testy/archive/alpacaGetHistoryBars.py +++ b/testy/archive/alpacaGetHistoryBars.py @@ -7,35 +7,38 @@ import time from alpaca.data import Quote, Trade, Snapshot, Bar from alpaca.data.models import BarSet, QuoteSet, TradeSet from alpaca.data.timeframe import TimeFrame -import mplfinance as mpf +# import mplfinance as mpf import pandas as pd - +from v2realbot.utils.utils import zoneNY +from v2realbot.config import ACCOUNT1_PAPER_API_KEY, ACCOUNT1_PAPER_SECRET_KEY parametry = {} # no keys required #client = CryptoHistoricalDataClient() -client = StockHistoricalDataClient(API_KEY, SECRET_KEY, raw_data=False) +client = StockHistoricalDataClient(ACCOUNT1_PAPER_API_KEY, ACCOUNT1_PAPER_SECRET_KEY, raw_data=False) datetime_object_from = datetime.datetime(2023, 2, 27, 18, 51, 38, tzinfo=datetime.timezone.utc) datetime_object_to = datetime.datetime(2023, 2, 27, 21, 51, 39, tzinfo=datetime.timezone.utc) -bar_request = StockBarsRequest(symbol_or_symbols="BAC",timeframe=TimeFrame.Hour, start=datetime_object_from, end=datetime_object_to, feed=DataFeed.SIP) +bar_request = StockBarsRequest(symbol_or_symbols="BAC",timeframe=TimeFrame.Minute, start=datetime_object_from, end=datetime_object_to, feed=DataFeed.SIP) -bars = client.get_stock_bars(bar_request).df +# bars = client.get_stock_bars(bar_request).df + +bars = client.get_stock_bars(bar_request) #bars = bars.drop(['symbol']) #print(bars.df.close) -bars = bars.tz_convert('America/New_York') -print(bars) -print(bars.df.columns) +#bars = bars.tz_convert('America/New_York') +print(bars.data["BAC"]) +#print(bars.df.columns) #Index(['open', 'high', 'low', 'close', 'volume', 'trade_count', 'vwap'], dtype='object') -bars.df.set_index('timestamp', inplace=True) +# bars.df.set_index('timestamp', inplace=True) -mpf.plot(bars.df, # the dataframe containing the OHLC (Open, High, Low and Close) data - type='candle', # use candlesticks - volume=True, # also show the volume - mav=(3,6,9), # use three different moving averages - figratio=(3,1), # set the ratio of the figure - style='yahoo', # choose the yahoo style - title='Prvni chart'); +# mpf.plot(bars.df, # the dataframe containing the OHLC (Open, High, Low and Close) data +# type='candle', # use candlesticks +# volume=True, # also show the volume +# mav=(3,6,9), # use three different moving averages +# figratio=(3,1), # set the ratio of the figure +# style='yahoo', # choose the yahoo style +# title='Prvni chart'); # #vrací se list od dict # print(bars["BAC"]) diff --git a/v2realbot/__pycache__/config.cpython-310.pyc b/v2realbot/__pycache__/config.cpython-310.pyc index db8f7b6..63e3332 100644 Binary files a/v2realbot/__pycache__/config.cpython-310.pyc and b/v2realbot/__pycache__/config.cpython-310.pyc differ diff --git a/v2realbot/common/__pycache__/model.cpython-310.pyc b/v2realbot/common/__pycache__/model.cpython-310.pyc index 65d4564..3759e12 100644 Binary files a/v2realbot/common/__pycache__/model.cpython-310.pyc and b/v2realbot/common/__pycache__/model.cpython-310.pyc differ diff --git a/v2realbot/common/model.py b/v2realbot/common/model.py index 1d4151b..21cbaaa 100644 --- a/v2realbot/common/model.py +++ b/v2realbot/common/model.py @@ -72,6 +72,7 @@ class RunnerView(BaseModel): run_name: Optional[str] = None run_note: Optional[str] = None run_account: Account + run_symbol: Optional[str] = None run_trade_count: Optional[int] = 0 run_profit: Optional[float] = 0 run_positions: Optional[int] = 0 @@ -85,6 +86,7 @@ class Runner(BaseModel): run_started: Optional[datetime] = None run_mode: Mode run_account: Account + run_symbol: Optional[str] = None run_name: Optional[str] = None run_note: Optional[str] = None run_trade_count: Optional[int] @@ -98,6 +100,33 @@ class Runner(BaseModel): run_pause_ev: Optional[object] = None run_stop_ev: Optional[object] = None + +class Bar(BaseModel): + """Represents one bar/candlestick of aggregated trade data over a specified interval. + + Attributes: + symbol (str): The ticker identifier for the security whose data forms the bar. + timestamp (datetime): The closing timestamp of the bar. + open (float): The opening price of the interval. + high (float): The high price during the interval. + low (float): The low price during the interval. + close (float): The closing price of the interval. + volume (float): The volume traded over the interval. + trade_count (Optional[float]): The number of trades that occurred. + vwap (Optional[float]): The volume weighted average price. + exchange (Optional[float]): The exchange the bar was formed on. + """ + + symbol: str + timestamp: datetime + open: float + high: float + low: float + close: float + volume: float + trade_count: Optional[float] + vwap: Optional[float] + class Order(BaseModel): id: UUID submitted_at: datetime @@ -130,6 +159,7 @@ class RunArchive(BaseModel): id: UUID #id of running strategy (stratin/runner) strat_id: UUID + symbol: str name: str note: Optional[str] = None started: datetime diff --git a/v2realbot/config.py b/v2realbot/config.py index a272a83..376d9fa 100644 --- a/v2realbot/config.py +++ b/v2realbot/config.py @@ -3,7 +3,7 @@ from v2realbot.enums.enums import Mode, Account, FillCondition from appdirs import user_data_dir #no print in console -QUIET_MODE = False +QUIET_MODE = True #how many consecutive trades with the fill price are necessary for LIMIT fill to happen in backtesting #0 - optimistic, every knot high will fill the order #N - N consecutive trades required diff --git a/v2realbot/controller/services.py b/v2realbot/controller/services.py index ea9905f..59e1cd6 100644 --- a/v2realbot/controller/services.py +++ b/v2realbot/controller/services.py @@ -2,8 +2,9 @@ from typing import Any, List from uuid import UUID, uuid4 import pickle from alpaca.data.historical import StockHistoricalDataClient -from alpaca.data.requests import StockTradesRequest +from alpaca.data.requests import StockTradesRequest, StockBarsRequest from alpaca.data.enums import DataFeed +from alpaca.data.timeframe import TimeFrame from v2realbot.enums.enums import RecordType, StartBarAlign, Mode, Account from v2realbot.common.model import StrategyInstance, Runner, RunRequest, RunArchive, RunArchiveDetail from v2realbot.utils.utils import AttributeDict, zoneNY, dict_replace_value, Store, parse_toml_string, json_serial @@ -365,6 +366,7 @@ def run_stratin(id: UUID, runReq: RunRequest): run_started = datetime.now(zoneNY), run_pause_ev = pe, run_name = name, + run_symbol = symbol, run_note = runReq.note, run_stop_ev = se, run_thread = vlakno, @@ -409,6 +411,7 @@ def archive_runner(runner: Runner, strat: StrategyInstance): strat_id = runner.id, name=runner.run_name, note=runner.run_note, + symbol=runner.run_symbol, started=runner.run_started, stopped=runner.run_stopped, mode=runner.run_mode, @@ -463,6 +466,19 @@ def get_archived_runner_details_byID(id: UUID): else: return 0, res +#returns b +def get_alpaca_history_bars(symbol: str, datetime_object_from: datetime, datetime_object_to: datetime, timeframe: TimeFrame): + """Returns Bar object + """ + try: + client = StockHistoricalDataClient(ACCOUNT1_LIVE_API_KEY, ACCOUNT1_LIVE_SECRET_KEY, raw_data=False) + #datetime_object_from = datetime(2023, 2, 27, 18, 51, 38, tzinfo=datetime.timezone.utc) + #datetime_object_to = datetime(2023, 2, 27, 21, 51, 39, tzinfo=datetime.timezone.utc) + bar_request = StockBarsRequest(symbol_or_symbols=symbol,timeframe=timeframe, start=datetime_object_from, end=datetime_object_to, feed=DataFeed.SIP) + bars = client.get_stock_bars(bar_request) + return 0, bars.data[symbol] + except Exception as e: + return -2, str(e) # change_archived_runner # delete_archived_runner_details diff --git a/v2realbot/main.py b/v2realbot/main.py index 23537b2..12391e7 100644 --- a/v2realbot/main.py +++ b/v2realbot/main.py @@ -2,6 +2,7 @@ import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from v2realbot.enums.enums import Mode, Account from v2realbot.config import WEB_API_KEY +from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from datetime import datetime #from icecream import install, ic import os @@ -12,7 +13,7 @@ from fastapi.security import APIKeyHeader import uvicorn from uuid import UUID import v2realbot.controller.services as cs -from v2realbot.common.model import StrategyInstance, RunnerView, RunRequest, Trade, RunArchive, RunArchiveDetail +from v2realbot.common.model import StrategyInstance, RunnerView, RunRequest, Trade, RunArchive, RunArchiveDetail, Bar from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, HTTPException, status, WebSocketException, Cookie, Query from fastapi.responses import HTMLResponse, FileResponse from fastapi.staticfiles import StaticFiles @@ -299,6 +300,15 @@ def _get_archived_runner_details_byID(runner_id) -> RunArchiveDetail: else: raise HTTPException(status_code=404, detail=f"No runner with id: {runner_id} a {set}") +#get alpaca history bars +@app.get("/history_bars/", dependencies=[Depends(api_key_auth)]) +def _get_alpaca_history_bars(symbol: str, datetime_object_from: datetime, datetime_object_to: datetime, timeframe_amount: int, timeframe_unit: TimeFrameUnit) -> list[Bar]: + res, set =cs.get_alpaca_history_bars(symbol, datetime_object_from, datetime_object_to, TimeFrame(amount=timeframe_amount,unit=timeframe_unit)) + if res == 0: + return set + else: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"No data found") + #join cekej na dokonceni vsech for i in cs.db.runners: diff --git a/v2realbot/static/index.html b/v2realbot/static/index.html index b9bc884..0fbd44d 100644 --- a/v2realbot/static/index.html +++ b/v2realbot/static/index.html @@ -1,37 +1,57 @@ - - + + + + + + V2realbot - - + + + + + + + + + + + + + + + -
+
- -
Status: Not connected
-