Example #1
0
def test_simulated_from_config():
    class NoSlippage(SlippageModel):
        def adjust_trade(self, trade: Trade, **kwargs) -> Trade:
            pass

    config = {
        'base_instrument': 'EURO',
        'instruments': ['BTC', 'ETH'],
        'exchanges': {
            'commission': 0.5,
            'base_precision': 0.3,
            'instrument_precision': 10,
            'min_trade_price': 1e-7,
            'max_trade_price': 1e7,
            'min_trade_size': 1e-4,
            'max_trade_size': 1e4,
            'initial_balance': 1e5,
            'window_size': 5,
            'should_pretransform_obs': True,
            'max_allowed_slippage_percent': 3.0,
            'slippage_model': NoSlippage
        }
    }

    with TradingContext(**config):
        df = pd.DataFrame([[900, 849, 9023, 94039, 943]],
                          columns=["open", "high", "low", "close", "volume"])
        exchange = SimulatedExchange(data_frame=df)

        assert exchange._base_instrument == 'EURO'
        assert exchange._commission == 0.5
Example #2
0
def test_simlulated_from_config():
    class NoSlippage(SlippageModel):
        def fill_order(self, trade: Trade, **kwargs) -> Trade:
            return trade

    config = {
        'base_instrument': 'EURO',
        'instruments': ['BTC', 'ETH'],
        'exchanges': {
            'commission_percent': 0.5,
            'base_precision': 0.3,
            'instrument_precision': 10,
            'min_trade_price': 1e-7,
            'max_trade_price': 1e7,
            'min_trade_amount': 1e-4,
            'max_trade_amount': 1e4,
            'initial_balance': 1e5,
            'window_size': 5,
            'should_pretransform_obs': True,
            'max_allowed_slippage_percent': 3.0,
            'slippage_model': NoSlippage
        }
    }

    with TradingContext(**config):

        exchange = SimulatedExchange()

        exchange.base_instrument == 'EURO'
        exchange._commission_percent == 0.5
def test_create_injected_simulated_exchange(trade_context):

    with trade_context:
        exchange = SimulatedExchange()
        exchange.reset()
        assert exchange.base_instrument == 'EURO'
        assert exchange.initial_balance == 1e4
        assert exchange._current_step == 0
Example #4
0
def test_injects_base_instrument():

    with TradingContext(**config):
        df = pd.DataFrame([[900, 849, 9023, 94039, 943]],
                          columns=["open", "high", "low", "close", "volume"])
        exchange = SimulatedExchange(data_frame=df)

        assert exchange._base_instrument == EUR
Example #5
0
def get_env(file_path):
    df = load_data(file_path)

    normalize = MinMaxNormalizer(inplace=True)
    difference = FractionalDifference(difference_order=0.6, inplace=True)
    feature_pipeline = FeaturePipeline(steps=[normalize, difference])

    reward_strategy = SimpleProfitStrategy()
    action_strategy = DiscreteActionStrategy(n_actions=20, instrument_symbol='BTC/USDT')

    exchange = SimulatedExchange(base_instrument='USDT',
                                 should_pretransform_obs=True,
                                 feature_pipeline=feature_pipeline
                                 )
    exchange.data_frame = df[:STEP]
    environment = TradingEnvironment(exchange=exchange,
                                     action_strategy=action_strategy,
                                     reward_strategy=reward_strategy,
                                     feature_pipeline=feature_pipeline)

    return environment
Example #6
0
def main():
    df = load_dataframe()

    exchange = SimulatedExchange(df)
    wallet_usd = Wallet(exchange, 0 * USD)
    wallet_btc = Wallet(exchange, .01 * BTC)
    portfolio = Portfolio(BTC, wallets=[wallet_usd, wallet_btc])
    trading_pair = TradingPair(USD, BTC)
    action = DynamicOrders(trading_pair)
    env = TradingEnvironment(portfolio, exchange, action, 'simple',
                             window_size=20)

    times = []
    for _ in range(300):
        action = 0
        if random.random() > .9:
            action = int(random.uniform(1, 20))
        env.step(action)
        t1 = time.time()
        env.render('human')
        times.append(time.time() - t1)
        if len(times) > 120:
            times.pop(0)
        print(f'FPS: {1 / np.mean(times):.1f}', end='\r')
