Skip to content

orders module

Base class for working with order records.

Order records capture information on filled orders. Orders are mainly populated when simulating a portfolio and can be accessed as Portfolio.orders.

>>> from vectorbtpro import *

>>> price = vbt.RandomData.pull(
...     ['a', 'b'],
...     start=datetime(2020, 1, 1),
...     end=datetime(2020, 3, 1),
...     seed=vbt.key_dict(a=42, b=43)
... ).get()

100%

>>> size = pd.DataFrame({
...     'a': np.random.randint(-1, 2, size=len(price.index)),
...     'b': np.random.randint(-1, 2, size=len(price.index)),
... }, index=price.index, columns=price.columns)
>>> pf = vbt.Portfolio.from_orders(price, size, fees=0.01, freq='d')

>>> pf.orders.side_buy.count()
symbol
a    17
b    15
Name: count, dtype: int64

>>> pf.orders.side_sell.count()
symbol
a    24
b    26
Name: count, dtype: int64

Stats

>>> pf.orders['a'].stats()
Start                  2019-12-31 22:00:00+00:00
End                    2020-02-29 22:00:00+00:00
Period                          61 days 00:00:00
Total Records                                 41
Side Counts: Buy                              17
Side Counts: Sell                             24
Size: Min              0 days 19:33:05.006182372
Size: Median                     1 days 00:00:00
Size: Max                        1 days 00:00:00
Fees: Min              0 days 20:26:25.905776572
Fees: Median           0 days 22:46:22.693324744
Fees: Max              1 days 01:04:25.541681491
Weighted Buy Price                      94.69917
Weighted Sell Price                    95.742148
Name: a, dtype: object

StatsBuilderMixin.stats() also supports (re-)grouping:

>>> pf.orders.stats(group_by=True)
Start                  2019-12-31 22:00:00+00:00
End                    2020-02-29 22:00:00+00:00
Period                          61 days 00:00:00
Total Records                                 82
Side Counts: Buy                              32
Side Counts: Sell                             50
Size: Min              0 days 19:33:05.006182372
Size: Median                     1 days 00:00:00
Size: Max                        1 days 00:00:00
Fees: Min              0 days 20:26:25.905776572
Fees: Median           0 days 23:58:29.773897679
Fees: Max              1 days 02:29:08.904770159
Weighted Buy Price                     98.804452
Weighted Sell Price                    99.969934
Name: group, dtype: object

Plots

Orders class has a single subplot based on Orders.plot():

>>> pf.orders['a'].plots().show()


fs_orders_attach_field_config ReadonlyConfig

Config of fields to be attached to FSOrders.

ReadonlyConfig(
    type=dict(
        attach_filters=True
    ),
    stop_type=dict(
        attach_filters=True
    )
)

fs_orders_field_config ReadonlyConfig

Field config for FSOrders.

ReadonlyConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('signal_idx', 'int64'),
        ('creation_idx', 'int64'),
        ('idx', 'int64'),
        ('size', 'float64'),
        ('price', 'float64'),
        ('fees', 'float64'),
        ('side', 'int64'),
        ('type', 'int64'),
        ('stop_type', 'int64')
    ]),
    settings=dict(
        idx=dict(
            title='Fill Index'
        ),
        signal_idx=dict(
            title='Signal Index',
            mapping='index',
            noindex=True
        ),
        creation_idx=dict(
            title='Creation Index',
            mapping='index',
            noindex=True
        ),
        type=dict(
            title='Type',
            mapping=OrderTypeT(
                Market=0,
                Limit=1
            )
        ),
        stop_type=dict(
            title='Stop Type',
            mapping=StopTypeT(
                SL=0,
                TSL=1,
                TTP=2,
                TP=3,
                TD=4,
                DT=5
            )
        )
    )
)

fs_orders_shortcut_config ReadonlyConfig

Config of shortcut properties to be attached to FSOrders.

