Files
v2realbot/research/test.ipynb
2024-04-25 06:24:51 +02:00

574 KiB

In [2]:
from v2realbot.tools.loadbatch import load_batch
from v2realbot.utils.utils import zoneNY
import pandas as pd
import numpy as np
import vectorbtpro as vbt

vbt.settings.set_theme("dark")
vbt.settings['plotting']['layout']['width'] = 1280
vbt.settings.plotting.auto_rangebreaks = True
# Set the option to display with pagination
pd.set_option('display.notebook_repr_html', True)
pd.set_option('display.max_rows', 10)  # Number of rows per page

res, df = load_batch(batch_id="e44a5075",
                     space_resolution_evenly=False,
                     indicators_columns=["Rsi14"],
                     main_session_only=True)
if res < 0:
    print("Error" + str(res) + str(df))
df = df["bars"]

#df
Activating profile profile1
Profile profile1 loaded successfully.
Current values:
{
    'AGG_EXCLUDED_TRADES': ['C', 'O', '4', 'B', '7', 'V', 'P', 'W', 'U', 'Z', 'F'],
    'BT_DELAYS': {
        'trigger_to_strat': 0.02,
        'strat_to_sub': 0.023,
        'sub_to_fill': 0.008,
        'fill_to_not': 0.023,
        'limit_order_offset': 0
    },
    'BT_FILL_CONDITION_BUY_LIMIT': <FillCondition.SLOW: 'slow'>,
    'BT_FILL_CONDITION_SELL_LIMIT': <FillCondition.SLOW: 'slow'>,
    'BT_FILL_CONS_TRADES_REQUIRED': 2,
    'BT_FILL_LOG_SURROUNDING_TRADES': 10,
    'BT_FILL_PRICE_MARKET_ORDER_PREMIUM': 0.005,
    'COUNT_API_REQUESTS': False,
    'GROUP_TRADES_WITH_TIMESTAMP_LESS_THAN': 0.003,
    'ILOG_SAVE_LEVEL_FROM': 1,
    'LIVE_DATA_FEED': 'sip',
    'NORMALIZED_TICK_BASE_PRICE': 30.0,
    'OFFLINE_MODE': False,
    'PROD_SERVER_HOSTNAMES': ['tradingeastcoast', 'David-MacBook-Pro.local'],
    'QUIET_MODE': True,
    'TEST_SERVER_HOSTNAMES': ['tradingtest']
}
config_handler.active_profile='profile1'
config handler initialized
Realtime Websocket connection will use FEED: sip and credential of ACCOUNT1
Resolution : 23
NOTE: DUPLICATES 100/3034 in bars. REMOVING.
Now there are 0/2934

filter dates

In [16]:
#naloadujeme do vbt symbol as column
basic_data = vbt.Data.from_data({"BAC": df}, tz_convert=zoneNY)
start_date = pd.Timestamp('2024-03-12 09:30', tz=zoneNY)
end_date = pd.Timestamp('2024-03-13 16:00', tz=zoneNY)

#basic_data = basic_data.transform(lambda df: df[df.index.date == start_date.date()])
basic_data = basic_data.transform(lambda df: df[(df.index >= start_date) & (df.index <= end_date)])
#basic_data.data["BAC"].info()

# fig = basic_data.plot(plot_volume=False)
# pivot_info = basic_data.run("pivotinfo", up_th=0.003, down_th=0.002)
# #pivot_info.plot()
# pivot_info.plot(fig=fig, conf_value_trace_kwargs=dict(visible=True))
# fig.show()


# rsi14 = basic_data.data["BAC"]["Rsi14"].rename("Rsi14")

# rsi14.vbt.plot().show()
# basic_data.data["BAC"].vbt.ohlcv.plot().show()
In [ ]:
@vbt.njit
def long_entry_place_func_nb(c, low, close, time_in_ns, rsi14, window_open, window_close):
    market_open_minutes = 570  # 9 hours * 60 minutes + 30 minutes

    for out_i in range(len(c.out)):
        i = c.from_i + out_i

        current_minutes = vbt.dt_nb.hour_nb(time_in_ns[i]) * 60 + vbt.dt_nb.minute_nb(time_in_ns[i])
        #print("current_minutes", current_minutes)
        # Calculate elapsed minutes since market open at 9:30 AM
        elapsed_from_open = current_minutes - market_open_minutes
        elapsed_from_open = elapsed_from_open if elapsed_from_open >= 0 else 0
        #print( "elapsed_from_open", elapsed_from_open)

        #elapsed_from_open = elapsed_minutes_from_open_nb(time_in_ns) 
        in_window = elapsed_from_open > window_open and elapsed_from_open < window_close
        #print("in_window", in_window)
        # if in_window:
        #     print("in window")

        if in_window and rsi14[i] > 60: # and low[i, c.col] <= hit_price: # and hour == 9:  # (4)!
            return out_i
    return -1

@vbt.njit
def long_exit_place_func_nb(c, high, close, time_index, tp, sl):  # (5)!
    entry_i = c.from_i - c.wait
    entry_price = close[entry_i, c.col]
    hit_price = entry_price * (1 + tp)
    stop_price = entry_price * (1 - sl)
    for out_i in range(len(c.out)):
        i = c.from_i + out_i
        last_bar_of_day = vbt.dt_nb.day_changed_nb(time_index[i], time_index[i + 1])

        #print(next_day)
        if last_bar_of_day: #pokud je dalsi next day, tak zavirame posledni
            print("ted",out_i)
            return out_i
        if close[i, c.col] >= hit_price or close[i, c.col] <= stop_price :
            return out_i
    return -1
In [7]:
df = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij'))

df
Out[7]:
<style scoped=""> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style>
a b c d e f g h i j
0 0.781728 0.268999 0.250692 0.242912 0.624507 0.552550 0.454135 0.680087 0.845730 0.243497
1 0.620733 0.496079 0.426937 0.401734 0.078539 0.438964 0.474857 0.813539 0.738967 0.151170
2 0.076841 0.519632 0.077733 0.243229 0.801078 0.438992 0.207201 0.662062 0.235880 0.606418
3 0.161092 0.546529 0.694200 0.794800 0.237513 0.234853 0.590338 0.716282 0.985255 0.548735
4 0.063619 0.717736 0.636102 0.805387 0.135608 0.688106 0.726477 0.020969 0.204228 0.312697
In [9]:
df.sum()
Out[9]:
a    1.704012
b    2.548974
c    2.085664
d    2.488062
e    1.877245
f    2.353465
g    2.453008
h    2.892939
i    3.010060
j    1.862517
dtype: float64