/
dynamic_orders.py
135 lines (108 loc) · 5.26 KB
/
dynamic_orders.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# Copyright 2019 The TensorTrade Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
import numpy as np
from typing import Union, List
from abc import abstractmethod
from itertools import product
from gym.spaces import Discrete
from tensortrade.actions import ActionScheme
from tensortrade.trades import TradeSide, TradeType
from tensortrade.instruments import Quantity
from tensortrade.orders import Order, OrderListener
class DynamicOrders(ActionScheme):
"""A discrete action scheme that determines actions based on a list of
trading pairs, order criteria, and trade sizes."""
def __init__(self,
pairs: Union[List['TradingPair'], 'TradingPair'],
criteria: Union[List['OrderCriteria'], 'OrderCriteria'] = None,
trade_sizes: Union[List[float], int] = 10,
trade_type: TradeType = TradeType.MARKET,
order_listener: OrderListener = None):
"""
Arguments:
pairs: A list of trading pairs to select from when submitting an order.
(e.g. TradingPair(BTC, USD), TradingPair(ETH, BTC), etc.)
criteria: A list of order criteria to select from when submitting an order.
(e.g. MarketOrder, LimitOrder w/ price, StopLoss, etc.)
trade_sizes: A list of trade sizes to select from when submitting an order.
(e.g. '[1, 1/3]' = 100% or 33% of balance is tradeable. '4' = 25%, 50%, 75%, or 100% of balance is tradeable.)
order_listener (optional): An optional listener for order events executed by this action scheme.
"""
self.pairs = self.default('pairs', pairs)
self.criteria = self.default('criteria', criteria)
self.trade_sizes = self.default('trade_sizes', trade_sizes)
self._trade_type = self.default('trade_type', trade_type)
self._order_listener = self.default('order_listener', order_listener)
self.reset()
@property
def action_space(self) -> Discrete:
"""The discrete action space produced by the action scheme."""
return Discrete(len(self._actions))
@property
def pairs(self) -> List['TradingPair']:
"""A list of trading pairs to select from when submitting an order.
(e.g. TradingPair(BTC, USD), TradingPair(ETH, BTC), etc.)
"""
return self._pairs
@pairs.setter
def pairs(self, pairs: Union[List['TradingPair'], 'TradingPair']):
self._pairs = pairs if isinstance(pairs, list) else [pairs]
@property
def criteria(self) -> List['OrderCriteria']:
"""A list of order criteria to select from when submitting an order.
(e.g. MarketOrderCriteria, LimitOrderCriteria, StopLossCriteria, CustomCriteria, etc.)
"""
return self._criteria
@criteria.setter
def criteria(self, criteria: Union[List['OrderCriteria'], 'OrderCriteria']):
self._criteria = criteria if isinstance(criteria, list) else [criteria]
@property
def trade_sizes(self) -> List[float]:
"""A list of trade sizes to select from when submitting an order.
(e.g. '[1, 1/3]' = 100% or 33% of balance is tradeable. '4' = 25%, 50%, 75%, or 100% of balance is tradeable.)
"""
return self._trade_sizes
@trade_sizes.setter
def trade_sizes(self, trade_sizes: Union[List[float], int]):
self._trade_sizes = trade_sizes if isinstance(trade_sizes, list) else [
(x + 1) / trade_sizes for x in range(trade_sizes)]
def get_order(self, action: int, exchange: 'Exchange', portfolio: 'Portfolio') -> Order:
if action == 0:
return None
(side, pair, criteria, size) = self._actions[action]
instrument = pair.base if side == TradeSide.BUY else pair.quote
wallet = portfolio.get_wallet(exchange.id, instrument=instrument)
price = exchange.quote_price(instrument)
size = min(wallet.balance.size, (wallet.balance.size * size))
if size < 10 ** -instrument.precision:
return None
quantity = size * instrument
wallet -= quantity
order = Order(side=side,
trade_type=self._trade_type,
pair=pair,
price=price,
quantity=quantity,
portfolio=portfolio,
criteria=criteria)
quantity.lock_for(order.id)
wallet += quantity
if self._order_listener is not None:
order.attach(self._order_listener)
return order
def reset(self):
self._actions = [None]
for trading_pair, criteria, size in product(self._pairs, self._criteria, self._trade_sizes):
self._actions += [(TradeSide.BUY, trading_pair, criteria, size)]
self._actions += [(TradeSide.SELL, trading_pair, criteria, size)]