Skip to content

minitrade.broker¤

minitrade.broker.base ¤

Broker ¤

Broker(account: BrokerAccount)

Bases: ABC

Broker is a base class that manages the connection to a broker system. Extend this class to add a concrete implementation to talk to a particular broker.

Parameters:

Name Type Description Default
account BrokerAccount

a BrokerAccount instance

required

AVAILABLE_BROKERS class-attribute instance-attribute ¤

AVAILABLE_BROKERS = {'IB': 'Interactive Brokers', 'Manual': 'Manual Trader'}

A dict mapping from broker alias to broker user-friendly name for supported brokers.

cancel_order abstractmethod ¤

cancel_order(plan: TradePlan, order: RawOrder = None) -> bool

Cancel a specific order or all pending orders of a trade plan if order is None.

Parameters:

Name Type Description Default
plan TradePlan

A trade plan

required
order RawOrder

A RawOrder to be cancelled

None

connect abstractmethod ¤

connect()

Set up a working connection to the broker.

Raises:

Type Description
ConnectionError

If a working connection can't be established.

disconnect abstractmethod ¤

disconnect() -> None

Disconnect from broker and release any resources.

download_orders abstractmethod ¤

download_orders() -> DataFrame | None

Get recent orders at broker. RawOrder submitted creates a correspoing order on the broker side, which can have different status such as open, cancelled, error, etc.

This function is called immediately before and after order submission to get the most recent order information on the broker side. The orders returned should be persisted to database and can be used for display, order validation, statistics, and record keeping. Since order status can change over time, new status should overwrite past one.

The number of orders returned depends on the data availability of each broker.

Returns:

Type Description
DataFrame | None

A dataframe that contains recent order information

download_trades abstractmethod ¤

download_trades() -> DataFrame | None

Get recent trades at broker. Trades are completed orders.

This function is called immediately before and after order submission to get the most recent trade information on the broker side. The trades returned should be persisted to database and can be used for display, order validation, statistics, and record keeping. Trade info is usually final.

The number of trades returned depends on the data availability of particular broker.

Returns:

Type Description
DataFrame | None

A dataframe that contains recently finished trades

find_order abstractmethod ¤

find_order(order: RawOrder) -> dict

Get last known order status, not necessarily latest.

A subclass implementing this function only needs to look up orders from the database, instead of querying the broker directly, which can be slow. In scenarios where stale information can't be tolerated, download_orders() is always called before this function is invoked.

Parameters:

Name Type Description Default
order RawOrder

A RawOrder

required

Returns:

Type Description
dict

A dict that contains broker specific order infomation associated with the order,

dict

or None if no broker order is found.

find_trades abstractmethod ¤

find_trades(order: RawOrder) -> dict

Get trade information associated with the raw order.

A 'RawOrder' can be filled in multiple trades at different time and prices, therefore a list of trades may be returned.

A subclass implementing this function only needs to look up trades from the database, instead of querying the broker directly, which can be slow. In scenarios where stale information can't be tolerated, download_trades() is always called before this function is invoked.

Parameters:

Name Type Description Default
order RawOrder

A RawOrder

required

Returns:

Type Description
dict

A list of dict that contains broker specific trade infomation associated with the order,

dict

or None if no broker trade is found.

format_trades abstractmethod ¤

format_trades(orders: list[RawOrder]) -> list[dict]

Get broker specific trade status corresponding to the list of orders and format in dict like: { 'ticker': ..., 'entry_time': ..., 'size': ..., 'entry_price': ..., 'commission': ... }

Parameters:

Name Type Description Default
orders list[RawOrder]

A list of RawOrder

required

Returns:

Type Description
list[dict]

A list of completed trades with relevant information

get_account_info abstractmethod ¤

get_account_info() -> dict

Get broker account meta info

Returns:

Type Description
dict

A dict that contains broker specific account information

get_broker staticmethod ¤

get_broker(account: BrokerAccount) -> Broker