Example #7
0
def test_injects_base_instrument():

    with TradingContext(**config):
        exchange = SimulatedExchange()

        assert exchange.base_instrument == 'EURO'
from tensortrade.instruments import *
from tensortrade.exchanges.simulated import SimulatedExchange
from tensortrade.orders import Order, Broker
from tensortrade.orders.recipe import Recipe
from tensortrade.orders.criteria import StopLoss, StopDirection
from tensortrade.wallets import Portfolio, Wallet
from tensortrade.trades import TradeSide, TradeType

PRICE_COLUMN = "close"
data_frame = pd.read_csv("tests/data/input/coinbase-1h-btc-usd.csv")
data_frame.columns = map(str.lower, data_frame.columns)
data_frame = data_frame.rename(columns={'volume btc': 'volume'})

exchange = SimulatedExchange(data_frame=data_frame,
                             price_column=PRICE_COLUMN,
                             randomize_time_slices=True)
broker = Broker(exchange)
broker.reset()


def test_init():
    wallets = [Wallet(exchange, 10000 * USD), Wallet(exchange, 0 * BTC)]
    portfolio = Portfolio(base_instrument=USD, wallets=wallets)
    base_wallet = portfolio.get_wallet(exchange.id, USD)

    quantity = (1 / 10) * base_wallet.balance
    order = Order(side=TradeSide.BUY,
                  trade_type=TradeType.MARKET,
                  pair=USD / BTC,
                  quantity=quantity,
exchange = CCXTExchange(exchange=coinbase, base_instrument='USD')

# RobinhoodExchange and InteractiveBrokersExchange are works in progress and allow you to trade stocks and ETF
# FBMExchnage is a simulated exchange which is simply an implementation of SimulatedExchange

from tensortrade.exchanges.simulated import FBMExchange

exchange = FBMExchange(base_instrument='BTC', timeframe='1h')

import pandas as pd

from tensortrade.exchanges.simulated import SimulatedExchange

df = pd.read_csv('./data/btc_ohclv_1h.csv')

exchange = SimulatedExchange(data_frame=df, base_instrument='USD')

# Feature Pipelines

from tensortrade.features import FeaturePipeline
from tensortrade.features.scalers import MinMaxNormalizer
from tensortrade.features.stationarity import FractionalDifference
from tensortrade.features.indicators import SimpleMovingAverage

price_columns = ['open', 'high', 'low', 'close']

normalize_price = MinMaxNormalizer(price_columns)
moving_averages = SimpleMovingAverage(price_columns)
difference_all = FractionalDifference(difference_order=0.6)

feature_pipeline = FeaturePipeline(
Example #10
0
from tensortrade.features.indicators import TAlibIndicator
from tensortrade.environments import TradingEnvironment
from tensortrade.features import FeaturePipeline
from tensortrade.actions import DiscreteActions
from tensortrade.rewards import SimpleProfit
from tensortrade.strategies import StableBaselinesTradingStrategy
from stable_baselines import PPO2
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

candles = BitmxMinCandle.objects.all().order_by('id')[:1000]
df = pd.DataFrame(list(candles.values()))
# df = pd.read_csv('./data/Coinbase_BTCUSD_1h.csv')
exchange = SimulatedExchange(data_frame=df,
                             base_instrument='USD',
                             window_size=5,
                             should_pretransform_obs=True)
# -------------------------- Feature Pipelines ------------------------#
price_columns = ["open", "high", "low", "close"]
volume_column = ["volume"]
normalized_price = MinMaxNormalizer(price_columns)
normalized_volume = MinMaxNormalizer(volume_column)
sma = SimpleMovingAverage(columns=price_columns, window_size=50)
indicators = TAlibIndicator(
    indicators=["EMA", "RSI", "CCI", "Stochastic", "MACD"],
    lows=[30, -100, 20],
    highs=[70, 100, 80])
difference_all = FractionalDifference(difference_order=0.6)
feature_pipeline = FeaturePipeline(steps=[
    normalized_price, sma, difference_all, normalized_volume, indicators
])