ReadonlyConfig(
    stop_orders=dict(),
    ranges=dict(),
    creation_ranges=dict(),
    fill_ranges=dict(),
    signal_to_creation_duration=dict(
        obj_type='mapped_array'
    ),
    creation_to_fill_duration=dict(
        obj_type='mapped_array'
    ),
    signal_to_fill_duration=dict(
        obj_type='mapped_array'
    )
)

orders_attach_field_config ReadonlyConfig

Config of fields to be attached to Orders.

ReadonlyConfig(
    side=dict(
        attach_filters=True
    )
)

orders_field_config ReadonlyConfig

Field config for Orders.

ReadonlyConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('idx', 'int64'),
        ('size', 'float64'),
        ('price', 'float64'),
        ('fees', 'float64'),
        ('side', 'int64')
    ]),
    settings=dict(
        id=dict(
            title='Order Id'
        ),
        idx=dict(),
        size=dict(
            title='Size'
        ),
        price=dict(
            title='Price'
        ),
        fees=dict(
            title='Fees'
        ),
        side=dict(
            title='Side',
            mapping=OrderSideT(
                Buy=0,
                Sell=1
            ),
            as_customdata=False
        )
    )
)

orders_shortcut_config ReadonlyConfig

Config of shortcut properties to be attached to Orders.

ReadonlyConfig(
    long_view=dict(),
    short_view=dict(),
    signed_size=dict(
        obj_type='mapped'
    ),
    value=dict(
        obj_type='mapped'
    ),
    weighted_price=dict(
        obj_type='red_array'
    ),
    price_status=dict(
        obj_type='mapped'
    )
)

FSOrders class

FSOrders(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends Orders for working with order records generated from signals.

Superclasses

Inherited members


creation_idx property

Mapped array of the field creation_idx.


creation_ranges property

FSOrders.get_creation_ranges() with default arguments.


creation_to_fill_duration property

FSOrders.get_creation_to_fill_duration() with default arguments.


field_config class variable

Field config of FSOrders.

HybridConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('signal_idx', 'int64'),
        ('creation_idx', 'int64'),
        ('idx', 'int64'),
        ('size', 'float64'),
        ('price', 'float64'),
        ('fees', 'float64'),
        ('side', 'int64'),
        ('type', 'int64'),
        ('stop_type', 'int64')
    ]),
    settings=dict(
        id=dict(
            name='id',
            title='Order Id',
            mapping='ids'
        ),
        col=dict(
            name='col',
            title='Column',
            mapping='columns',
            as_customdata=False
        ),
        idx=dict(
            name='idx',
            title='Fill Index',
            mapping='index'
        ),
        size=dict(
            title='Size'
        ),
        price=dict(
            title='Price'
        ),
        fees=dict(
            title='Fees'
        ),
        side=dict(
            title='Side',
            mapping=OrderSideT(
                Buy=0,
                Sell=1
            ),
            as_customdata=False
        ),
        signal_idx=dict(
            title='Signal Index',
            mapping='index',
            noindex=True
        ),
        creation_idx=dict(
            title='Creation Index',
            mapping='index',
            noindex=True
        ),
        type=dict(
            title='Type',
            mapping=OrderTypeT(
                Market=0,
                Limit=1
            )
        ),
        stop_type=dict(
            title='Stop Type',
            mapping=StopTypeT(
                SL=0,
                TSL=1,
                TTP=2,
                TP=3,
                TD=4,
                DT=5
            )
        )
    )
)

Returns FSOrders._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.

To change fields, you can either change the config in-place, override this property, or overwrite the instance variable FSOrders._field_config.


fill_ranges property

FSOrders.get_fill_ranges() with default arguments.


get_creation_ranges method

FSOrders.get_creation_ranges(
    **kwargs
)

Get records of type Ranges for signal-to-creation ranges.


get_creation_to_fill_duration method

