OlympusTrader.broker package¶
Submodules¶
OlympusTrader.broker.alpaca_broker module¶
- class OlympusTrader.broker.alpaca_broker.AlpacaBroker(paper: bool, feed: DataFeed = DataFeed.IEX, verbose: int = 0, **kwargs)¶
Bases:
BaseBroker- HISTORICAL_DATA: dict[str, dict[Literal['trade', 'quote', 'bar', 'news', 'signals'], DataFrame]] = {}¶
- cancel_order(order_id)¶
Cancel an order by order_id
- async closeStream(assetStreams)¶
- async closeTradeStream()¶
Close the trade stream
- close_all_positions()¶
Close all open positions and cancel all open orders
- close_position(symbol, qty=None, percent=None)¶
Close a position by symbol
- crypto_client: CryptoHistoricalDataClient = None¶
- crypto_stream_client: CryptoDataStream = None¶
- execute_insight_order(insight: Insight, asset: IAsset) IOrder | None¶
Manage insight order by planing entry and exit orders for a given insight
- format_on_bar(bar: Bar | DataFrame | Series)¶
Format stream bar data to { symbol: str, bar: -> open, high, low, close, volume} - (data={}, index=MultiIndex[(str, pd.Timestamp), names=[‘symbol’, ‘timestamp’]], columns=[‘open’, ‘high’, ‘low’, ‘close’, ‘volume’]):
- format_on_quote(quote: Quote)¶
Format stream quote data
- format_on_trade_update(trade: TradeUpdate)¶
Format stream Trade Order data and event
- get_account()¶
Get account information
- get_history(asset: ~OlympusTrader.broker.interfaces.IAsset, start: <module 'datetime' from '/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/datetime.py'>, end: <module 'datetime' from '/home/docs/.asdf/installs/python/3.12.10/lib/python3.12/datetime.py'>, resolution: ~OlympusTrader.utils.timeframe.ITimeFrame)¶
Get historical data for a given asset open, high, low, close, volume
- get_order(order_id)¶
Get order by order_id
- get_orders()¶
Get all orders
- get_position(symbol)¶
Get position by symbol
- get_positions()¶
Get all open positions
- get_ticker_info(symbol)¶
Get ticker information by symbol
- async startTradeStream(callback: Awaitable)¶
Listen to trades and order updates and call the callback function with the data
- stock_client: StockHistoricalDataClient = None¶
- stock_stream_client: StockDataStream = None¶
- async streamMarketData(callback: Awaitable, assetStreams)¶
Listen to market data and call the callback function with the data
- trade_stream_client: TradingStream = None¶
- trading_client: TradingClient = None¶
OlympusTrader.broker.base_broker module¶
- class OlympusTrader.broker.base_broker.BaseBroker(name: ISupportedBrokers = ISupportedBrokers.BASE, paper: bool = True, feed: str | None = None, verbose: int = 0)¶
Bases:
ABC- BACKTEST_FlOW_CONTROL: AsyncStepCoordinator = <OlympusTrader.utils.asyncStepCoordinator.AsyncStepCoordinator object>¶
- DataFeed: str | None¶
- LOGGER: Logger = None¶
- NAME: ISupportedBrokers = 'BaseBroker'¶
- PAPER: bool¶
- RUNNING_MARKET_STREAM: bool = False¶
- RUNNING_TRADE_STREAM: bool = False¶
- VERBOSE: int = 0¶
- abstractmethod cancel_order(order_id: str) str | None¶
Cancel an order by order_id
- abstractmethod async closeStream(assetStreams: List[IMarketDataStream])¶
- abstractmethod async closeTradeStream()¶
Close the trade stream
- abstractmethod close_all_positions()¶
Close all open positions and cancel all open orders
- abstractmethod close_position(symbol: str, qty: float | None = None, percent: float | None = None) IOrder | None¶
Close a position by symbol
- abstractmethod execute_insight_order(insight: Insight, asset: IAsset) IOrder | None¶
Manage insight order by planing entry and exit orders for a given insight
- abstractmethod format_on_bar(bar: Any, symbol: str | None = None) DataFrame | None¶
Format stream bar data to { symbol: str, bar: -> open, high, low, close, volume} - (data={}, index=MultiIndex[(str, pd.Timestamp), names=[‘symbol’, ‘timestamp’]], columns=[‘open’, ‘high’, ‘low’, ‘close’, ‘volume’]):
- abstractmethod format_on_trade_update(trade: Any) tuple[IOrder, ITradeUpdateEvent]¶
Format stream Trade Order data and event
- property get_current_time: datetime¶
Get the current broker time
- abstractmethod get_history(asset: ~OlympusTrader.broker.interfaces.IAsset, start=datetime.datetime(2025, 12, 9, 12, 9, 34, 424562), end=datetime.datetime(2025, 12, 16, 12, 9, 34, 424568), resolution=<OlympusTrader.utils.timeframe.ITimeFrame object>) DataFrame¶
Get historical data for a given asset open, high, low, close, volume
- abstractmethod async startTradeStream(callback: Awaitable)¶
Listen to trades and order updates and call the callback function with the data
- abstractmethod async streamMarketData(callback: Awaitable, assetStreams: List[IMarketDataStream])¶
Listen to market data and call the callback function with the data
- supportedFeatures: ISupportedBrokerFeatures¶
OlympusTrader.broker.interfaces module¶
- class OlympusTrader.broker.interfaces.IAccount(account_id: str, equity: float, cash: float, currency: str, buying_power: float, shorting_enabled: bool, leverage: float)¶
Bases:
object- account_id: str¶
- buying_power: float¶
- cash: float¶
- currency: str¶
- equity: float¶
- leverage: float¶
- shorting_enabled: bool¶
- class OlympusTrader.broker.interfaces.IAccountState¶
Bases:
TypedDict
- class OlympusTrader.broker.interfaces.IAsset¶
Bases:
TypedDict- asset_type: Literal['stock', 'crypto', 'forex']¶
- contract_size: NotRequired[int]¶
- exchange: str¶
- fractionable: bool¶
- id: str¶
- marginable: bool¶
- max_order_size: NotRequired[float]¶
- min_order_size: float¶
- min_price_increment: float¶
- name: str¶
- price_base: NotRequired[int]¶
- quantity_base: NotRequired[int]¶
- shortable: bool¶
- status: Literal['active', 'inactive']¶
- symbol: str¶
- tradable: bool¶
- class OlympusTrader.broker.interfaces.IOrder¶
Bases:
TypedDict- created_at: datetime¶
- filled_at: datetime | None¶
- filled_price: float | None¶
- filled_qty: float¶
- legs: IOrderLegs | None¶
- limit_price: float¶
- order_class: IOrderClass¶
- order_id: str | UUID¶
- qty: float¶
- side: IOrderSide¶
- status: ITradeUpdateEvent¶
- stop_price: float | None¶
- submitted_at: datetime¶
- time_in_force: ITimeInForce¶
- type: IOrderType¶
- updated_at: datetime¶
- class OlympusTrader.broker.interfaces.IOrderClass(*values)¶
Bases:
Enum- BRACKET = 'bracket'¶
- OCO = 'oco'¶
- OTO = 'oto'¶
- SIMPLE = 'simple'¶
- TRO = 'tro'¶
- class OlympusTrader.broker.interfaces.IOrderLeg¶
Bases:
TypedDict- created_at: datetime¶
- filled_at: datetime | None¶
- filled_price: float | None¶
- limit_price: float¶
- order_class: IOrderClass¶
- order_id: str¶
- status: ITradeUpdateEvent¶
- submitted_at: datetime¶
- type: IOrderType¶
- updated_at: datetime¶
- class OlympusTrader.broker.interfaces.IOrderLegs¶
Bases:
TypedDict
- class OlympusTrader.broker.interfaces.IOrderRequest¶
Bases:
TypedDict- limit_price: float¶
- order_class: IOrderClass¶
- qty: float¶
- side: IOrderSide¶
- stop_loss: float¶
- symbol: str¶
- take_profit: float¶
- time_in_force: ITimeInForce¶
- trail_price: float¶
- type: IOrderType¶
- class OlympusTrader.broker.interfaces.IOrderSide(*values)¶
Bases:
EnumOrder Side.
- BUY = 'Long'¶
- SELL = 'Short'¶
- class OlympusTrader.broker.interfaces.IOrderType(*values)¶
Bases:
EnumOrder Type.
- LIMIT = 'Limit'¶
- MARKET = 'Market'¶
- STOP = 'Stop'¶
- STOP_LIMIT = 'Stop_limit'¶
- TRAILING_STOP = 'Trailing_stop'¶
- class OlympusTrader.broker.interfaces.IPosition¶
Bases:
TypedDict- avg_entry_price: float¶
- cost_basis: float¶
- current_price: float¶
- margin_required: float | None = 0¶
BackTesting param: The margin required for leveraged positions
- market_value: float¶
- qty: float¶
- side: IOrderSide¶
- unrealized_pl: float¶
- class OlympusTrader.broker.interfaces.IQuote¶
Bases:
TypedDict- ask: float¶
- ask_size: float¶
- bid: float¶
- bid_size: float¶
- symbol: str¶
- timestamp: datetime¶
- volume: float¶
- class OlympusTrader.broker.interfaces.ISupportedBrokerFeatures(barDataStreaming: bool = True, tradeEventStreaming: bool = True, featuredBarDataStreaming: bool = True, submitOrder: bool = True, maxOrderValue: float = None, cancelOrder: bool = True, closePosition: bool = True, getAccount: bool = True, getPosition: bool = True, getPositions: bool = True, getHistory: bool = True, getQuote: bool = True, getTickerInfo: bool = True, leverage: bool = True, shorting: bool = True, margin: bool = True, bracketOrders: bool = True, trailingStop: bool = True)¶
Bases:
objectSupported Broker Features.
- barDataStreaming: bool = True¶
- bracketOrders: bool = True¶
- cancelOrder: bool = True¶
- closePosition: bool = True¶
- featuredBarDataStreaming: bool = True¶
- getAccount: bool = True¶
- getHistory: bool = True¶
- getPosition: bool = True¶
- getPositions: bool = True¶
- getQuote: bool = True¶
- getTickerInfo: bool = True¶
- leverage: bool = True¶
- margin: bool = True¶
- maxOrderValue: float = None¶
- shorting: bool = True¶
- submitOrder: bool = True¶
- tradeEventStreaming: bool = True¶
- trailingStop: bool = True¶
- class OlympusTrader.broker.interfaces.ISupportedBrokers(*values)¶
Bases:
EnumSupported Brokers.
- ALPACA = 'AlpacaBroker'¶
- BASE = 'BaseBroker'¶
- CCXT = 'CCXTBroker'¶
- MT5 = 'MetaTrader5Broker'¶
- PAPER = 'PaperBrokerr'¶
- T212 = 'TradingTwoOneTwoBroker'¶
- TV = 'TradingViewBroker'¶
- class OlympusTrader.broker.interfaces.ITimeInForce(*values)¶
Bases:
Enum- DAY = 'day'¶
- FOK = 'fok'¶
- GTC = 'gtc'¶
- IOC = 'ioc'¶
- OPG = 'opg'¶
- class OlympusTrader.broker.interfaces.ITradeUpdate(order: IOrder, event: ITradeUpdateEvent)¶
Bases:
object
- class OlympusTrader.broker.interfaces.ITradeUpdateEvent(*values)¶
Bases:
EnumTrade Update Event.
- ACCEPTED = 'accepted'¶
- CANCELED = 'canceled'¶
- CLOSED = 'closed'¶
- EXPIRED = 'expired'¶
- FILLED = 'fill'¶
- NEW = 'new'¶
- PARTIAL_FILLED = 'partial_filled'¶
- PENDING_NEW = 'pending_new'¶
- REJECTED = 'rejected'¶
- REPLACED = 'replaced'¶
OlympusTrader.broker.mt5_broker module¶
OlympusTrader.broker.paper_broker module¶
- class OlympusTrader.broker.paper_broker.PaperBroker(cash: float = 100000.0, start_date: date = None, end_date: date = None, leverage: int = 4, currency: str = 'GBP', allow_short: bool = True, mode: IStrategyMode = IStrategyMode.BACKTEST, feed: Literal['yf', 'eod'] = 'yf', feedDelay: int = 0, verbose: int = 0)¶
Bases:
BaseBroker- CurrentTime: datetime = None¶
- END_DATE: datetime = None¶
- FeedDelay: int = 0¶
- HISTORICAL_DATA: dict[str, dict[Literal['trade', 'quote', 'bar', 'news', 'signals'], DataFrame]] = {}¶
- LEVERAGE: int = 4¶
- MODE: IStrategyMode = 'Backtest'¶
- PreviousTime: datetime = None¶
- STARTING_CASH: float = 100000.0¶
- START_DATE: datetime = None¶
- VERBOSE: int = 0¶
- cancel_order(order_id: str)¶
Cancel an order by order_id
- async closeStream(assetStreams: List[IMarketDataStream])¶
- async closeTradeStream()¶
Close the trade stream
- close_all_positions()¶
Close all open positions and cancel all open orders
- close_position(symbol: str, qty=None, percent=None)¶
Close a position by symbol
- execute_insight_order(insight: Insight, asset: IAsset)¶
Manage insight order by planing entry and exit orders for a given insight
- export_trade_log(filename='trade_log.csv')¶
- export_vbt_signals(asset, filename='vbt_signals.csv')¶
- format_on_bar(bar, symbol: str)¶
Format stream bar data to { symbol: str, bar: -> open, high, low, close, volume} - (data={}, index=MultiIndex[(str, pd.Timestamp), names=[‘symbol’, ‘timestamp’]], columns=[‘open’, ‘high’, ‘low’, ‘close’, ‘volume’]):
- format_on_quote(quote)¶
Format stream quote data
- format_on_trade_update(trade: ITradeUpdate)¶
Format stream Trade Order data and event
- get_VBT_results(timeFrame: ITimeFrame) dict[str, Portfolio]¶
returns the backtest results from Vector BT - profit and loss, profit and loss percentage, number of orders executed and filled, cag sharp rattio, percent win. etc.
- get_account()¶
Get account information
- property get_current_time: datetime¶
Get the current broker time
- get_history(asset: IAsset, start: datetime, end: datetime, resolution: ITimeFrame, shouldDelta: bool = True) DataFrame¶
Get historical data for a given asset open, high, low, close, volume
- get_order(order_id)¶
Get order by order_id
- get_orders()¶
Get all orders
- get_position(symbol: str, mode: Literal['all', 'active'] = 'active')¶
Get position by symbol
- get_positions(mode: Literal['all', 'active'] = 'active')¶
Get all open positions
- get_ticker_info(symbol: str)¶
Get ticker information by symbol
- async processActiveOrders(callback: Awaitable)¶
Process active orders that are either filled or partially filled. This method checks for take profit and stop loss conditions and updates the order status accordingly. It also updates the position information and calculates the P&L for filled positions.
- async processCanceledOrders(callback: Awaitable)¶
Process canceled orders that are either canceled or pending new. This method cancels pending orders and removes it from the PENDING_ORDERS and UPDATE_ORDERS.
- async processClosedOrders(callback: Awaitable)¶
Process closed orders that are either filled or closed. This method updates the order status to CLOSED and sets the stop price to the current bar’s open price. It also updates the filled quantity and filled at time.
- async processPendingOrders(callback: Awaitable)¶
Process pending orders that are either new or accepted. This method checks the current market conditions and fills market orders immediately. It also processes limit orders based on the current bar’s high and low prices.
- async processUpdateOrders(callback: Awaitable)¶
- setCurrentTime(time: datetime)¶
- async startTradeStream(callback)¶
Listen to trades and order updates and call the callback function with the data
- async streamMarketData(callback, assetStreams)¶
Listen to market data and call the async callback with the data.
Important: callback must be an async callable: async def callback(bar, timeframe=…).
- update_account_balance()¶
- update_account_history()¶
- update_order(order_id: str, price: float, qty: float)¶
Update an order by order_id