2022-03-20 10:09:33 +01:00
from pathlib import Path
from typing import Union
import json
2022-07-23 15:27:46 +02:00
import re
2022-03-20 10:09:33 +01:00
2022-06-26 17:32:41 +02:00
import pandas as pd
2022-03-20 10:09:33 +01:00
PACKAGE_ROOT = Path ( __file__ ) . parent . parent
#PACKAGE_PARENT = '..'
#SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
#sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
#PACKAGE_ROOT = os.path.dirname(os.path.abspath(__file__))
class App :
""" Globally visible variables. """
# System
loop = None # asyncio main loop
sched = None # Scheduler
analyzer = None # Store and analyze data
# Connector client
client = None
# WebSocket for push notifications
bm = None
conn_key = None # Socket
signal = None , # Latest signal "BUY", "SELL"
#
# State of the server (updated after each interval)
#
# State 0 or None or empty means ok. String and other non empty objects mean error
error_status = 0 # Networks, connections, exceptions etc. what does not allow us to work at all
server_status = 0 # If server allow us to trade (maintenance, down etc.)
account_status = 0 # If account allows us to trade (funds, suspended etc.)
trade_state_status = 0 # Something wrong with our trading logic (wrong use, inconsistent state etc. what we cannot recover)
# Trade status
2022-04-10 19:38:53 +02:00
transaction = None
2022-03-20 10:09:33 +01:00
status = None # BOUGHT, SOLD, BUYING, SELLING
order = None # Latest or current order
order_time = None # Order submission time
# Available assets for trade
# Can be set by the sync/recover function or updated by the trading algorithm
base_quantity = " 0.04108219 " # BTC owned (on account, already bought, available for trade)
quote_quantity = " 1000.0 " # USDT owned (on account, available for trade)
#
# Trader. Status data retrieved from the server. Below are examples only.
#
system_status = { " status " : 0 , " msg " : " normal " } # 0: normal,1:system maintenance
2022-04-18 13:25:25 +02:00
symbol_info = { }
account_info = { }
2022-03-20 10:09:33 +01:00
#
# Constant configuration parameters
#
config = {
" actions " : [ " notify " ] , # Values: notify, trade
# Binance
" api_key " : " " ,
" api_secret " : " " ,
# Telegram
" telegram_bot_token " : " " , # Source address of messages
" telegram_chat_id " : " " , # Destination address of messages
2022-07-17 10:21:42 +02:00
#
# Naming conventions
#
" merge_file_name " : " data " ,
" feature_file_name " : " features " ,
" matrix_file_name " : " matrix " ,
" predict_file_name " : " predictions " , # predict, predict-rolling
2022-08-07 14:04:47 +02:00
" signal_file_name " : " signals " ,
" signal_models_file_name " : " signal_models " ,
2022-07-17 10:21:42 +02:00
2023-03-11 10:05:43 +01:00
" model_folder " : " MODELS " ,
2022-07-17 10:21:42 +02:00
" time_column " : " timestamp " ,
2022-04-17 19:55:22 +02:00
# File locations
2022-07-23 15:27:46 +02:00
" data_folder " : " C:/DATA_ITB " , # Location for all source and generated data/models
2022-07-17 10:21:42 +02:00
# ==============================================
# === DOWNLOADER, MERGER and (online) READER ===
2022-04-17 19:55:22 +02:00
# Symbol determines sub-folder and used in other identifiers
2022-07-17 10:21:42 +02:00
" symbol " : " BTCUSDT " , # BTCUSDT ETHUSDT ^gspc
2022-04-15 21:45:46 +02:00
2022-07-23 15:27:46 +02:00
# This parameter determines the time raster (granularity) for the data
2022-07-17 10:21:42 +02:00
# Currently 1m for binance, and 1d for yahoo are supported (only workdays)
" freq " : " 1m " ,
2022-04-17 19:55:22 +02:00
2022-07-23 15:27:46 +02:00
# This list is used for downloading and then merging data
# "folder" is symbol name for downloading. prefix will be added column names during merge
2022-07-17 10:21:42 +02:00
" data_sources " : [
2022-07-23 15:27:46 +02:00
{ " folder " : " BTCUSDT " , " file " : " klines " , " column_prefix " : " " }
2022-07-17 10:21:42 +02:00
] ,
2022-04-17 19:55:22 +02:00
2022-04-15 11:46:19 +02:00
# ==========================
2022-04-02 11:50:07 +02:00
# === FEATURE GENERATION ===
2022-03-20 10:09:33 +01:00
2022-04-19 19:05:39 +02:00
# What columns to pass to which feature generator and how to prefix its derived features
2022-07-17 10:21:42 +02:00
# Each executes one feature generation function applied to columns with the specified prefix
2022-04-18 13:25:25 +02:00
" feature_sets " : [
2022-07-23 15:27:46 +02:00
{ " column_prefix " : " " , " generator " : " binance_main " , " feature_prefix " : " " }
2022-04-18 13:25:25 +02:00
] ,
2022-07-23 15:27:46 +02:00
# Parameters of some feature generators
# They influence generated feature names (below)
" base_window " : 360 ,
" averaging_windows " : [ 1 , 10 , 60 ] ,
" area_windows " : [ 10 , 60 ] ,
2022-04-02 11:50:07 +02:00
2022-04-19 19:05:39 +02:00
# ========================
# === LABEL GENERATION ===
2022-07-17 10:21:42 +02:00
" label_sets " : [
2022-07-23 15:27:46 +02:00
{ " column_prefix " : " " , " generator " : " highlow " , " feature_prefix " : " " } ,
2022-07-17 10:21:42 +02:00
] ,
# highlow label parameter: max (of high) and min (of low) for this horizon ahead
2022-07-23 15:27:46 +02:00
" highlow_horizon " : 60 , # 1 hour prediction
2022-04-19 19:05:39 +02:00
# ===========================
# === MODEL TRAIN/PREDICT ===
2022-07-17 10:21:42 +02:00
# predict off-line and on-line
2022-04-19 19:05:39 +02:00
2022-07-17 10:21:42 +02:00
# This number of tail rows will be excluded from model training
2022-07-23 15:27:46 +02:00
" label_horizon " : 60 ,
" train_length " : int ( 0.5 * 525_600 ) , # train set maximum size. algorithms may decrease this length
2022-04-02 11:50:07 +02:00
2022-07-23 15:27:46 +02:00
# List all features to be used for training/prediction by selecting them from the result of reature generation
# Remove: "_std_1", "_trend_1"
2022-07-17 10:21:42 +02:00
" train_features " : [
2022-07-23 15:27:46 +02:00
" close_1 " , " close_10 " , " close_60 " ,
" close_std_10 " , " close_std_60 " ,
" volume_1 " , " volume_10 " , " volume_60 " ,
" span_1 " , " span_10 " , " span_60 " ,
" trades_1 " , " trades_10 " , " trades_60 " ,
" tb_base_1 " , " tb_base_10 " , " tb_base_60 " ,
" close_area_10 " , " close_area_60 " ,
" close_trend_10 " , " close_trend_60 " ,
" volume_trend_10 " , " volume_trend_60 "
2022-04-02 11:50:07 +02:00
] ,
2022-04-16 20:30:34 +02:00
2022-07-17 10:21:42 +02:00
# Models (for each algorithm) will be trained for these target labels
2022-03-20 10:09:33 +01:00
" labels " : [
2022-04-15 11:46:19 +02:00
" high_10 " , " high_15 " , " high_20 " , " high_25 " , " high_30 " ,
2022-07-23 15:27:46 +02:00
#"high_01", "high_02", "high_03", "high_04", "high_05",
#"low_01", "low_02", "low_03", "low_04", "low_05",
" low_10 " , " low_15 " , " low_20 " , " low_25 " , " low_30 "
2022-04-02 11:50:07 +02:00
] ,
2022-03-20 10:09:33 +01:00
2022-08-20 11:26:28 +02:00
# algorithm names defined in the model store
" algorithms " : [ " lc " ] ,
2022-07-17 10:21:42 +02:00
# ONLINE (PREDICTION) PARAMETERS
# Minimum history length required to compute derived features
# It is used in online mode where we need to maintain data window of this size or larger
# Take maximum aggregation windows from feature generation code (and add something to be sure that we have all what is needed)
# Basically, should be equal to base_window
" features_horizon " : 10180 ,
2023-02-11 17:50:07 +01:00
# =======================================
# === AGGREGATION AND POST-PROCESSING ===
2022-03-25 22:49:33 +01:00
2023-02-12 11:06:34 +01:00
" score_aggregation " : {
2023-02-11 17:50:07 +01:00
# These ML predicted columns (scores) will be used for aggregation
" buy_labels " : [ " high_10_lc " , " high_15_lc " , " high_20_lc " ] ,
" sell_labels " : [ " low_10_lc " , " low_15_lc " , " low_20_lc " ] ,
2022-03-20 10:09:33 +01:00
2023-03-11 14:37:33 +01:00
" trade_score " : " trade_score " , # Output column name: positive values - buy, negative values - sell
2023-02-05 17:27:37 +01:00
" point_threshold " : None , # Produce boolean column (optional)
" window " : 3 , # Aggregate in time
2023-02-11 13:33:04 +01:00
" combine " : " " , # "no_combine" (or empty), "relative", "difference"
" coefficient " : 1.0 , # Scale the scores to make them symmetric
" constant " : 0.0
2023-02-05 17:27:37 +01:00
} ,
2022-03-25 22:49:33 +01:00
2023-03-05 11:10:52 +01:00
# ================================
# === SIGNAL RULES FOR TRADING ===
2023-02-11 17:50:07 +01:00
" signal_model " : {
2023-02-12 12:38:10 +01:00
" rule_type " : " " , # empty, 'two_dim_rule'
2023-02-11 17:50:07 +01:00
# Rule parameters to decide whether to buy/sell after all aggregations/combinations
2023-03-11 14:37:33 +01:00
" buy_signal_threshold " : 0.1 ,
" sell_signal_threshold " : - 0.1 ,
2023-02-11 17:50:07 +01:00
# To decide whether to notify (can be an option of individual users/consumers)
" buy_notify_threshold " : 0.05 ,
2022-04-19 19:05:39 +02:00
" sell_notify_threshold " : 0.05 ,
2022-03-25 22:49:33 +01:00
2022-04-13 16:34:38 +02:00
" trade_icon_step " : 0.1 , # For each step, one icon added
" notify_frequency_minutes " : 10 , # 1m, 5m, 10m, 15m etc. Minutes will be divided by this number
2022-03-20 10:09:33 +01:00
} ,
2023-03-05 11:10:52 +01:00
" train_signal_model " : {
" buy_sell_equal " : False , # If true, only buy parameters will be used
" grid " : {
# Lists of rule thresholds to test performance
" buy_signal_threshold " : [ 0.1 , 0.2 , 0.3 ] ,
" sell_signal_threshold " : [ - 0.1 , - 0.2 , - 0.3 ]
}
} ,
2022-04-15 11:46:19 +02:00
# =====================
2022-03-20 10:09:33 +01:00
# === TRADER SERVER ===
2022-04-19 19:05:39 +02:00
" base_asset " : " " , # BTC ETH
" quote_asset " : " " ,
2022-03-20 10:09:33 +01:00
" trader " : {
# For debugging: determine what parts of code will be executed
" no_trades_only_data_processing " : False , # in market or out of market processing is excluded (all below parameters ignored)
" test_order_before_submit " : False , # Send test submit to the server as part of validation
" simulate_order_execution " : False , # Instead of real orders, simulate their execution (immediate buy/sell market orders and use high price of klines for limit orders)
" percentage_used_for_trade " : 99 , # in % to the available USDT quantity, that is, we will derive how much BTC to buy using this percentage
" limit_price_adjustment " : - 0.0001 , # Limit price of orders will be better than the latest close price (0 means no change, positive - better for us, negative - worse for us)
# Signal model (trade strategy) - currently NOT USED
" sell_timeout " : 70 , # Seconds
" percentage_sell_price " : 1.018 , # our planned profit per trade via limit sell order (part of the model)
} ,
2022-04-15 11:46:19 +02:00
# ==================
2022-03-20 10:09:33 +01:00
# === COLLECTORS ===
" collector " : {
" folder " : " DATA " ,
" flush_period " : 300 , # seconds
" depth " : {
" folder " : " DEPTH " ,
" symbols " : [ " BTCUSDT " , " ETHBTC " , " ETHUSDT " , " IOTAUSDT " , " IOTABTC " , " IOTAETH " ] ,
" limit " : 100 , # Legal values (depth): '5, 10, 20, 50, 100, 500, 1000, 5000' <100 weight=1
" freq " : " 1m " , # Binance standard frequency: 5s, 1m etc.
} ,
" stream " : {
" folder " : " STREAM " ,
# Stream formats:
# For kline channel: <symbol>@kline_<interval>, Event type: "e": "kline", Symbol: "s": "BNBBTC"
# For depth channel: <symbol>@depth<levels>[@100ms], Event type: NO, Symbol: NO
# btcusdt@ticker
" channels " : [ " kline_1m " , " depth20 " ] , # kline_1m, depth20, depth5
" symbols " : [ " BTCUSDT " , " ETHBTC " , " ETHUSDT " , " IOTAUSDT " , " IOTABTC " , " IOTAETH " ] ,
# "BTCUSDT", "ETHBTC", "ETHUSDT", "IOTAUSDT", "IOTABTC", "IOTAETH"
}
} ,
}
def data_provider_problems_exist ( ) :
if App . error_status != 0 :
return True
if App . server_status != 0 :
return True
return False
def problems_exist ( ) :
if App . error_status != 0 :
return True
if App . server_status != 0 :
return True
if App . account_status != 0 :
return True
if App . trade_state_status != 0 :
return True
return False
def load_config ( config_file ) :
if config_file :
config_file_path = PACKAGE_ROOT / config_file
2022-07-23 15:27:46 +02:00
with open ( config_file_path , encoding = ' utf-8 ' ) as json_file :
#conf_str = json.load(json_file)
conf_str = json_file . read ( )
# Remove everything starting with // and till the line end
conf_str = re . sub ( r " //.*$ " , " " , conf_str , flags = re . M )
conf_json = json . loads ( conf_str )
App . config . update ( conf_json )
2022-03-20 10:09:33 +01:00
if __name__ == " __main__ " :
pass