FSOrders.get_creation_to_fill_duration(
    **kwargs
)

Get duration between creation and fill.


get_fill_ranges method

FSOrders.get_fill_ranges(
    **kwargs
)

Get records of type Ranges for creation-to-fill ranges.


get_ranges method

FSOrders.get_ranges(
    **kwargs
)

Get records of type Ranges for signal-to-fill ranges.


get_signal_to_creation_duration method

FSOrders.get_signal_to_creation_duration(
    **kwargs
)

Get duration between signal and creation.


get_signal_to_fill_duration method

FSOrders.get_signal_to_fill_duration(
    **kwargs
)

Get duration between signal and fill.


get_stop_orders method

FSOrders.get_stop_orders(
    **kwargs
)

Get stop orders.


metrics class variable

Metrics supported by FSOrders.

HybridConfig(
    start_index=dict(
        title='Start Index',
        calc_func=<function Orders.<lambda> at 0x1647194e0>,
        agg_func=None,
        tags='wrapper'
    ),
    end_index=dict(
        title='End Index',
        calc_func=<function Orders.<lambda> at 0x164719580>,
        agg_func=None,
        tags='wrapper'
    ),
    total_duration=dict(
        title='Total Duration',
        calc_func=<function Orders.<lambda> at 0x164719620>,
        apply_to_timedelta=True,
        agg_func=None,
        tags='wrapper'
    ),
    total_records=dict(
        title='Total Records',
        calc_func='count',
        tags='records'
    ),
    side_counts=dict(
        title='Side Counts',
        calc_func='side.value_counts',
        incl_all_keys=True,
        post_calc_func=<function Orders.<lambda> at 0x1647196c0>,
        tags=[
            'orders',
            'side'
        ]
    ),
    type_counts=dict(
        title='Type Counts',
        calc_func='type.value_counts',
        incl_all_keys=True,
        post_calc_func=<function FSOrders.<lambda> at 0x16471a980>,
        tags=[
            'orders',
            'type'
        ]
    ),
    stop_type_counts=dict(
        title='Stop Type Counts',
        calc_func='stop_type.value_counts',
        incl_all_keys=True,
        post_calc_func=<function FSOrders.<lambda> at 0x16471aa20>,
        tags=[
            'orders',
            'stop_type'
        ]
    ),
    size=dict(
        title='Size',
        calc_func='size.describe',
        post_calc_func=<function Orders.<lambda> at 0x164719760>,
        tags=[
            'orders',
            'size'
        ]
    ),
    fees=dict(
        title='Fees',
        calc_func='fees.describe',
        post_calc_func=<function Orders.<lambda> at 0x164719800>,
        tags=[
            'orders',
            'fees'
        ]
    ),
    weighted_buy_price=dict(
        title='Weighted Buy Price',
        calc_func='side_buy.get_weighted_price',
        tags=[
            'orders',
            'buy',
            'price'
        ]
    ),
    weighted_sell_price=dict(
        title='Weighted Sell Price',
        calc_func='side_sell.get_weighted_price',
        tags=[
            'orders',
            'sell',
            'price'
        ]
    ),
    avg_signal_to_creation_duration=dict(
        title='Avg Signal-Creation Duration',
        calc_func='signal_to_creation_duration.mean',
        apply_to_timedelta=True,
        tags=[
            'orders',
            'duration'
        ]
    ),
    avg_creation_to_fill_duration=dict(
        title='Avg Creation-Fill Duration',
        calc_func='creation_to_fill_duration.mean',
        apply_to_timedelta=True,
        tags=[
            'orders',
            'duration'
        ]
    ),
    avg_signal_to_fill_duration=dict(
        title='Avg Signal-Fill Duration',
        calc_func='signal_to_fill_duration.mean',
        apply_to_timedelta=True,
        tags=[
            'orders',
            'duration'
        ]
    )
)

Returns FSOrders._metrics, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.