Create a broker connector for a account that specifies the type of broker and the login credentials.

Parameters:

Name Type Description Default
account BrokerAccount

A BrokerAccount instance

required

Returns:

Type Description
Broker

A Broker instance

Raises:

Type Description
AttributeError

If the type of broker is not supported

get_portfolio abstractmethod ¤

get_portfolio() -> DataFrame | None

Get account portfolio

Returns:

Type Description
DataFrame | None

A dataframe that contains broker specific portfolio infomation

is_ready abstractmethod ¤

is_ready() -> bool

Check if the broker connector has a working connection with the broker.

All calls interacting with the broker system should only be sent after is_ready return True.

Returns:

Type Description
bool

True if a connection to broker is ready, otherwise False

resolve_tickers abstractmethod ¤

resolve_tickers(ticker_css: str) -> dict[str, list]

Resolve generic tickers to broker specific ticker IDs.

Parameters:

Name Type Description Default
ticker_css str

A list of tickers formatted as a comma separated string

required

Returns:

Type Description
dict[str, list]

A dict mapping each generic ticker name to a list of broker ticker options. The format is like { TK1: [ {'id': id1, 'label': label1}, {'id': id2, 'label': label2} ], TK2: [ {'id': id1, 'label': label1} ], TK3: [] } where id is the broker specific ticker ID, label is a human readable string to help disambiguate the options.

submit_order abstractmethod ¤

submit_order(plan: TradePlan, order: RawOrder) -> str

Submit an order to the broker.

Parameters:

Name Type Description Default
plan TradePlan

A trade plan

required
order RawOrder

A RawOrder to be submitted

required

Returns:

Type Description
str

Broker assigned order ID if order is submitted successfully, otherwise None

BrokerAccount dataclass ¤

BrokerAccount(*, alias: str, broker: str, mode: str, username: str, password: str)

BrokerAccount describes a broker account, such as name, type, and login credentials.

alias instance-attribute ¤

alias: str

Account alias

broker instance-attribute ¤

broker: str

Broker alias as in Broker.AVAILABLE_BROKERS

mode instance-attribute ¤

mode: str

"Live" or "Paper". Note this is only a hint to help remember. Whether an account is live or paper depends on the account itself rather than this field.

password instance-attribute ¤

password: str

Account password

username instance-attribute ¤

username: str

Account username

delete ¤

delete() -> None

Delete broker account from database.

get_account staticmethod ¤

get_account(plan_or_alias: TradePlan | str) -> BrokerAccount

Look up a broker account from a broker account alias or the alias as specified in a TradePlan.

Parameters:

Name Type Description Default
plan_or_alias TradePlan | str

A trade plan or a broker account alias

required

Returns:

Type Description
BrokerAccount

A broker account, or None if the alias is invalid

list staticmethod ¤

list() -> list[BrokerAccount]

Return the list of available broker accounts.

Returns:

Type Description
list[BrokerAccount]

A list of zero or more broker accounts

save ¤

save() -> None

Save a broker account to database.

OrderValidator ¤

OrderValidator(plan: TradePlan)

OrderValidator is responsible for integrity checks on a raw order before it's submitted to broker.

validate ¤

validate(order: RawOrder)

Run a bunch of checks to ensure the raw order is valid.

For example, a valid order should:

  • have valid values for all its attributes
  • not be a duplicate of what has been submitted before
  • be timely

OrderValidatorLog dataclass ¤

OrderValidatorLog(*, id: str, order_id: str, order: str, result: str, exception: str | None = None, log_time: datetime)

OrderValidatorLog logs the results of order validation.

exception class-attribute instance-attribute ¤

exception: str | None = None

Exception that occurs during validation

id instance-attribute ¤

id: str

Validator run ID

log_time instance-attribute ¤

log_time: datetime

Log time

order instance-attribute ¤

order: str

Raw order in Json format

order_id instance-attribute ¤

order_id: str

Raw order ID

result instance-attribute ¤

result: str

Validation output