# TWAP

TWAP spreads an order out through time in order to fill at the time-weighted average price, calculated between the time the order is submitted to the final atomic order close.

The price can be specified as a fixed external target, such as the top bid/ask or last trade price, or as an explicit target which must be matched against the top bid/ask/last trade/etc.

Available price targets/explicit target conditions:

- OB side price (top bid/ask)
- OB mid price
- Last trade price

Source:
  - twap/index.js, line 24

##### Example

    await host.startAO('bfx-twap', {
      symbol: 'tBTCUSD',
      amount: -0.5,
      sliceAmount: -0.1,
      sliceInterval: 10,
      priceDelta: 100, // max distance from price target to fulfill condition
      priceTarget: 16650,
      priceCondition: TWAP.Config.PRICE_COND.MATCH_LAST,
      tradeBeyondEnd: false,
      orderType: 'LIMIT',
      submitDelay: 150,
      cancelDelay: 150,
      _margin: false
    })

##### Parameters:

Name | Type | Attributes | Description
--- | --- | --- | ---
`symbol` | string |  | symbol to trade on
`amount` | number |  | total order amount
`sliceAmount` | number |  | individual slice order amount
`priceDelta` | number |  | max acceptable distance from price target
`priceCondition` | string | <optional> | MATCH_LAST, MATCH_SIDE, MATCH_MID
`priceTarget` | number | string |  | numeric, or OB_SIDE, OB_MID, LAST
`tradeBeyondEnd` | boolean |  | if true, slices are not cancelled after their interval expires
`orderType` | string |  | LIMIT or MARKET
`_margin` | boolean |  | if false, order type is prefixed with EXCHANGE
`submitDelay` | number | <optional> | in ms, defaults to 1500
`cancelDelay` | number | <optional> | in ms, defaults to 5000

### Members

#### (static) generateOrder

Source:
  - twap/util/generate_order.js, line 9

Generates the next slice order for the provided instance, taking into account the remaining amount that needs to be filled.

#### (static) getOBPrice

Source:
  - twap/util/get_ob_price.js, line 6

Extracts the target price from the last known order book. Null if unavailable

#### (static) getTradePrice

Source:
  - twap/util/get_trade_price.js, line 6

Extracts the target price from the last known trade. Null if unavailable

#### (static) hasOBTarget

Source:
  - twap/util/has_ob_target.js, line 7

Reports of the provided execution parameters have an order book price target.

#### (static) hasTradeTarget

Source:
  - twap/util/has_trade_target.js, line 7

Reports of the provided execution parameters have a trade price target.

#### (static) isTargetMet

Source:
  - twap/util/is_target_met.js, line 5

Reports if the price target for the provided execution parameters is met for the specified price.

### Methods

#### (async, static) declareChannels(instance, host)

Source:
  - twap/meta/declare_channels.js, line 16

Declares necessary data channels for price matching. The instance may require a `book` or `trades` channel depending on the execution parameters.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | object | AO instance state
`host` | object | algo host instance for declaring channel requirements

#### (static) declareEvents(instance, host)

Source:
  - twap/meta/declare_events.js, line 13

Declares internal `self:interval_tick` event handler to the host for event routing.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | object | AO instance state
`host` | object | algo host instance for event mapping

#### (static) genOrderLabel(state) → {string}

Source:
  - twap/meta/gen_order_label.js, line 13

Generates a label for a TWAP instance for rendering in an UI.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---

`state`

object

source instance state

###### Properties

Name | Type | Description
--- | --- | ---
`args` | object | source instance execution parameters

##### Returns:

label

Type
  string

#### (static) genPreview(args) → {Array.<object>}

Source:
  - twap/meta/gen_preview.js, line 15

Generates an array of preview orders which show what could be expected if an instance of TWAP was executed with the specified parameters.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`args` | object | instance parameters

##### Returns:

previewOrders

Type
  Array.<object>

#### (static) getUIDef() → {AOUIDefinition}

Source:
  - twap/meta/get_ui_def.js, line 9

Returns the UI layout definition for TWAP, with a field for each parameter.

Part of the `meta` handler section.

##### Returns:

uiDef

Type
  AOUIDefinition

#### (static) initState(args) → {object}

Source:
  - twap/meta/init_state.js, line 12

Creates an initial state object for a TWAP instance to begin executing with.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`args` | object | instance execution parameters

##### Returns:

initialState

Type
  object

#### (async, static) onDataManagedBook(instance, book, meta)

Source:
  - twap/events/data_managed_book.js, line 19
See:
  - module:TWAP.hasOBTarget

Saves the book on the instance state if it is needed for price target matching, and it is for the configured symbol.

Mapped to the `data:managedBook` event.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | AOInstance | AO instance state
`book` | object | order book model
`meta` | EventMetaInformation | source channel information