To change metrics, you can either change the config in-place, override this property, or overwrite the instance variable FSOrders._metrics.


ranges property

FSOrders.get_ranges() with default arguments.


signal_idx property

Mapped array of the field signal_idx.


signal_to_creation_duration property

FSOrders.get_signal_to_creation_duration() with default arguments.


signal_to_fill_duration property

FSOrders.get_signal_to_fill_duration() with default arguments.


stop_orders property

FSOrders.get_stop_orders() with default arguments.


stop_type property

Mapped array of the field stop_type.


stop_type_dt property

Records filtered by stop_type == 5.


stop_type_sl property

Records filtered by stop_type == 0.


stop_type_td property

Records filtered by stop_type == 4.


stop_type_tp property

Records filtered by stop_type == 3.


stop_type_tsl property

Records filtered by stop_type == 1.


stop_type_ttp property

Records filtered by stop_type == 2.


type property

Mapped array of the field type.


type_limit property

Records filtered by type == 1.


type_market property

Records filtered by type == 0.


Orders class

Orders(
    wrapper,
    records_arr,
    open=None,
    high=None,
    low=None,
    close=None,
    **kwargs
)

Extends PriceRecords for working with order records.

Superclasses

Inherited members

Subclasses


col property

Mapped array of the field col.


fees property

Mapped array of the field fees.


field_config class variable

Field config of Orders.

HybridConfig(
    dtype=np.dtype([
        ('id', 'int64'),
        ('col', 'int64'),
        ('idx', 'int64'),
        ('size', 'float64'),
        ('price', 'float64'),
        ('fees', 'float64'),
        ('side', 'int64')
    ]),
    settings=dict(
        id=dict(
            name='id',
            title='Order Id',
            mapping='ids'
        ),
        col=dict(
            name='col',
            title='Column',
            mapping='columns',
            as_customdata=False
        ),
        idx=dict(
            name='idx',
            title='Index',
            mapping='index'
        ),
        size=dict(
            title='Size'
        ),
        price=dict(
            title='Price'
        ),
        fees=dict(
            title='Fees'
        ),
        side=dict(
            title='Side',
            mapping=OrderSideT(
                Buy=0,
                Sell=1
            ),
            as_customdata=False
        )
    )
)

Returns Orders._field_config, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.

To change fields, you can either change the config in-place, override this property, or overwrite the instance variable Orders._field_config.


get_long_view method

Orders.get_long_view(
    init_position=0.0,
    init_price=nan,
    jitted=None,
    chunked=None
)

See get_long_view_orders_nb().


get_price_status method

Orders.get_price_status(
    **kwargs
)

See price_status_nb().


get_short_view method

Orders.get_short_view(
    init_position=0.0,
    init_price=nan,
    jitted=None,
    chunked=None
)

See get_short_view_orders_nb().


get_signed_size method

Orders.get_signed_size(
    **kwargs
)

Get signed size.


get_value method

Orders.get_value(
    **kwargs
)

Get value.


get_weighted_price method

Orders.get_weighted_price(
    group_by=None,
    jitted=None,
    chunked=None,
    wrap_kwargs=None,
    **kwargs
)

Get size-weighted price average.


id property

Mapped array of the field id.


idx property

Mapped array of the field idx.


long_view property

Orders.get_long_view() with default arguments.


metrics class variable

Metrics supported by Orders.

