code
stringlengths
17
6.64M
def init_datasets() -> None: preprocess_enron() preprocess_ling() preprocess_sms() preprocess_spamassassin()
def train_val_test_split(df, train_size=0.8, has_val=True): 'Return a tuple (DataFrame, DatasetDict) with a custom train/val/split' if isinstance(train_size, int): train_size = (train_size / len(df)) df = df.sample(frac=1, random_state=0) (df_train, df_test) = train_test_split(df, test_size=(1...
class EvalOnTrainCallback(TrainerCallback): 'Custom callback to evaluate on the training set during training.' def __init__(self, trainer) -> None: super().__init__() self._trainer = trainer def on_epoch_end(self, args, state, control, **kwargs): if control.should_evaluate: ...
def get_trainer(model, dataset, tokenizer=None): 'Return a trainer object for transformer models.' def compute_metrics(y_pred): 'Computer metrics during training.' (logits, labels) = y_pred predictions = np.argmax(logits, axis=(- 1)) return evaluate.load('f1').compute(predicti...
def predict(trainer, model, dataset, tokenizer=None): 'Convert the predict function to specific classes to unify the API.' if (type(model).__name__ == 'SetFitModel'): return model(dataset['text']) elif ('T5' in type(model).__name__): predictions = trainer.predict(dataset) predictio...
def train_llms(seeds, datasets, train_sizes, test_set='test'): 'Train all the large language models.' for seed in list(seeds): set_seed(seed) for dataset_name in list(datasets): for train_size in train_sizes: scores = pd.DataFrame(index=list(LLMS.keys()), columns=(l...
def train_baselines(seeds, datasets, train_sizes, test_set='test'): 'Train all the baseline models.' init_nltk() for seed in list(seeds): set_seed(seed) for dataset_name in list(datasets): for train_size in train_sizes: scores = pd.DataFrame(index=list(MODELS.ke...
def init_nltk(): nltk.download('punkt') nltk.download('stopwords')
def tokenize_words(text): 'Tokenize words in text and remove punctuation' text = word_tokenize(str(text).lower()) text = [token for token in text if token.isalnum()] return text
def remove_stopwords(text): 'Remove stopwords from the text' text = [token for token in text if (token not in stopwords.words('english'))] return text
def stem(text): 'Stem the text (originate => origin)' text = [ps.stem(token) for token in text] return text
def transform(text): 'Tokenize, remove stopwords, stem the text' text = tokenize_words(text) text = remove_stopwords(text) text = stem(text) text = ' '.join(text) return text
def transform_df(df): 'Apply the transform function to the dataframe' df['transformed_text'] = df['text'].apply(transform) return df
def encode_df(df, encoder=None): 'Encode the features for training set' if hasattr(encoder, 'vocabulary_'): X = encoder.transform(df['transformed_text']).toarray() else: X = encoder.fit_transform(df['transformed_text']).toarray() y = df['label'].values return (X, y, encoder)
def tokenize(dataset, tokenizer): 'Tokenize dataset' def tokenization(examples): return tokenizer(examples['text'], padding='max_length', truncation=True) def tokenization_t5(examples, padding='max_length'): text = [('classify as ham or spam: ' + item) for item in examples['text']] ...
def set_seed(seed) -> None: 'Fix random seeds' random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
def plot_loss(experiment: str, dataset_name: str, model_name: str) -> None: 'Plot loss curve for LLMs.' log = pd.read_csv(f'outputs/csv/loss_{model_name}_{experiment}.csv') log = pd.DataFrame(log).iloc[:(- 1)] train_losses = log['train_loss'].dropna().values eval_losses = log['eval_loss'].dropna()...
def plot_scores(experiment: str, dataset_name: str) -> None: 'Plot scores as histogram.' scores = pd.read_csv(f'outputs/csv/{experiment}.csv', index_col=0) x = np.arange(len(scores)) width = 0.2 (fig, ax) = plt.subplots(figsize=(9, 3)) rects1 = ax.bar(x=(x - width), height=scores['f1'], width=...
def plot_pie_charts() -> None: 'Plot ham/spam distribution for each dataset.' dataset_names = ['ling', 'sms', 'spamassassin', 'enron'] (fig, axs) = plt.subplots(1, 4, figsize=(16, 4)) for (i, dataset_name) in enumerate(dataset_names): df = get_dataset(dataset_name) axs[i].pie(df['label...
def save_scores(experiment: str, index: str, values: dict) -> None: 'Log scores for individual models in the corresponding csv file' llms = ['BERT', 'RoBERTa', 'SetFit-MiniLM', 'SetFit-mpnet', 'FLAN-T5-small', 'FLAN-T5-base'] models = ['NB', 'LR', 'KNN', 'SVM', 'XGBoost', 'LightGBM'] Path(f'outputs/cs...
def run(config: Dict[(str, Any)], log_dir: str='', kernel_seed: int=0, kernel_random_state: Optional[np.random.RandomState]=None) -> Dict[(str, Any)]: '\n Wrapper function that enables to run one simulation.\n It does the following steps:\n - instantiation of the kernel\n - running of the simulation\n...
class Agent(): '\n Base Agent class\n\n Attributes:\n id: Must be a unique number (usually autoincremented).\n name: For human consumption, should be unique (often type + number).\n type: For machine aggregation of results, should be same for all agents\n following the same s...
class BaseGenerator(ABC, Generic[T]): '\n This is an abstract base class defining the interface for Generator objects in\n ABIDES. This class is not used directly and is instead inherited from child classes.\n\n Generators should produce an infinite amount of values.\n ' @abstractmethod def n...
class InterArrivalTimeGenerator(BaseGenerator[float], ABC): '\n General class for time generation. These generators are used to generates a delta time between currrent time and the next wakeup of the agent.\n ' pass
class ConstantTimeGenerator(InterArrivalTimeGenerator): '\n Generates constant delta time of length step_duration\n\n Arguments:\n step_duration: length of the delta time in ns\n ' def __init__(self, step_duration: float) -> None: self.step_duration: float = step_duration def nex...
class PoissonTimeGenerator(InterArrivalTimeGenerator): '\n Lambda must be specified either in second through lambda_time or seconds^-1\n through lambda_freq.\n\n Arguments:\n random_generator: configuration random generator\n lambda_freq: frequency (in s^-1)\n lambda_time: period (in...
class Kernel(): '\n ABIDES Kernel\n\n Arguments:\n agents: List of agents to include in the simulation.\n start_time: Timestamp giving the start time of the simulation.\n stop_time: Timestamp giving the end time of the simulation.\n default_computation_delay: time penalty applied...
class LatencyModel(): "\n LatencyModel provides a latency model for messages in the ABIDES simulation. The\n default is a cubic model as described herein.\n\n Arguments:\n random_state: An initialized ``np.random.RandomState`` object.\n min_latency: A 2-D numpy array of pairwise minimum lat...
@dataclass class Message(): 'The base Message class no longer holds envelope/header information, however any\n desired information can be placed in the arbitrary body.\n\n Delivery metadata is now handled outside the message itself.\n\n The body may be overridden by specific message type subclasses.\n ...
@dataclass class MessageBatch(Message): '\n Helper used for batching multiple messages being sent by the same sender to the same\n destination together. If very large numbers of messages are being sent this way,\n using this class can help performance.\n ' messages: List[Message]
@dataclass class WakeupMsg(Message): '\n Empty message sent to agents when woken up.\n ' pass
def subdict(d: Dict[(str, Any)], keys: List[str]) -> Dict[(str, Any)]: '\n Returns a dictionnary with only the keys defined in the keys list\n Arguments:\n - d: original dictionnary\n - keys: list of keys to keep\n Returns:\n - dictionnary with only the subset of keys\n ' retu...
def restrictdict(d: Dict[(str, Any)], keys: List[str]) -> Dict[(str, Any)]: '\n Returns a dictionnary with only the intersections of the keys defined in the keys list and the keys in the o\n Arguments:\n - d: original dictionnary\n - keys: list of keys to keep\n Returns:\n - dictionn...
def custom_eq(a: Any, b: Any) -> bool: 'returns a==b or True if both a and b are null' return ((a == b) | ((a != a) & (b != b)))
def get_wake_time(open_time, close_time, a=0, b=1): '\n Draw a time U-quadratically distributed between open_time and close_time.\n\n For details on U-quadtratic distribution see https://en.wikipedia.org/wiki/U-quadratic_distribution.\n ' def cubic_pow(n: float) -> float: 'Helper function: r...
def fmt_ts(timestamp: NanosecondTime) -> str: '\n Converts a timestamp stored as nanoseconds into a human readable string.\n ' return pd.Timestamp(timestamp, unit='ns').strftime('%Y-%m-%d %H:%M:%S')
def str_to_ns(string: str) -> NanosecondTime: '\n Converts a human readable time-delta string into nanoseconds.\n\n Arguments:\n string: String to convert into nanoseconds. Uses Pandas to do this.\n\n Examples:\n - "1s" -> 1e9 ns\n - "1min" -> 6e10 ns\n - "00:00:30" -> 3e10 ns...
def datetime_str_to_ns(string: str) -> NanosecondTime: '\n Takes a datetime written as a string and returns in nanosecond unix timestamp.\n\n Arguments:\n string: String to convert into nanoseconds. Uses Pandas to do this.\n ' return pd.Timestamp(string).value
def ns_date(ns_datetime: NanosecondTime) -> NanosecondTime: '\n Takes a datetime in nanoseconds unix timestamp and rounds it to that day at 00:00.\n\n Arguments:\n ns_datetime: Nanosecond time value to round.\n ' return (ns_datetime - (ns_datetime % ((24 * 3600) * int(1000000000.0))))
def parse_logs_df(end_state: dict) -> pd.DataFrame: '\n Takes the end_state dictionnary returned by an ABIDES simulation goes through all\n the agents, extracts their log, and un-nest them returns a single dataframe with the\n logs from all the agents warning: this is meant to be used for debugging and\n...
def input_sha_wrapper(func: Callable) -> Callable: '\n compute a sha for the function call by looking at function name and inputs for the call\n ' def inner(*args, **kvargs): argspec = inspect.getfullargspec(func) index_first_kv = (len(argspec.args) - (len(argspec.defaults) if (argspec....
def cache_wrapper(func: Callable, cache_dir='cache/', force_recompute=False) -> Callable: '\n local caching decorator\n checks the functional call sha is only there is specified directory\n ' def inner(*args, **kvargs): if (not os.path.isdir(cache_dir)): os.mkdir(cache_dir) ...
def test_constant_time_generator(): g = ConstantTimeGenerator(10) assert (g.next() == 10) assert (g.mean() == 10)
def test_poisson_time_generator(): g = PoissonTimeGenerator(np.random.RandomState(), lambda_freq=10) assert (g.mean() == 0.1) assert (abs(((np.mean([g.next() for _ in range(100000)]) / 1000000000.0) - 0.1)) < 0.001) g = PoissonTimeGenerator(np.random.RandomState(), lambda_time=10) assert (g.mean()...
def test_str_to_ns(): assert (str_to_ns('0') == 0) assert (str_to_ns('1') == 1) assert (str_to_ns('1us') == 1000.0) assert (str_to_ns('1ms') == 1000000.0) assert (str_to_ns('1s') == 1000000000.0) assert (str_to_ns('1sec') == 1000000000.0) assert (str_to_ns('1second') == 1000000000.0) a...
class AbidesGymCoreEnv(gym.Env, ABC): '\n Abstract class for core gym to inherit from to create usable specific ABIDES Gyms\n ' def __init__(self, background_config_pair: Tuple[(Callable, Optional[Dict[(str, Any)]])], wakeup_interval_generator: InterArrivalTimeGenerator, state_buffer_length: int, first...
class SubGymMarketsDailyInvestorEnv_v0(AbidesGymMarketsEnv): '\n Daily Investor V0 environnement. It defines one of the ABIDES-Gym-markets environnement.\n This environment presents an example of the classic problem where an investor tries to make money buying and selling a stock through-out a single day.\n...
class AbidesGymMarketsEnv(AbidesGymCoreEnv, ABC): '\n Abstract class for markets gym to inherit from to create usable specific ABIDES Gyms\n\n Arguments:\n - background_config_pair: tuple consisting in the background builder function and the inputs to use\n - wakeup_interval_generator: generat...
class MyCallbacks(DefaultCallbacks): '\n Class that defines callbacks for the execution environment\n ' def on_episode_start(self, *, worker: RolloutWorker, base_env: BaseEnv, policies: Dict[(str, Policy)], episode: MultiAgentEpisode, env_index: int, **kwargs): 'Callback run on the rollout work...
class SubGymMarketsExecutionEnv_v0(AbidesGymMarketsEnv): '\n Execution V0 environnement. It defines one of the ABIDES-Gym-markets environnement.\n This environment presents an example of the algorithmic orderexecution problem.\n The agent has either an initial inventory of the stocks it tries to trade ou...
class CoreGymAgent(Agent, ABC): '\n Abstract class to inherit from to create usable specific ABIDES Gym Experiemental Agents\n ' @abstractmethod def update_raw_state(self) -> None: raise NotImplementedError @abstractmethod def get_raw_state(self) -> deque: raise NotImplemen...
class FinancialGymAgent(CoreBackgroundAgent, CoreGymAgent): "\n Gym experimental agent class. This agent is the interface between the ABIDES simulation and the ABIDES Gym environments.\n\n Arguments:\n - id: agents id in the simulation\n - symbol: ticker of the traded asset\n - starting...
class CoreBackgroundAgent(TradingAgent): def __init__(self, id: int, symbol: str, starting_cash: int, subscribe_freq: int=int(100000000.0), lookback_period: Optional[int]=None, subscribe: bool=True, subscribe_num_levels: Optional[int]=None, wakeup_interval_generator: InterArrivalTimeGenerator=ConstantTimeGenerat...
class MomentumAgent(TradingAgent): '\n Simple Trading Agent that compares the 20 past mid-price observations with the 50 past observations and places a\n buy limit order if the 20 mid-price average >= 50 mid-price average or a\n sell limit order if the 20 mid-price average < 50 mid-price average\n ' ...
class ExchangeAgent(FinancialAgent): '\n The ExchangeAgent expects a numeric agent id, printable name, agent type, timestamp\n to open and close trading, a list of equity symbols for which it should create order\n books, a frequency at which to archive snapshots of its order books, a pipeline\n delay ...
class FinancialAgent(Agent): "\n The FinancialAgent class contains attributes and methods that should be available to\n all agent types (traders, exchanges, etc) in a financial market simulation.\n\n To be honest, it mainly exists because the base Agent class should not have any\n finance-specific asp...
class AdaptiveMarketMakerAgent(TradingAgent): "This class implements a modification of the Chakraborty-Kearns `ladder` market-making strategy, wherein the\n the size of order placed at each level is set as a fraction of measured transacted volume in the previous time\n period.\n\n Can skew orders to size...
class NoiseAgent(TradingAgent): '\n Noise agent implement simple strategy. The agent wakes up once and places 1 order.\n ' def __init__(self, id: int, name: Optional[str]=None, type: Optional[str]=None, random_state: Optional[np.random.RandomState]=None, symbol: str='IBM', starting_cash: int=100000, lo...
class TradingAgent(FinancialAgent): '\n The TradingAgent class (via FinancialAgent, via Agent) is intended as the\n base class for all trading agents (i.e. not things like exchanges) in a\n market simulation.\n\n It handles a lot of messaging (inbound and outbound) and state maintenance\n automatic...
def list_dict_flip(ld: List[Dict[(str, Any)]]) -> Dict[(str, List[Any])]: '\n Utility that returns a dictionnary of list of dictionnary into a dictionary of list\n\n Arguments:\n - ld: list of dictionaary\n Returns:\n - flipped: dictionnary of lists\n Example:\n - ld = [{"a":1, "b...
def identity_decorator(func): '\n identy for decorators: take a function and return that same function\n\n Arguments:\n - func: function\n Returns:\n - wrapper_identity_decorator: function\n ' def wrapper_identity_decorator(*args, **kvargs): return func(*args, **kvargs) ...
def ignore_mkt_data_buffer_decorator(func): '\n Decorator for function that takes as input self and raw_state.\n Applies the given function while ignoring the buffering in the market data.\n Only last element of the market data buffer is kept\n Arguments:\n - func: function\n Returns:\n ...
def ignore_buffers_decorator(func): '\n Decorator for function that takes as input self and raw_state.\n Applies the given function while ignoring the buffering in both the market data and the general raw state.\n Only last elements are kept.\n Arguments:\n - func: function\n Returns:\n ...
def get_mid_price(bids: List[PriceLevel], asks: List[PriceLevel], last_transaction: int) -> int: '\n Utility that computes the mid price from the snapshot of bid and ask side\n\n Arguments:\n - bids: list of list snapshot of bid side\n - asks: list of list snapshot of ask side\n - last_...
def get_val(book: List[PriceLevel], level: int) -> Tuple[(int, int)]: '\n utility to compute the price and level at the level-th level of the order book\n\n Arguments:\n - book: side of the order book (bid or ask)\n - level: level of interest in the OB side (index starts at 0 for best bid/ask)...
def get_last_val(book: List[PriceLevel], mid_price: int) -> int: '\n utility to compute the price of the deepest placed order in the side of the order book\n\n Arguments:\n - book: side of the order book (bid or ask)\n - mid_price: current mid price used for corner cases\n\n Returns:\n ...
def get_volume(book: List[PriceLevel], depth: Optional[int]=None) -> int: '\n utility to compute the volume placed between the top of the book (depth 0) and the depth\n\n Arguments:\n - book: side of the order book (bid or ask)\n - depth: depth used to compute sum of the volume\n\n Returns:...
def get_imbalance(bids: List[PriceLevel], asks: List[PriceLevel], direction: str='BUY', depth: Optional[int]=None) -> float: '\n utility to compute the imbalance computed between the top of the book and the depth-th value of depth\n\n Arguments:\n - bids: list of list snapshot of bid side\n - ...
class ValueAgent(TradingAgent): def __init__(self, id: int, name: Optional[str]=None, type: Optional[str]=None, random_state: Optional[np.random.RandomState]=None, symbol: str='IBM', starting_cash: int=100000, sigma_n: float=10000, r_bar: int=100000, kappa: float=0.05, sigma_s: float=100000, order_size_model=Non...
def build_config(ticker='ABM', historical_date='20200603', start_time='09:30:00', end_time='16:00:00', exchange_log_orders=True, log_orders=True, book_logging=True, book_log_depth=10, seed=1, stdout_log_level='INFO', num_momentum_agents=25, num_noise_agents=5000, num_value_agents=100, execution_agents=True, execution...
def build_config(seed=(int((datetime.now().timestamp() * 1000000)) % ((2 ** 32) - 1)), date='20210205', end_time='10:00:00', stdout_log_level='INFO', ticker='ABM', starting_cash=10000000, log_orders=True, book_logging=True, book_log_depth=10, stream_history_length=500, exchange_log_orders=None, num_noise_agents=1000,...
class OrderSizeGenerator(BaseGenerator[int], ABC): pass
class ConstantOrderSizeGenerator(OrderSizeGenerator): def __init__(self, order_size: int) -> None: self.order_size: int = order_size def next(self) -> int: return self.order_size def mean(self) -> int: return self.order_size
class UniformOrderSizeGenerator(OrderSizeGenerator): def __init__(self, order_size_min: int, order_size_max: int, random_generator: np.random.RandomState) -> None: self.order_size_min: int = order_size_min self.order_size_max: int = (order_size_max + 1) self.random_generator: np.random.Ra...
class OrderDepthGenerator(BaseGenerator[int], ABC): pass
class ConstantDepthGenerator(OrderDepthGenerator): def __init__(self, order_depth: int) -> None: self.order_depth: int = order_depth def next(self) -> int: return self.order_depth def mean(self) -> int: return self.order_depth
class UniformDepthGenerator(OrderDepthGenerator): def __init__(self, order_depth_min: int, order_depth_max: int, random_generator: np.random.RandomState) -> None: self.random_generator: np.random.RandomState = random_generator self.order_depth_min: int = order_depth_min self.order_depth_m...
@dataclass class MarketClosedMsg(Message): '\n This message is sent from an ``ExchangeAgent`` to a ``TradingAgent`` when a ``TradingAgent`` has\n made a request that cannot be completed because the market the ``ExchangeAgent`` trades\n is closed.\n ' pass
@dataclass class MarketHoursRequestMsg(Message): '\n This message can be sent to an ``ExchangeAgent`` to query the opening hours of the market\n it trades. A ``MarketHoursMsg`` is sent in response.\n ' pass
@dataclass class MarketHoursMsg(Message): '\n This message is sent by an ``ExchangeAgent`` in response to a ``MarketHoursRequestMsg``\n message sent from a ``TradingAgent``.\n\n Attributes:\n mkt_open: The time that the market traded by the ``ExchangeAgent`` opens.\n mkt_close: The time tha...
@dataclass class MarketClosePriceRequestMsg(Message): "\n This message can be sent to an ``ExchangeAgent`` to request that the close price of\n the market is sent when the exchange closes. This is used to accurately calculate\n the agent's final mark-to-market value.\n "
@dataclass class MarketClosePriceMsg(Message): "\n This message is sent by an ``ExchangeAgent`` when the exchange closes to all agents\n that habve requested this message. The value is used to accurately calculate the\n agent's final mark-to-market value.\n\n Attributes:\n close_prices: A mappi...
@dataclass class MarketDataSubReqMsg(Message, ABC): '\n Base class for creating or cancelling market data subscriptions with an\n ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True attempts to create a new subscripti...
@dataclass class MarketDataFreqBasedSubReqMsg(MarketDataSubReqMsg, ABC): '\n Base class for creating or cancelling market data subscriptions with an\n ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True attempts to cr...
@dataclass class MarketDataEventBasedSubReqMsg(MarketDataSubReqMsg, ABC): '\n Base class for creating or cancelling market data subscriptions with an\n ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True attempts to c...
@dataclass class L1SubReqMsg(MarketDataFreqBasedSubReqMsg): '\n This message requests the creation or cancellation of a subscription to L1 order\n book data from an ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True ...
@dataclass class L2SubReqMsg(MarketDataFreqBasedSubReqMsg): '\n This message requests the creation or cancellation of a subscription to L2 order\n book data from an ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True ...
@dataclass class L3SubReqMsg(MarketDataFreqBasedSubReqMsg): '\n This message requests the creation or cancellation of a subscription to L3 order\n book data from an ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True ...
@dataclass class TransactedVolSubReqMsg(MarketDataFreqBasedSubReqMsg): '\n This message requests the creation or cancellation of a subscription to transacted\n volume order book data from an ``ExchangeAgent``.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for....
@dataclass class BookImbalanceSubReqMsg(MarketDataEventBasedSubReqMsg): '\n This message requests the creation or cancellation of a subscription to book\n imbalance events.\n\n Attributes:\n symbol: The symbol of the security to request a data subscription for.\n cancel: If True attempts to...
@dataclass class MarketDataMsg(Message, ABC): '\n Base class for returning market data subscription results from an ``ExchangeAgent``.\n\n The ``last_transaction`` and ``exchange_ts`` fields are not directly related to the\n subscription data but are included for bookkeeping purposes.\n\n Attributes:\...
@dataclass class MarketDataEventMsg(MarketDataMsg, ABC): '\n Base class for returning market data subscription results from an ``ExchangeAgent``.\n\n The ``last_transaction`` and ``exchange_ts`` fields are not directly related to the\n subscription data but are included for bookkeeping purposes.\n\n A...
@dataclass class L1DataMsg(MarketDataMsg): '\n This message returns L1 order book data as part of an L1 data subscription.\n\n Attributes:\n symbol: The symbol of the security this data is for.\n last_transaction: The time of the last transaction that happened on the exchange.\n exchang...
@dataclass class L2DataMsg(MarketDataMsg): '\n This message returns L2 order book data as part of an L2 data subscription.\n\n Attributes:\n symbol: The symbol of the security this data is for.\n last_transaction: The time of the last transaction that happened on the exchange.\n exchang...
@dataclass class L3DataMsg(MarketDataMsg): '\n This message returns L3 order book data as part of an L3 data subscription.\n\n Attributes:\n symbol: The symbol of the security this data is for.\n last_transaction: The time of the last transaction that happened on the exchange.\n exchang...
@dataclass class TransactedVolDataMsg(MarketDataMsg): '\n This message returns order book transacted volume data as part of an transacted\n volume data subscription.\n\n Attributes:\n symbol: The symbol of the security this data is for.\n last_transaction: The time of the last transaction t...
@dataclass class BookImbalanceDataMsg(MarketDataEventMsg): '\n Sent when the book imbalance reaches a certain threshold dictated in the\n subscription request message.\n\n Attributes:\n symbol: The symbol of the security this data is for.\n last_transaction: The time of the last transaction...
@dataclass class OrderMsg(Message, ABC): pass
@dataclass class LimitOrderMsg(OrderMsg): order: LimitOrder
@dataclass class MarketOrderMsg(OrderMsg): order: MarketOrder