##### Listens to Events:

- AOHost~event:dataManagedBook

#### (async, static) onDataTrades(instance, trades, meta) → {Promise}

Source:
  - twap/events/data_trades.js, line 18

Saves the last trade on the instance state to be used in price matching.

Mapped to the `data:trades` event.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | AOInstance | AO instance
`trades` | Array.<object> | array of incoming trades
`meta` | EventMetaInformation | source channel information

##### Listens to Events:

- AOHost~event:dataTrades

##### Returns:

p - resolves on completion

Type
  Promise

#### (async, static) onLifeStart(instance) → {Promise}

Source:
  - twap/events/life_start.js, line 15

Sets up the `self:interval_tick` interval and saves it on the state.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | AOInstance | AO instance

##### Listens to Events:

- AOHost~event:lifeStart

##### Returns:

p - resolves on completion

Type
  Promise

#### (async, static) onLifeStop(instance) → {Promise}

Source:
  - twap/events/life_stop.js, line 12

Clears the tick interval prior to teardown

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | object | AO instance

##### Listens to Events:

- AOHost~event:lifeStop

##### Returns:

p - resolves on completion

Type
  Promise

#### (async, static) onOrdersOrderCancel(instance, order) → {Promise}

Source:
  - twap/events/orders_order_cancel.js, line 16

Triggered when an atomic order cancellation is detected; cancels any open orders and emits the `exec:stop` event to trigger teardown.

Mapped to the `orders:order_cancel` event.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | object | AO instance
`order` | object | the order that was cancelled

##### Listens to Events:

- AOHost~event:ordersOrderCancel

##### Returns:

p - resolves on completion

Type
  Promise

#### (async, static) onOrdersOrderFill(instance, order) → {Promise}

Source:
  - twap/events/orders_order_fill.js, line 18

Triggered when an atomic order fills. Updates the remaining amount on the instance state, and emits the `exec:stop` if the instance is now fully filled.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | AOInstance | AO instance
`order` | object | the order that filled

##### Listens to Events:

- AOHost~event:ordersOrderFill

##### Returns:

p - resolves on completion

Type
  Promise

#### (async, static) onSelfIntervalTick(instance) → {Promise}

Source:
  - twap/events/self_interval_tick.js, line 21

Submits the next slice order if the price condition/target is met.

##### Parameters:

Name | Type | Description
--- | --- | ---
`instance` | AOInstance | AO instance

##### Listens to Events:

- module:TWAP~event:selfIntervalTick

##### Returns:

p - resolves on completion

Type
  Promise

#### (static) processParams(data) → {object}

Source:
  - twap/meta/process_params.js, line 15

Converts a raw parameters Object received from an UI into a parameters Object which can be used by TWAP instance for execution.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`data` | object | raw parameters from an UI

##### Returns:

parameters - ready to be passed to a fresh instance

Type
  object

#### (static) serialize(state) → {object}

Source:
  - twap/meta/serialize.js, line 14

Creates a POJO from an instance's state which can be stored as JSON in a database, and later loaded with the corresponding `module:TWAP.unserialize` method.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`state` | object | instance state to be serialized

##### Returns:

pojo - DB-ready plain JS object

Type
  object

#### (static) unserialize(loadedState) → {object}

Source:
  - twap/meta/unserialize.js, line 12

Converts a loaded POJO into a state object ready for live execution.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---
`loadedState` | object | data from a DB

##### Returns:

instanceState - ready for execution

Type
  object

#### (static) validateParams(args) → {string}

Source:
  - twap/meta/validate_params.js, line 29

Verifies that a parameters Object is valid, and all parameters are within the configured boundaries for a valid TWAP order.

Part of the `meta` handler section.

##### Parameters:

Name | Type | Description
--- | --- | ---

`args`

object

incoming parameters

###### Properties

Name | Type | Attributes | Description
--- | --- | --- | ---
`amount` | number |  | total order amount
`sliceAmount` | number |  | individual slice order amount
`priceDelta` | number |  | max acceptable distance from price target
`priceCondition` | string | <optional> | MATCH_LAST, MATCH_SIDE, MATCH_MID
`priceTarget` | number | string |  | numeric, or OB_SIDE, OB_MID, LAST
`tradeBeyondEnd` | boolean |  | if true, slices are not cancelled after their interval expires
`orderType` | string |  | LIMIT or MARKET
`submitDelay` | number | <optional> | in ms, defaults to 1500
`cancelDelay` | number | <optional> | in ms, defaults to 5000

##### Returns:

error - null if parameters are valid, otherwise a description of which parameter is invalid.

Type
  string

### Events

#### selfIntervalTick

Source:
  - twap/meta/declare_events.js, line 17

Triggers price target comparison and a potential atomic order submit

##### Listeners of This Event:

- module:TWAP.onSelfIntervalTick