HybridConfig(
    start_index=dict(
        title='Start Index',
        calc_func=<function Orders.<lambda> at 0x1647194e0>,
        agg_func=None,
        tags='wrapper'
    ),
    end_index=dict(
        title='End Index',
        calc_func=<function Orders.<lambda> at 0x164719580>,
        agg_func=None,
        tags='wrapper'
    ),
    total_duration=dict(
        title='Total Duration',
        calc_func=<function Orders.<lambda> at 0x164719620>,
        apply_to_timedelta=True,
        agg_func=None,
        tags='wrapper'
    ),
    total_records=dict(
        title='Total Records',
        calc_func='count',
        tags='records'
    ),
    side_counts=dict(
        title='Side Counts',
        calc_func='side.value_counts',
        incl_all_keys=True,
        post_calc_func=<function Orders.<lambda> at 0x1647196c0>,
        tags=[
            'orders',
            'side'
        ]
    ),
    size=dict(
        title='Size',
        calc_func='size.describe',
        post_calc_func=<function Orders.<lambda> at 0x164719760>,
        tags=[
            'orders',
            'size'
        ]
    ),
    fees=dict(
        title='Fees',
        calc_func='fees.describe',
        post_calc_func=<function Orders.<lambda> at 0x164719800>,
        tags=[
            'orders',
            'fees'
        ]
    ),
    weighted_buy_price=dict(
        title='Weighted Buy Price',
        calc_func='side_buy.get_weighted_price',
        tags=[
            'orders',
            'buy',
            'price'
        ]
    ),
    weighted_sell_price=dict(
        title='Weighted Sell Price',
        calc_func='side_sell.get_weighted_price',
        tags=[
            'orders',
            'sell',
            'price'
        ]
    )
)

Returns Orders._metrics, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.

To change metrics, you can either change the config in-place, override this property, or overwrite the instance variable Orders._metrics.


plot method

Orders.plot(
    column=None,
    plot_ohlc=True,
    plot_close=True,
    ohlc_type=None,
    ohlc_trace_kwargs=None,
    close_trace_kwargs=None,
    buy_trace_kwargs=None,
    sell_trace_kwargs=None,
    add_trace_kwargs=None,
    fig=None,
    **layout_kwargs
)

Plot orders.

Args

column : str
Name of the column to plot.
plot_ohlc : bool
Whether to plot OHLC.
plot_close : bool
Whether to plot close.
ohlc_type

Either 'OHLC', 'Candlestick' or Plotly trace.

Pass None to use the default.

ohlc_trace_kwargs : dict
Keyword arguments passed to ohlc_type.
close_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for Orders.close.
buy_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Buy" markers.
sell_trace_kwargs : dict
Keyword arguments passed to plotly.graph_objects.Scatter for "Sell" markers.
add_trace_kwargs : dict
Keyword arguments passed to add_trace.
fig : Figure or FigureWidget
Figure to add traces to.
**layout_kwargs
Keyword arguments for layout.

Usage

>>> index = pd.date_range("2020", periods=5)
>>> price = pd.Series([1., 2., 3., 2., 1.], index=index)
>>> size = pd.Series([1., 1., 1., 1., -1.], index=index)
>>> orders = vbt.Portfolio.from_orders(price, size).orders

>>> orders.plot().show()


plots_defaults property

Defaults for PlotsBuilderMixin.plots().

Merges PriceRecords.plots_defaults and plots from orders.


price property

Mapped array of the field price.


price_status property

Orders.get_price_status() with default arguments.


short_view property

Orders.get_short_view() with default arguments.


side property

Mapped array of the field side.


side_buy property

Records filtered by side == 0.


side_sell property

Records filtered by side == 1.


signed_size property

Orders.get_signed_size() with default arguments.


size property

Mapped array of the field size.


stats_defaults property

Defaults for StatsBuilderMixin.stats().

Merges PriceRecords.stats_defaults and stats from orders.


subplots class variable

Subplots supported by Orders.

HybridConfig(
    plot=dict(
        title='Orders',
        yaxis_kwargs=dict(
            title='Price'
        ),
        check_is_not_grouped=True,
        plot_func='plot',
        tags='orders'
    )
)

Returns Orders._subplots, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.

To change subplots, you can either change the config in-place, override this property, or overwrite the instance variable Orders._subplots.


value property

Orders.get_value() with default arguments.


weighted_price property

Orders.get_weighted_price() with default arguments.