/ docs / src / types.md
types.md
  1  # Types
  2  By learning the main types you get to know the building blocks to start composing your [strategy](guides/../guides/strategy-development.md) for [backtesting](guides/execution-modes.md#simulation)-mode) and/or [live trading](guides/execution-modes.md#live-mode).
  3  
  4  The main type is the `Strategy` and it has its own [strategy](guides/../guides/strategy-development.md).
  5  Other important types follow.
  6  
  7  ## Instruments
  8  `Asset` and `Derivative` are implementations of the `AbstractAsset` abstract type, defined in the `Instruments` package. They are usually obtained after parsing a string. `Asset`s are typically spot pairs of base and quote currency, while `Derivative`s can be either swaps or contracts with settlement dates. These are "static" structures that do not query real-time data. The only information they hold is what can be parsed from the string itself.
  9  
 10  - `raw`: The parsed substring.
 11  - `bc`: Base currency.
 12  - `qc`: Quote currency.
 13  - `fiat`: `true` if the pair involves stable currencies, which is a static list defined in `Instruments.fiatnames`.
 14  - `leveraged`: `true` if the base currency is a leveraged token, which is a type of token that usually involves periodic rebalancing. This should be considered as additional information and may be unreliable, as there is no standard for naming such assets.
 15  - `unleveraged_bc`: If the pair is leveraged, this field returns the base currency without the "multiplier", allowing you to find similar markets of the same currency.
 16  
 17  ##### Derivatives only fields
 18  - `asset`: The simpler `Asset` type, which forwards all its fields.
 19  - `sc`: The settlement currency.
 20  - `id`: A string that usually represents the settlement date.
 21  - `strike`: The strike price of the contract.
 22  - `kind`: If it is an option, either `Call` or `Put`; otherwise, `Unkn` (unknown).
 23  
 24  `Asset` can be conveniently constructed from the REPL using `a"BTC/USDT"` or `d"BTC/USDT:USDT"` for `Derivative`s.
 25  
 26  ## Asset instances
 27  
 28  The `AssetInstance` is a rich type that refers to a particular asset. It is not parametrized over a specific asset, but rather over the `AbstractAsset` implementation, the [exchanges](exchanges.md), and the margin mode. An asset instance's information is always related to a specific [exchanges](exchanges.md). For example, `cash(ai)` should return the amount of cash available for that asset on the [exchanges](exchanges.md) matching the instance's ExchangeID parameter.
 29  
 30  Here are the properties of the `AssetInstance`:
 31  
 32  - `asset`: The underlying implementation of `AbstractAsset`.
 33  - `data`: A `SortedDict` (smallest to largest) of [OHLCV data](guides/../guides/data-management.md#ohlcv-data). The key is a `TimeFrame`, and the value is a `DataFrame` with columns: timestamp, high, open, low, close, and volume.
 34  - `history`: The trade history of the asset.
 35  - `cash`: The amount of owned cash.
 36  - `cash_committed`: The total amount of cash used by pending orders.
 37  - `exchange`: The exchange of this asset instance.
 38  - `longpos/shortpos`: The `Position`s when the margin mode is activated. `committed/cash` refers to the position cash within [margin trading](guides/../guides/strategy-development.md).
 39  - `limits/precision`: See [ccxt](https://docs.ccxt.com/#/README?id=precision-and-limits).
 40  - `fees`: The trading fees as a decimal percentage for takers or makers.
 41  
 42  ## Positions
 43  When trading with margin, asset instances manage the status of long or short positions. In `NotHedged` mode (the default), you can only have either a long or short position open at any given time. Positions `cash` and `cash_committed` replace the asset instance's own fields.
 44  
 45  The following are the fields of the position struct:
 46  
 47  - `status`: Represents the current status of the position, which can be either open (`PositionOpen()`) or closed (`PositionClose()`).
 48  - `asset`: Represents the derivative inherited from the asset instance.
 49  - `timestamp`: Indicates the last time the position was updated, such as when [leverage](guides/../guides/strategy-development.md#margin-modes), margin, or position size was modified.
 50  - `liquidation_price`: Represents the price that would trigger a liquidation event.
 51  - `entryprice`: Represents the average price of entry for the position.
 52  - `maintenance_margin`: Specifies the minimum margin required to avoid liquidation, measured in the quote currency.
 53  - `initial_margin`: Specifies the minimum margin required to open the position.
 54  - `additional_margin`: Represents the margin added on top of the initial margin.
 55  - `notional`: Indicates the value of the position with respect to the current price.
 56  - `cash`/`cash_committed`: Represents the amount of cash held, which should always be equal to the number of contracts multiplied by the contract size.
 57  - `[leverage](guides/../guides/strategy-development.md#margin-modes)`: Specifies the [leverage](guides/../guides/strategy-development.md#margin-modes) factor for the position.
 58  - `min_size`: Represents the same value as `limits.cost.min` of the asset instance.
 59  - `hedged`: Indicates whether the margin mode is hedged (`true`) or not (`false`).
 60  - `tiers`: Refers to a `LeverageTiersDict` defined in the `Exchanges` module. It is parsed from ccxt and is required to fetch the correct maintenance margin rate based on the position size.
 61  - `this_tier`: Represents the current tier of the position, which is updated when the notional value changes.
 62  
 63  ## Orders
 64  Order types parameters are:
 65  - `OrderType{<:OrderSide}`: The order type is an abstract type with the `OrderSide` parameter which can be `Buy`, `Sell`, or rarely `Both`. An `OrderType` can be, for example, a `LimitOrderType` or a `MarketOrderType`. These types are themselves supertypes for more specific orders like `FOKOrderType` and `GTCOrderType`. Creating order instances parametrized with different kinds should produce different behavior in order execution.
 66  - `AbstractAsset`, `ExchangeID`: same as asset instances, orders refer to a kind of asset on a specific exchange.
 67  - `PositionSide`: either `Long` or `Short`, the order refers to either a long or short position. Once the order is filled, its amount will be added to the cash of the matching position.
 68  Orders have mostly simple data fields:
 69  - `asset`: the `AbstractAsset` implementation that refers to it
 70  - `exc`: the `ExchangeID` of the matching exchange
 71  - `date`: the date the order was opened
 72  - `price`: the target price of the order, for market orders, this would be the last price before the order was opened.
 73  - `amount`: the total amount requested by the order
 74  - `attrs`: An unspecified named tuple that is used to hold custom data specific to order types.
 75  
 76  ## Trades
 77  Trades are "atomic" events. Orders are composed of one or more trades. They have the same type parameters as the orders. A trade for a specific order matches its exact type parameters.
 78  - `order`: The order to which this trade belongs.
 79  - `date`: The execution date of the trade.
 80  - `amount`: The sum of the amounts of all the trades performed by an order is always below or equal to the order amount.
 81  - `price`: The price can differ from the order price depending on whether the order is a limit or market order.
 82  - `value`: The product of the price and amount.
 83  - `fees`: The fees of the trade, in the quote currency. They can be positive or negative (they are favorable if negative).
 84  - `size`: The product of the price and amount, plus or minus the fees.
 85  - `leverage`: The leverage that was used for the order and with which the trade was executed. We currently do not allow changing the leverage while there are open orders. Therefore, trades that belong to the same order should have the same leverage. Without margin, the leverage should always be equal to `1.0`.
 86  
 87  ## Dates
 88  
 89  The [Julia](https://julialang.org/) main `Dates` package is never imported directly. It is instead exported by the package `TimeTicks`, which, among many utility functions, overrides the `now` function to always use the `UTC` timezone.
 90  
 91  A very important type is the `TimeFrame` type, which defines a segment of time. Most of the time, the concrete type of a `TimeFrame` will be a time period (`Dates.Period`).
 92  
 93  For convenience, [timeframes](guides/../guides/data-management.md#timeframes) can be constructed using the `tf"1m"` notation for a 1-minute [timeframe](guides/../guides/data-management.md#timeframes). This notation can be freely used because, by using the macro, the [timeframe](guides/../guides/data-management.md#timeframes) is replaced at compile time. Moreover, construction is cached and the instances are singletons (`@assert tf"1m" === tf"1m"`). Parsing is also cached, but only by calling `convert(TimeFrame, v)` or `[timeframe](guides/../guides/data-management.md#timeframes)(v)`, and it incurs only the lookup cost (~500ns).
 94  
 95  Parsing is done to match the timeframe naming used within CCTX, and the time period used should be expected to be in `Millisecond`.
 96  
 97  Dates can also be constructed within the repl using the `dt` prefix. For example, `dt"2020-"` will create a `DateTime` value for the date `2020-01-01T00:00:00`. We also implement a `DateRange`, which is used to keep track of the time between two dates, and it also works as an iterator when the step field (`Period`) is defined. Date ranges can be conveniently created using the prefix `dtr`. For example, `dtr"2020-..2021-"` will construct a daterange for the full year 2020. You can specify the date precision up to the second as specified by the standard, like `dtr"2020-01-01T:00:00:01..2021-01-01T00:00:01"`.
 98  
 99  
100  ## See Also
101  
102  - **[Exchanges](exchanges.md)** - Exchange integration and configuration
103  - **[Config](config.md)** - Exchange integration and configuration
104  - **[Overview](troubleshooting/index.md)** - Troubleshooting: Troubleshooting and problem resolution
105  - **[Optimization](optimization.md)** - Performance optimization techniques
106  - **[Performance Issues](troubleshooting/performance-issues.md)** - Troubleshooting: Performance optimization techniques
107  - **[Data Management](guides/../guides/data-management.md)** - Guide: Data handling and management
108  
109  ## [OHLCV](guides/../guides/data-management.md#ohlcv-data)
110  We use the `DataFrames` package, so when we refer to [OHLCV data](guides/../guides/data-management.md#ohlcv-data), there is a `DataFrame` involved. Within the `Data` package, there are multiple utility functions to deal with [OHLCV data](guides/../guides/data-management.md#ohlcv-data). Some of these functions include:
111  - `ohlcv/at(df, date)`: This function allows you to get the value of a column at a particular index by date. For example, you can use `closeat(df, date)` to fetch the close value at a specific date.
112  - `df[dt"2020-01-01", :close]`: This syntax allows you to directly fetch the close value at the nearest matching date by using the `dt` prefix.
113  - `df[dtr"2020-..2021-"]`: This syntax allows you to slice the dataframe for the rows within a specific date range using the `dtr` prefix.
114  
115  Additionally, there are utility functions for guessing the timeframe of an [OHLCV](guides/../guides/data-management.md#ohlcv-data) dataframe by looking at the difference between timestamps. You can use the `timeframe!(df)` function to set the "timeframe" key on the metadata of the timestamp column of the dataframe.
116  
117  Please make sure this documentation is up to date. Check if it lists all the public fields of the struct and remove any sentences that mention functions that do not exist. Also, fix any spelling, grammar, and syntax errors.
118  
119  !!! info "Numbered types"
120      Some types have a number at the end, you can just ignore it, eventually it will be removed.